diff --git a/.vn/scripts/build-scripts.sh b/.vn/scripts/build-scripts.sh index 0648919b..f62f5a89 100755 --- a/.vn/scripts/build-scripts.sh +++ b/.vn/scripts/build-scripts.sh @@ -13,7 +13,9 @@ do fname=`basename "$f"` fname_no_ext=`echo "$fname" | cut -d. -f1` echo "Filename $fname, without ext $fname_no_ext" - yarn run ncc build "$ts_sources_dir/$f" --no-cache --out "$vn_scripts_dir/dist" + # TODO: We use transpile-only because SimpleSchema typings are not correctly loaded, we would + # need to find a way to point to the right declaration file + yarn run ncc build "$ts_sources_dir/$f" --no-cache --out "$vn_scripts_dir/dist" --transpile-only mkdir -p "$vn_scripts_dir/$dname" mv "$vn_scripts_dir/dist/index.js" "$vn_scripts_dir/$dname/$fname_no_ext".js done diff --git a/.vn/scripts/db/reset.js b/.vn/scripts/db/reset.js index 08b1a2e7..18a91c8c 100644 --- a/.vn/scripts/db/reset.js +++ b/.vn/scripts/db/reset.js @@ -1,2095 +1,1366 @@ -/******/ (() => { - // webpackBootstrap - /******/ var __webpack_modules__ = { - /***/ 6071: /***/ ( - __unused_webpack_module, - exports, - __nccwpck_require__ - ) => { - var aws4 = exports, - url = __nccwpck_require__(8835), - querystring = __nccwpck_require__(1191), - crypto = __nccwpck_require__(6417), - lru = __nccwpck_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)); +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ 6071: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +var aws4 = exports, + url = __nccwpck_require__(8835), + querystring = __nccwpck_require__(1191), + crypto = __nccwpck_require__(6417), + lru = __nccwpck_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)) +} + +// A bit of a combination of: +// https://github.com/aws/aws-sdk-java-v2/blob/dc695de6ab49ad03934e1b02e7263abbd2354be0/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAws4Signer.java#L59 +// https://github.com/aws/aws-sdk-js/blob/18cb7e5b463b46239f9fdd4a65e2ff8c81831e8f/lib/signers/v4.js#L191-L199 +// https://github.com/mhart/aws4fetch/blob/b3aed16b6f17384cf36ea33bcba3c1e9f3bdfefd/src/main.js#L25-L34 +var HEADERS_TO_IGNORE = { + 'authorization': true, + 'connection': true, + 'x-amzn-trace-id': true, + 'user-agent': true, + 'expect': true, + 'presigned-expires': true, + 'range': true, +} + +// 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 } + } + } - // A bit of a combination of: - // https://github.com/aws/aws-sdk-java-v2/blob/dc695de6ab49ad03934e1b02e7263abbd2354be0/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAws4Signer.java#L59 - // https://github.com/aws/aws-sdk-js/blob/18cb7e5b463b46239f9fdd4a65e2ff8c81831e8f/lib/signers/v4.js#L191-L199 - // https://github.com/mhart/aws4fetch/blob/b3aed16b6f17384cf36ea33bcba3c1e9f3bdfefd/src/main.js#L25-L34 - var HEADERS_TO_IGNORE = { - authorization: true, - connection: true, - "x-amzn-trace-id": true, - "user-agent": true, - expect: true, - "presigned-expires": true, - range: true, - }; - - // 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(); + return hostParts +} - // 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; +// 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 - this.isCodeCommitGit = - this.service === "codecommit" && request.method === "GIT"; - } + return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts'] + .indexOf(this.service) >= 0 +} - RequestSigner.prototype.matchHost = function (host) { - var match = (host || "").match( - /([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/ - ); - var hostParts = (match || []).slice(1, 3); +RequestSigner.prototype.createHost = function() { + var region = this.isSingleRegion() ? '' : '.' + this.region, + subdomain = this.service === 'ses' ? 'email' : this.service + return subdomain + region + '.amazonaws.com' +} - // 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(); +RequestSigner.prototype.prepareRequest = function() { + this.parsePath() - 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; - } - } - } + var request = this.request, headers = request.headers, query - return hostParts; - }; + if (request.signQuery) { - // 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 - ); - }; + this.parsedPath.query = query = this.parsedPath.query || {} - RequestSigner.prototype.createHost = function () { - var region = this.isSingleRegion() ? "" : "." + this.region, - subdomain = this.service === "ses" ? "email" : this.service; - return subdomain + region + ".amazonaws.com"; - }; + if (this.credentials.sessionToken) + query['X-Amz-Security-Token'] = this.credentials.sessionToken - RequestSigner.prototype.prepareRequest = function () { - this.parsePath(); + if (this.service === 's3' && !query['X-Amz-Expires']) + query['X-Amz-Expires'] = 86400 - var request = this.request, - headers = request.headers, - query; + if (query['X-Amz-Date']) + this.datetime = query['X-Amz-Date'] + else + query['X-Amz-Date'] = this.getDateTime() - if (request.signQuery) { - this.parsedPath.query = query = this.parsedPath.query || {}; + query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256' + query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString() + query['X-Amz-SignedHeaders'] = this.signedHeaders() - if (this.credentials.sessionToken) - query["X-Amz-Security-Token"] = this.credentials.sessionToken; + } else { - if (this.service === "s3" && !query["X-Amz-Expires"]) - query["X-Amz-Expires"] = 86400; + 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 (query["X-Amz-Date"]) this.datetime = query["X-Amz-Date"]; - else query["X-Amz-Date"] = this.getDateTime(); + if (request.body && !headers['Content-Length'] && !headers['content-length']) + headers['Content-Length'] = Buffer.byteLength(request.body) - 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 (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) + headers['X-Amz-Security-Token'] = this.credentials.sessionToken - 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(); - } + if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) + headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex') - delete headers.Authorization; - delete headers.authorization; - } - }; + 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() + } - RequestSigner.prototype.sign = function () { - if (!this.parsedPath) this.prepareRequest(); + delete headers.Authorization + delete headers.authorization + } +} - if (this.request.signQuery) { - this.parsedPath.query["X-Amz-Signature"] = this.signature(); - } else { - this.request.headers.Authorization = this.authHeader(); - } +RequestSigner.prototype.sign = function() { + if (!this.parsedPath) this.prepareRequest() - this.request.path = this.formatPath(); + if (this.request.signQuery) { + this.parsedPath.query['X-Amz-Signature'] = this.signature() + } else { + this.request.headers.Authorization = this.authHeader() + } - return this.request; - }; + this.request.path = this.formatPath() - RequestSigner.prototype.getDateTime = function () { - if (!this.datetime) { - var headers = this.request.headers, - date = new Date(headers.Date || headers.date || new Date()); + return this.request +} - this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, ""); +RequestSigner.prototype.getDateTime = function() { + if (!this.datetime) { + var headers = this.request.headers, + date = new Date(headers.Date || headers.date || new Date) - // 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; - }; + this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '') - RequestSigner.prototype.getDate = function () { - return this.getDateTime().substr(0, 8); - }; + // 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') + } - RequestSigner.prototype.authHeader = function () { - return [ - "AWS4-HMAC-SHA256 Credential=" + - this.credentials.accessKeyId + - "/" + - this.credentialString(), - "SignedHeaders=" + this.signedHeaders(), - "Signature=" + this.signature(), - ].join(", "); - }; + 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, '/') + } - 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"); - }; + 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) + .filter(function(key) { return HEADERS_TO_IGNORE[key.toLowerCase()] == null }) + .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() }) + .filter(function(key) { return HEADERS_TO_IGNORE[key] == null }) + .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.stringToSign = function () { - return [ - "AWS4-HMAC-SHA256", - this.getDateTime(), - this.credentialString(), - hash(this.canonicalString(), "hex"), - ].join("\n"); - }; +RequestSigner.prototype.parsePath = function() { + var path = this.request.path || '/' - 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, "/"); - } + // 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)) + } - return [ - this.request.method || "GET", - pathStr, - queryStr, - this.canonicalHeaders() + "\n", - this.signedHeaders(), - bodyHash, - ].join("\n"); - }; + var queryIx = path.indexOf('?'), + query = null - RequestSigner.prototype.canonicalHeaders = function () { - var headers = this.request.headers; - function trimAll(header) { - return header.toString().trim().replace(/\s+/g, " "); - } - return Object.keys(headers) - .filter(function (key) { - return HEADERS_TO_IGNORE[key.toLowerCase()] == null; - }) - .sort(function (a, b) { - return a.toLowerCase() < b.toLowerCase() ? -1 : 1; - }) - .map(function (key) { - return key.toLowerCase() + ":" + trimAll(headers[key]); - }) - .join("\n"); - }; + if (queryIx >= 0) { + query = querystring.parse(path.slice(queryIx + 1)) + path = path.slice(0, queryIx) + } - RequestSigner.prototype.signedHeaders = function () { - return Object.keys(this.request.headers) - .map(function (key) { - return key.toLowerCase(); - }) - .filter(function (key) { - return HEADERS_TO_IGNORE[key] == null; - }) - .sort() - .join(";"); - }; + this.parsedPath = { + path: path, + query: query, + } +} - RequestSigner.prototype.credentialString = function () { - return [this.getDate(), this.region, this.service, "aws4_request"].join( - "/" - ); - }; +RequestSigner.prototype.formatPath = function() { + var path = this.parsedPath.path, + query = this.parsedPath.query - RequestSigner.prototype.defaultCredentials = function () { - var env = process.env; - return { - accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY, - secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY, - sessionToken: env.AWS_SESSION_TOKEN, - }; - }; + if (!query) return path - RequestSigner.prototype.parsePath = function () { - var path = this.request.path || "/"; + // Services don't support empty query string keys + if (query[''] != null) delete query[''] - // 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)); - } + return path + '?' + encodeRfc3986(querystring.stringify(query)) +} - var queryIx = path.indexOf("?"), - query = null; +aws4.RequestSigner = RequestSigner - if (queryIx >= 0) { - query = querystring.parse(path.slice(queryIx + 1)); - path = path.slice(0, queryIx); - } +aws4.sign = function(request, credentials) { + return new RequestSigner(request, credentials).sign() +} - this.parsedPath = { - path: path, - query: query, - }; - }; - RequestSigner.prototype.formatPath = function () { - var path = this.parsedPath.path, - query = this.parsedPath.query; +/***/ }), - if (!query) return path; +/***/ 4225: +/***/ ((module) => { - // Services don't support empty query string keys - if (query[""] != null) delete query[""]; +module.exports = function(size) { + return new LruCache(size) +} - return path + "?" + encodeRfc3986(querystring.stringify(query)); - }; +function LruCache(size) { + this.capacity = size | 0 + this.map = Object.create(null) + this.list = new DoublyLinkedList() +} - aws4.RequestSigner = RequestSigner; +LruCache.prototype.get = function(key) { + var node = this.map[key] + if (node == null) return undefined + this.used(node) + return node.val +} - aws4.sign = function (request, credentials) { - return new RequestSigner(request, credentials).sign(); - }; +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++ + } +} - /***/ - }, - /***/ 4225: /***/ (module) => { - module.exports = function (size) { - return new LruCache(size); - }; +function DoublyLinkedList() { + this.firstNode = null + this.lastNode = null +} - function LruCache(size) { - this.capacity = size | 0; - this.map = Object.create(null); - this.list = new DoublyLinkedList(); - } +DoublyLinkedList.prototype.moveToFront = function(node) { + if (this.firstNode == node) return - LruCache.prototype.get = function (key) { - var node = this.map[key]; - if (node == null) return undefined; - this.used(node); - return node.val; - }; + this.remove(node) - 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; - }; + 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 + } +} - LruCache.prototype.used = function (node) { - this.list.moveToFront(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 + } +} - 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; - } +function DoublyLinkedNode(key, val) { + this.key = key + this.val = val + this.prev = null + this.next = 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; - } - }; +/***/ 2214: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - DoublyLinkedList.prototype.pop = function () { - var lastNode = this.lastNode; - if (lastNode != null) { - this.remove(lastNode); - } - return lastNode; - }; +"use strict"; - 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; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Binary = void 0; +var buffer_1 = __nccwpck_require__(4293); +var ensure_buffer_1 = __nccwpck_require__(6669); +var uuid_utils_1 = __nccwpck_require__(3152); +var uuid_1 = __nccwpck_require__(2568); +var error_1 = __nccwpck_require__(240); +/** + * A class representation of the BSON Binary type. + * @public + */ +var Binary = /** @class */ (function () { + /** + * @param buffer - a buffer object containing the binary data. + * @param subType - the option binary type. + */ + function Binary(buffer, subType) { + if (!(this instanceof Binary)) + return new Binary(buffer, subType); + if (!(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer)) { + throw new error_1.BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); + } + this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + // create an empty binary buffer + this.buffer = buffer_1.Buffer.alloc(Binary.BUFFER_SIZE); + this.position = 0; } - }; - - function DoublyLinkedNode(key, val) { - this.key = key; - this.val = val; - this.prev = null; - this.next = null; - } - - /***/ - }, - - /***/ 336: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - var DuplexStream = __nccwpck_require__(1642).Duplex, - util = __nccwpck_require__(1669), - Buffer = __nccwpck_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; + else { + if (typeof buffer === 'string') { + // string + this.buffer = buffer_1.Buffer.from(buffer, 'binary'); } - }.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; + else if (Array.isArray(buffer)) { + // number[] + this.buffer = buffer_1.Buffer.from(buffer); + } + else { + // Buffer | TypedArray | ArrayBuffer + this.buffer = ensure_buffer_1.ensureBuffer(buffer); + } + this.position = this.buffer.byteLength; } - 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)); + } + /** + * Updates this binary with byte_value. + * + * @param byteValue - a single byte we wish to write. + */ + Binary.prototype.put = function (byteValue) { + // If it's a string and a has more than one character throw an error + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new error_1.BSONTypeError('only accepts single character String'); } - - 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; + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new error_1.BSONTypeError('only accepts single character Uint8Array or Array'); + // Decode the byte value once + var decodedByte; + if (typeof byteValue === 'string') { + decodedByte = byteValue.charCodeAt(0); } - }; - - BufferList.prototype.get = function get(index) { - if (index > this.length || index < 0) { - return undefined; + else if (typeof byteValue === 'number') { + decodedByte = byteValue; } - 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; + else { + decodedByte = byteValue[0]; } - - // 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 (decodedByte < 0 || decodedByte > 255) { + throw new error_1.BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); } - - 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; + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decodedByte; } - - // 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(); + else { + var buffer = buffer_1.Buffer.alloc(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++] = decodedByte; } - 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; - } + }; + /** + * Writes a buffer or string to the binary. + * + * @param sequence - a string or buffer to be written to the Binary BSON object. + * @param offset - specify the binary of where to write the content. + */ + Binary.prototype.write = function (sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + sequence.length) { + var buffer = buffer_1.Buffer.alloc(this.buffer.length + sequence.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + // Assign the new buffer + this.buffer = buffer; } - 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 (ArrayBuffer.isView(sequence)) { + this.buffer.set(ensure_buffer_1.ensureBuffer(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; } - 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); + else if (typeof sequence === 'string') { + this.buffer.write(sequence, offset, sequence.length, 'binary'); + this.position = + offset + sequence.length > this.position ? offset + sequence.length : this.position; } - - offset = Number(offset || 0); - if (isNaN(offset)) { - offset = 0; + }; + /** + * Reads **length** bytes starting at **position**. + * + * @param position - read from the given position in the Binary. + * @param length - the number of bytes to read. + */ + Binary.prototype.read = function (position, length) { + length = length && length > 0 ? length : this.position; + // Let's return the data based on the type we have + return this.buffer.slice(position, position + length); + }; + /** + * Returns the value of this binary as a string. + * @param asRaw - Will skip converting to a string + * @remarks + * This is handy when calling this function conditionally for some key value pairs and not others + */ + Binary.prototype.value = function (asRaw) { + asRaw = !!asRaw; + // Optimize to serialize for the situation where the data == size of buffer + if (asRaw && this.buffer.length === this.position) { + return this.buffer; } - - if (offset < 0) { - offset = this.length + offset; + // If it's a node.js buffer object + if (asRaw) { + return this.buffer.slice(0, this.position); } - - if (offset < 0) { - offset = 0; + return this.buffer.toString('binary', 0, this.position); + }; + /** the length of the binary sequence */ + Binary.prototype.length = function () { + return this.position; + }; + Binary.prototype.toJSON = function () { + return this.buffer.toString('base64'); + }; + Binary.prototype.toString = function (format) { + return this.buffer.toString(format); + }; + /** @internal */ + Binary.prototype.toExtendedJSON = function (options) { + options = options || {}; + var base64String = this.buffer.toString('base64'); + var subType = Number(this.sub_type).toString(16); + if (options.legacy) { + return { + $binary: base64String, + $type: subType.length === 1 ? '0' + subType : subType + }; } - - if (search.length === 0) { - return offset > this.length ? this.length : offset; + return { + $binary: { + base64: base64String, + subType: subType.length === 1 ? '0' + subType : subType + } + }; + }; + Binary.prototype.toUUID = function () { + if (this.sub_type === Binary.SUBTYPE_UUID) { + return new uuid_1.UUID(this.buffer.slice(0, this.position)); } - - 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++; + throw new error_1.BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported."); + }; + /** @internal */ + Binary.fromExtendedJSON = function (doc, options) { + options = options || {}; + var data; + var type; + if ('$binary' in doc) { + if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { + type = doc.$type ? parseInt(doc.$type, 16) : 0; + data = buffer_1.Buffer.from(doc.$binary, 'base64'); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = buffer_1.Buffer.from(doc.$binary.base64, 'base64'); + } } - } - buffOffset = 0; } - return -1; - }; - - BufferList.prototype._match = function (offset, search) { - if (this.length - offset < search.length) { - return false; + else if ('$uuid' in doc) { + type = 4; + data = uuid_utils_1.uuidHexStringToBuffer(doc.$uuid); } - for ( - var searchOffset = 0; - searchOffset < search.length; - searchOffset++ - ) { - if (this.get(offset + searchOffset) !== search[searchOffset]) { - return false; - } + if (!data) { + throw new error_1.BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc)); } - 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, - __nccwpck_require__ - ) => { - var BSON = __nccwpck_require__(6800), - Binary = __nccwpck_require__(5497), - Code = __nccwpck_require__(7113), - DBRef = __nccwpck_require__(3797), - Decimal128 = __nccwpck_require__(414), - Double = __nccwpck_require__(972), - Int32 = __nccwpck_require__(6142), - Long = __nccwpck_require__(8522), - Map = __nccwpck_require__(3639), - MaxKey = __nccwpck_require__(5846), - MinKey = __nccwpck_require__(5325), - ObjectId = __nccwpck_require__(9502), - BSONRegExp = __nccwpck_require__(4636), - Symbol = __nccwpck_require__(2259), - Timestamp = __nccwpck_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, - __nccwpck_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 = __nccwpck_require__(4293).Buffer; // TODO just use global Buffer - } - - var utils = __nccwpck_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, - __nccwpck_require__ - ) => { - "use strict"; - - var Map = __nccwpck_require__(3639), - Long = __nccwpck_require__(8522), - Double = __nccwpck_require__(972), - Timestamp = __nccwpck_require__(1031), - ObjectID = __nccwpck_require__(9502), - BSONRegExp = __nccwpck_require__(4636), - Symbol = __nccwpck_require__(2259), - Int32 = __nccwpck_require__(6142), - Code = __nccwpck_require__(7113), - Decimal128 = __nccwpck_require__(414), - MinKey = __nccwpck_require__(5325), - MaxKey = __nccwpck_require__(5846), - DBRef = __nccwpck_require__(3797), - Binary = __nccwpck_require__(5497); - - // Parts of the parser - var deserialize = __nccwpck_require__(2139), - serializer = __nccwpck_require__(9290), - calculateObjectSize = __nccwpck_require__(1273), - utils = __nccwpck_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"; + return new Binary(data, type); + }; + /** @internal */ + Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Binary.prototype.inspect = function () { + var asBuffer = this.value(true); + return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")"; + }; + /** + * Binary default subtype + * @internal + */ + Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** Initial buffer default size */ + Binary.BUFFER_SIZE = 256; + /** Default BSON type */ + Binary.SUBTYPE_DEFAULT = 0; + /** Function BSON type */ + Binary.SUBTYPE_FUNCTION = 1; + /** Byte Array BSON type */ + Binary.SUBTYPE_BYTE_ARRAY = 2; + /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */ + Binary.SUBTYPE_UUID_OLD = 3; + /** UUID BSON type */ + Binary.SUBTYPE_UUID = 4; + /** MD5 BSON type */ + Binary.SUBTYPE_MD5 = 5; + /** Encrypted BSON type */ + Binary.SUBTYPE_ENCRYPTED = 6; + /** Column BSON type */ + Binary.SUBTYPE_COLUMN = 7; + /** User BSON type */ + Binary.SUBTYPE_USER_DEFINED = 128; + return Binary; +}()); +exports.Binary = Binary; +Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' }); +//# sourceMappingURL=binary.js.map + +/***/ }), + +/***/ 1960: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BSONRegExp = exports.MaxKey = exports.MinKey = exports.Int32 = exports.Double = exports.Timestamp = exports.Long = exports.UUID = exports.ObjectId = exports.Binary = exports.DBRef = exports.BSONSymbol = exports.Map = exports.Code = exports.LongWithoutOverridesClass = exports.EJSON = exports.BSON_INT64_MIN = exports.BSON_INT64_MAX = exports.BSON_INT32_MIN = exports.BSON_INT32_MAX = exports.BSON_DATA_UNDEFINED = exports.BSON_DATA_TIMESTAMP = exports.BSON_DATA_SYMBOL = exports.BSON_DATA_STRING = exports.BSON_DATA_REGEXP = exports.BSON_DATA_OID = exports.BSON_DATA_OBJECT = exports.BSON_DATA_NUMBER = exports.BSON_DATA_NULL = exports.BSON_DATA_MIN_KEY = exports.BSON_DATA_MAX_KEY = exports.BSON_DATA_LONG = exports.BSON_DATA_INT = exports.BSON_DATA_DECIMAL128 = exports.BSON_DATA_DBPOINTER = exports.BSON_DATA_DATE = exports.BSON_DATA_CODE_W_SCOPE = exports.BSON_DATA_CODE = exports.BSON_DATA_BOOLEAN = exports.BSON_DATA_BINARY = exports.BSON_DATA_ARRAY = exports.BSON_BINARY_SUBTYPE_COLUMN = exports.BSON_BINARY_SUBTYPE_ENCRYPTED = exports.BSON_BINARY_SUBTYPE_UUID_NEW = exports.BSON_BINARY_SUBTYPE_UUID = exports.BSON_BINARY_SUBTYPE_USER_DEFINED = exports.BSON_BINARY_SUBTYPE_MD5 = exports.BSON_BINARY_SUBTYPE_FUNCTION = exports.BSON_BINARY_SUBTYPE_DEFAULT = exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = void 0; +exports.deserializeStream = exports.calculateObjectSize = exports.deserialize = exports.serializeWithBufferAndIndex = exports.serialize = exports.setInternalBufferSize = exports.BSONTypeError = exports.BSONError = exports.ObjectID = exports.Decimal128 = void 0; +var buffer_1 = __nccwpck_require__(4293); +var binary_1 = __nccwpck_require__(2214); +Object.defineProperty(exports, "Binary", ({ enumerable: true, get: function () { return binary_1.Binary; } })); +var code_1 = __nccwpck_require__(2393); +Object.defineProperty(exports, "Code", ({ enumerable: true, get: function () { return code_1.Code; } })); +var db_ref_1 = __nccwpck_require__(6528); +Object.defineProperty(exports, "DBRef", ({ enumerable: true, get: function () { return db_ref_1.DBRef; } })); +var decimal128_1 = __nccwpck_require__(3640); +Object.defineProperty(exports, "Decimal128", ({ enumerable: true, get: function () { return decimal128_1.Decimal128; } })); +var double_1 = __nccwpck_require__(9732); +Object.defineProperty(exports, "Double", ({ enumerable: true, get: function () { return double_1.Double; } })); +var ensure_buffer_1 = __nccwpck_require__(6669); +var extended_json_1 = __nccwpck_require__(6602); +var int_32_1 = __nccwpck_require__(8070); +Object.defineProperty(exports, "Int32", ({ enumerable: true, get: function () { return int_32_1.Int32; } })); +var long_1 = __nccwpck_require__(2332); +Object.defineProperty(exports, "Long", ({ enumerable: true, get: function () { return long_1.Long; } })); +var map_1 = __nccwpck_require__(2935); +Object.defineProperty(exports, "Map", ({ enumerable: true, get: function () { return map_1.Map; } })); +var max_key_1 = __nccwpck_require__(2281); +Object.defineProperty(exports, "MaxKey", ({ enumerable: true, get: function () { return max_key_1.MaxKey; } })); +var min_key_1 = __nccwpck_require__(5508); +Object.defineProperty(exports, "MinKey", ({ enumerable: true, get: function () { return min_key_1.MinKey; } })); +var objectid_1 = __nccwpck_require__(1248); +Object.defineProperty(exports, "ObjectId", ({ enumerable: true, get: function () { return objectid_1.ObjectId; } })); +Object.defineProperty(exports, "ObjectID", ({ enumerable: true, get: function () { return objectid_1.ObjectId; } })); +var error_1 = __nccwpck_require__(240); +var calculate_size_1 = __nccwpck_require__(7426); +// Parts of the parser +var deserializer_1 = __nccwpck_require__(719); +var serializer_1 = __nccwpck_require__(673); +var regexp_1 = __nccwpck_require__(7709); +Object.defineProperty(exports, "BSONRegExp", ({ enumerable: true, get: function () { return regexp_1.BSONRegExp; } })); +var symbol_1 = __nccwpck_require__(2922); +Object.defineProperty(exports, "BSONSymbol", ({ enumerable: true, get: function () { return symbol_1.BSONSymbol; } })); +var timestamp_1 = __nccwpck_require__(7431); +Object.defineProperty(exports, "Timestamp", ({ enumerable: true, get: function () { return timestamp_1.Timestamp; } })); +var uuid_1 = __nccwpck_require__(2568); +Object.defineProperty(exports, "UUID", ({ enumerable: true, get: function () { return uuid_1.UUID; } })); +var constants_1 = __nccwpck_require__(5419); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_BYTE_ARRAY", ({ enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_BYTE_ARRAY; } })); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_DEFAULT", ({ enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_DEFAULT; } })); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_FUNCTION", ({ enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_FUNCTION; } })); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_MD5", ({ enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_MD5; } })); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_USER_DEFINED", ({ enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_USER_DEFINED; } })); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_UUID", ({ enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_UUID; } })); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_UUID_NEW", ({ enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_UUID_NEW; } })); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_ENCRYPTED", ({ enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_ENCRYPTED; } })); +Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_COLUMN", ({ enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_COLUMN; } })); +Object.defineProperty(exports, "BSON_DATA_ARRAY", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_ARRAY; } })); +Object.defineProperty(exports, "BSON_DATA_BINARY", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_BINARY; } })); +Object.defineProperty(exports, "BSON_DATA_BOOLEAN", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_BOOLEAN; } })); +Object.defineProperty(exports, "BSON_DATA_CODE", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_CODE; } })); +Object.defineProperty(exports, "BSON_DATA_CODE_W_SCOPE", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_CODE_W_SCOPE; } })); +Object.defineProperty(exports, "BSON_DATA_DATE", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_DATE; } })); +Object.defineProperty(exports, "BSON_DATA_DBPOINTER", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_DBPOINTER; } })); +Object.defineProperty(exports, "BSON_DATA_DECIMAL128", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_DECIMAL128; } })); +Object.defineProperty(exports, "BSON_DATA_INT", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_INT; } })); +Object.defineProperty(exports, "BSON_DATA_LONG", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_LONG; } })); +Object.defineProperty(exports, "BSON_DATA_MAX_KEY", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_MAX_KEY; } })); +Object.defineProperty(exports, "BSON_DATA_MIN_KEY", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_MIN_KEY; } })); +Object.defineProperty(exports, "BSON_DATA_NULL", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_NULL; } })); +Object.defineProperty(exports, "BSON_DATA_NUMBER", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_NUMBER; } })); +Object.defineProperty(exports, "BSON_DATA_OBJECT", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_OBJECT; } })); +Object.defineProperty(exports, "BSON_DATA_OID", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_OID; } })); +Object.defineProperty(exports, "BSON_DATA_REGEXP", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_REGEXP; } })); +Object.defineProperty(exports, "BSON_DATA_STRING", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_STRING; } })); +Object.defineProperty(exports, "BSON_DATA_SYMBOL", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_SYMBOL; } })); +Object.defineProperty(exports, "BSON_DATA_TIMESTAMP", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_TIMESTAMP; } })); +Object.defineProperty(exports, "BSON_DATA_UNDEFINED", ({ enumerable: true, get: function () { return constants_1.BSON_DATA_UNDEFINED; } })); +Object.defineProperty(exports, "BSON_INT32_MAX", ({ enumerable: true, get: function () { return constants_1.BSON_INT32_MAX; } })); +Object.defineProperty(exports, "BSON_INT32_MIN", ({ enumerable: true, get: function () { return constants_1.BSON_INT32_MIN; } })); +Object.defineProperty(exports, "BSON_INT64_MAX", ({ enumerable: true, get: function () { return constants_1.BSON_INT64_MAX; } })); +Object.defineProperty(exports, "BSON_INT64_MIN", ({ enumerable: true, get: function () { return constants_1.BSON_INT64_MIN; } })); +var extended_json_2 = __nccwpck_require__(6602); +Object.defineProperty(exports, "EJSON", ({ enumerable: true, get: function () { return extended_json_2.EJSON; } })); +var timestamp_2 = __nccwpck_require__(7431); +Object.defineProperty(exports, "LongWithoutOverridesClass", ({ enumerable: true, get: function () { return timestamp_2.LongWithoutOverridesClass; } })); +var error_2 = __nccwpck_require__(240); +Object.defineProperty(exports, "BSONError", ({ enumerable: true, get: function () { return error_2.BSONError; } })); +Object.defineProperty(exports, "BSONTypeError", ({ enumerable: true, get: function () { return error_2.BSONTypeError; } })); +/** @internal */ +// Default Max Size +var MAXSIZE = 1024 * 1024 * 17; +// Current Internal Temporary Serialization Buffer +var buffer = buffer_1.Buffer.alloc(MAXSIZE); +/** + * Sets the size of the internal serialization buffer. + * + * @param size - The desired size for the internal serialization buffer + * @public + */ +function setInternalBufferSize(size) { + // Resize the internal serialization buffer if needed + if (buffer.length < size) { + buffer = buffer_1.Buffer.alloc(size); + } +} +exports.setInternalBufferSize = setInternalBufferSize; +/** + * Serialize a Javascript object. + * + * @param object - the Javascript object to serialize. + * @returns Buffer object containing the serialized object. + * @public + */ +function serialize(object, options) { + if (options === void 0) { 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 = buffer_1.Buffer.alloc(minInternalBufferSize); + } + // Attempt to serialize + var serializationIndex = serializer_1.serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); + // Create the final buffer + var finishedBuffer = buffer_1.Buffer.alloc(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; +} +exports.serialize = serialize; +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, + * useful when pre-allocating the space for serialization. + * + * @param object - the Javascript object to serialize. + * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object. + * @returns the index pointing to the last written byte in the buffer. + * @public + */ +function serializeWithBufferAndIndex(object, finalBuffer, options) { + if (options === void 0) { 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_1.serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined); + buffer.copy(finalBuffer, startIndex, 0, serializationIndex); + // Return the index + return startIndex + serializationIndex - 1; +} +exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; +/** + * Deserialize data as BSON. + * + * @param buffer - the buffer containing the serialized set of BSON documents. + * @returns returns the deserialized Javascript Object. + * @public + */ +function deserialize(buffer, options) { + if (options === void 0) { options = {}; } + return deserializer_1.deserialize(buffer instanceof buffer_1.Buffer ? buffer : ensure_buffer_1.ensureBuffer(buffer), options); +} +exports.deserialize = deserialize; +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param object - the Javascript object to calculate the BSON byte size for + * @returns size of BSON object in bytes + * @public + */ +function calculateObjectSize(object, options) { + if (options === void 0) { options = {}; } + options = options || {}; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + return calculate_size_1.calculateObjectSize(object, serializeFunctions, ignoreUndefined); +} +exports.calculateObjectSize = calculateObjectSize; +/** + * Deserialize stream data as BSON documents. + * + * @param data - the buffer containing the serialized set of BSON documents. + * @param startIndex - the start index in the data Buffer where the deserialization is to start. + * @param numberOfDocuments - number of documents to deserialize. + * @param documents - an array where to store the deserialized documents. + * @param docStartIndex - the index in the documents array from where to start inserting documents. + * @param options - additional options used for the deserialization. + * @returns next index in the buffer after deserialization **x** numbers of documents. + * @public + */ +function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + var bufferData = ensure_buffer_1.ensureBuffer(data); + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = bufferData[index] | + (bufferData[index + 1] << 8) | + (bufferData[index + 2] << 16) | + (bufferData[index + 3] << 24); + // Update options with index + internalOptions.index = index; + // Parse the document at this point + documents[docStartIndex + i] = deserializer_1.deserialize(bufferData, internalOptions); + // Adjust index by the document size + index = index + size; + } + // Return object containing end index of parsing and list of documents + return index; +} +exports.deserializeStream = deserializeStream; +/** + * BSON default export + * @deprecated Please use named exports + * @privateRemarks + * We want to someday deprecate the default export, + * so none of the new TS types are being exported on the default + * @public + */ +var BSON = { + Binary: binary_1.Binary, + Code: code_1.Code, + DBRef: db_ref_1.DBRef, + Decimal128: decimal128_1.Decimal128, + Double: double_1.Double, + Int32: int_32_1.Int32, + Long: long_1.Long, + UUID: uuid_1.UUID, + Map: map_1.Map, + MaxKey: max_key_1.MaxKey, + MinKey: min_key_1.MinKey, + ObjectId: objectid_1.ObjectId, + ObjectID: objectid_1.ObjectId, + BSONRegExp: regexp_1.BSONRegExp, + BSONSymbol: symbol_1.BSONSymbol, + Timestamp: timestamp_1.Timestamp, + EJSON: extended_json_1.EJSON, + setInternalBufferSize: setInternalBufferSize, + serialize: serialize, + serializeWithBufferAndIndex: serializeWithBufferAndIndex, + deserialize: deserialize, + calculateObjectSize: calculateObjectSize, + deserializeStream: deserializeStream, + BSONError: error_1.BSONError, + BSONTypeError: error_1.BSONTypeError +}; +exports.default = BSON; +//# sourceMappingURL=bson.js.map + +/***/ }), + +/***/ 2393: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Code = void 0; +/** + * A class representation of the BSON Code type. + * @public + */ +var Code = /** @class */ (function () { + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + function Code(code, scope) { + if (!(this instanceof Code)) + return new Code(code, scope); 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; + } + Code.prototype.toJSON = function () { + return { code: this.code, scope: this.scope }; + }; + /** @internal */ + Code.prototype.toExtendedJSON = function () { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + }; + /** @internal */ + Code.fromExtendedJSON = function (doc) { + return new Code(doc.$code, doc.$scope); + }; + /** @internal */ + Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Code.prototype.inspect = function () { + var codeJson = this.toJSON(); + return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")"; + }; + return Code; +}()); +exports.Code = Code; +Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' }); +//# sourceMappingURL=code.js.map + +/***/ }), + +/***/ 5419: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BSON_BINARY_SUBTYPE_USER_DEFINED = exports.BSON_BINARY_SUBTYPE_COLUMN = exports.BSON_BINARY_SUBTYPE_ENCRYPTED = exports.BSON_BINARY_SUBTYPE_MD5 = exports.BSON_BINARY_SUBTYPE_UUID_NEW = exports.BSON_BINARY_SUBTYPE_UUID = exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = exports.BSON_BINARY_SUBTYPE_FUNCTION = exports.BSON_BINARY_SUBTYPE_DEFAULT = exports.BSON_DATA_MAX_KEY = exports.BSON_DATA_MIN_KEY = exports.BSON_DATA_DECIMAL128 = exports.BSON_DATA_LONG = exports.BSON_DATA_TIMESTAMP = exports.BSON_DATA_INT = exports.BSON_DATA_CODE_W_SCOPE = exports.BSON_DATA_SYMBOL = exports.BSON_DATA_CODE = exports.BSON_DATA_DBPOINTER = exports.BSON_DATA_REGEXP = exports.BSON_DATA_NULL = exports.BSON_DATA_DATE = exports.BSON_DATA_BOOLEAN = exports.BSON_DATA_OID = exports.BSON_DATA_UNDEFINED = exports.BSON_DATA_BINARY = exports.BSON_DATA_ARRAY = exports.BSON_DATA_OBJECT = exports.BSON_DATA_STRING = exports.BSON_DATA_NUMBER = exports.JS_INT_MIN = exports.JS_INT_MAX = exports.BSON_INT64_MIN = exports.BSON_INT64_MAX = exports.BSON_INT32_MIN = exports.BSON_INT32_MAX = void 0; +/** @internal */ +exports.BSON_INT32_MAX = 0x7fffffff; +/** @internal */ +exports.BSON_INT32_MIN = -0x80000000; +/** @internal */ +exports.BSON_INT64_MAX = Math.pow(2, 63) - 1; +/** @internal */ +exports.BSON_INT64_MIN = -Math.pow(2, 63); +/** + * Any integer up to 2^53 can be precisely represented by a double. + * @internal + */ +exports.JS_INT_MAX = Math.pow(2, 53); +/** + * Any integer down to -2^53 can be precisely represented by a double. + * @internal + */ +exports.JS_INT_MIN = -Math.pow(2, 53); +/** Number BSON Type @internal */ +exports.BSON_DATA_NUMBER = 1; +/** String BSON Type @internal */ +exports.BSON_DATA_STRING = 2; +/** Object BSON Type @internal */ +exports.BSON_DATA_OBJECT = 3; +/** Array BSON Type @internal */ +exports.BSON_DATA_ARRAY = 4; +/** Binary BSON Type @internal */ +exports.BSON_DATA_BINARY = 5; +/** Binary BSON Type @internal */ +exports.BSON_DATA_UNDEFINED = 6; +/** ObjectId BSON Type @internal */ +exports.BSON_DATA_OID = 7; +/** Boolean BSON Type @internal */ +exports.BSON_DATA_BOOLEAN = 8; +/** Date BSON Type @internal */ +exports.BSON_DATA_DATE = 9; +/** null BSON Type @internal */ +exports.BSON_DATA_NULL = 10; +/** RegExp BSON Type @internal */ +exports.BSON_DATA_REGEXP = 11; +/** Code BSON Type @internal */ +exports.BSON_DATA_DBPOINTER = 12; +/** Code BSON Type @internal */ +exports.BSON_DATA_CODE = 13; +/** Symbol BSON Type @internal */ +exports.BSON_DATA_SYMBOL = 14; +/** Code with Scope BSON Type @internal */ +exports.BSON_DATA_CODE_W_SCOPE = 15; +/** 32 bit Integer BSON Type @internal */ +exports.BSON_DATA_INT = 16; +/** Timestamp BSON Type @internal */ +exports.BSON_DATA_TIMESTAMP = 17; +/** Long BSON Type @internal */ +exports.BSON_DATA_LONG = 18; +/** Decimal128 BSON Type @internal */ +exports.BSON_DATA_DECIMAL128 = 19; +/** MinKey BSON Type @internal */ +exports.BSON_DATA_MIN_KEY = 0xff; +/** MaxKey BSON Type @internal */ +exports.BSON_DATA_MAX_KEY = 0x7f; +/** Binary Default Type @internal */ +exports.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** Binary Function Type @internal */ +exports.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** Binary Byte Array Type @internal */ +exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ +exports.BSON_BINARY_SUBTYPE_UUID = 3; +/** Binary UUID Type @internal */ +exports.BSON_BINARY_SUBTYPE_UUID_NEW = 4; +/** Binary MD5 Type @internal */ +exports.BSON_BINARY_SUBTYPE_MD5 = 5; +/** Encrypted BSON type @internal */ +exports.BSON_BINARY_SUBTYPE_ENCRYPTED = 6; +/** Column BSON type @internal */ +exports.BSON_BINARY_SUBTYPE_COLUMN = 7; +/** Binary User Defined Type @internal */ +exports.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; +//# sourceMappingURL=constants.js.map + +/***/ }), + +/***/ 6528: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DBRef = exports.isDBRefLike = void 0; +var utils_1 = __nccwpck_require__(4419); +/** @internal */ +function isDBRefLike(value) { + return (utils_1.isObjectLike(value) && + value.$id != null && + typeof value.$ref === 'string' && + (value.$db == null || typeof value.$db === 'string')); +} +exports.isDBRefLike = isDBRefLike; +/** + * A class representation of the BSON DBRef type. + * @public + */ +var DBRef = /** @class */ (function () { + /** + * @param collection - the collection name. + * @param oid - the reference ObjectId. + * @param db - optional db name, if omitted the reference is local to the current db. + */ + function DBRef(collection, oid, db, fields) { + if (!(this instanceof DBRef)) + return new DBRef(collection, oid, db, fields); + // check if namespace has been provided + var parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + collection = parts.shift(); + } + this.collection = collection; 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, + this.fields = fields || {}; + } + Object.defineProperty(DBRef.prototype, "namespace", { + // Property provided for compatibility with the 1.x parser + // the 1.x parser used a "namespace" property, while 4.x uses "collection" + /** @internal */ + get: function () { + return this.collection; + }, + set: function (value) { + this.collection = value; + }, + enumerable: false, + configurable: true + }); + DBRef.prototype.toJSON = function () { + var o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + }; + /** @internal */ + DBRef.prototype.toExtendedJSON = function (options) { + options = options || {}; + var o = { + $ref: this.collection, + $id: this.oid }; - }; - - module.exports = DBRef; - module.exports.DBRef = DBRef; - - /***/ - }, - - /***/ 414: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - var Long = __nccwpck_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 = __nccwpck_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); + if (options.legacy) { + return o; } - + if (this.db) + o.$db = this.db; + o = Object.assign(o, this.fields); + return o; + }; + /** @internal */ + DBRef.fromExtendedJSON = function (doc) { + var copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + }; + /** @internal */ + DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + DBRef.prototype.inspect = function () { + // NOTE: if OID is an ObjectId class it will just print the oid string. + var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); + return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")"; + }; + return DBRef; +}()); +exports.DBRef = DBRef; +Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' }); +//# sourceMappingURL=db_ref.js.map + +/***/ }), + +/***/ 3640: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Decimal128 = void 0; +var buffer_1 = __nccwpck_require__(4293); +var error_1 = __nccwpck_require__(240); +var long_1 = __nccwpck_require__(2332); +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+)?$/; +// 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; +// Detect if the value is a digit +function isDigit(value) { + return !isNaN(parseInt(value, 10)); +} +// Divide two uint128 values +function divideu128(value) { + var DIVISOR = long_1.Long.fromNumber(1000 * 1000 * 1000); + var _rem = long_1.Long.fromNumber(0); + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { 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) }; + } + for (var 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_1.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 +function multiply64x2(left, right) { + if (!left && !right) { + return { high: long_1.Long.fromNumber(0), low: long_1.Long.fromNumber(0) }; + } + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new long_1.Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new long_1.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_1.Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new long_1.Long(productLow.getLowBits(), 0)); + // Return the 128 bit result + return { high: productHigh, low: productLow }; +} +function lessThan(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; +} +function invalidErr(string, message) { + throw new error_1.BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message); +} +/** + * A class representation of the BSON Decimal128 type. + * @public + */ +var Decimal128 = /** @class */ (function () { + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + function Decimal128(bytes) { + if (!(this instanceof Decimal128)) + return new Decimal128(bytes); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; } - - 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; + else { + this.bytes = bytes; } - - 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) { + } + /** + * Create a Decimal128 instance from a string representation + * + * @param representation - a numeric string representation. + */ + Decimal128.fromString = function (representation) { // 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 @@ -2100,7 +1371,6 @@ 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 @@ -2111,581 +1381,433 @@ 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]; + var significandHigh = new long_1.Long(0, 0); // The low 17 digits of the significand - var significandLow = [0, 0]; + var significandLow = new long_1.Long(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: 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"); + if (representation.length >= 7000) { + throw new error_1.BSONTypeError('' + representation + ' 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); - + var stringMatch = representation.match(PARSE_STRING_REGEXP); + var infMatch = representation.match(PARSE_INF_REGEXP); + var nanMatch = representation.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"); + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new error_1.BSONTypeError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + // full_match = stringMatch[0] + // sign = stringMatch[1] + var unsignedNumber = stringMatch[2]; + // stringMatch[3] is undefined if a whole number (ex "1", 12") + // but defined if a number w/ decimal in it (ex "1.0, 12.2") + var e = stringMatch[4]; + var expSign = stringMatch[5]; + var expNumber = stringMatch[6]; + // they provided e, but didn't give an exponent number. for ex "1e" + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + // they provided e, but didn't give a number before it. for ex "e1" + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } } - // Get the negative or positive sign - if (string[index] === "+" || string[index] === "-") { - isNegative = string[index++] === "-"; + if (representation[index] === '+' || representation[index] === '-') { + isNegative = representation[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)); - } + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(buffer_1.Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + else if (representation[index] === 'N') { + return new Decimal128(buffer_1.Buffer.from(NAN_BUFFER)); + } } - // Read all the digits - while (isDigit(string[index]) || string[index] === ".") { - if (string[index] === ".") { - if (sawRadix) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); + while (isDigit(representation[index]) || representation[index] === '.') { + if (representation[index] === '.') { + if (sawRadix) + invalidErr(representation, 'contains multiple periods'); + sawRadix = true; + index = index + 1; + continue; } - - 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 (nDigitsStored < 34) { + if (representation[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + foundNonZero = true; + // Only store 34 digits + digits[digitsInsert++] = parseInt(representation[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"); + if (foundNonZero) + nDigits = nDigits + 1; + if (sawRadix) + radixPosition = radixPosition + 1; + nDigitsRead = nDigitsRead + 1; + index = index + 1; } - + if (sawRadix && !nDigitsRead) + throw new error_1.BSONTypeError('' + representation + ' 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; + if (representation[index] === 'e' || representation[index] === 'E') { + // Read exponent digits + var match = representation.substr(++index).match(EXPONENT_REGEX); + // No digits read + if (!match || !match[2]) + return new Decimal128(buffer_1.Buffer.from(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)); - } - + if (representation[index]) + return new Decimal128(buffer_1.Buffer.from(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; + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } + else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + if (significantDigits !== 1) { + while (digits[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; + 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 - ) - ); + // 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; + } + invalidErr(representation, 'overflow'); } - } - - exponent = exponent - 1; + 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 - ) - ); + // Shift last digit. can only do this if < significant digits than # stored. + if (lastDigit === 0 && significantDigits < nDigitsStored) { + 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 + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); } - } } - // 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 (lastDigit - firstDigit + 1 < significantDigits) { + 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) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + // if negative, we need to increment again to account for - sign at start. + if (isNegative) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + if (roundDigit >= 5) { + roundBit = 1; + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(representation[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 - ) - ); - } + 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(buffer_1.Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } } - } else { - break; - } } - } } - // Encode significand // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); + significandHigh = long_1.Long.fromNumber(0); // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - + significandLow = long_1.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])); - } + significandHigh = long_1.Long.fromNumber(0); + significandLow = long_1.Long.fromNumber(0); } - - var significand = multiply64x2( - significandHigh, - Long.fromString("100000000000000000") - ); - + else if (lastDigit - firstDigit < 17) { + var dIdx = firstDigit; + significandLow = long_1.Long.fromNumber(digits[dIdx++]); + significandHigh = new long_1.Long(0, 0); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(long_1.Long.fromNumber(10)); + significandLow = significandLow.add(long_1.Long.fromNumber(digits[dIdx])); + } + } + else { + var dIdx = firstDigit; + significandHigh = long_1.Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(long_1.Long.fromNumber(10)); + significandHigh = significandHigh.add(long_1.Long.fromNumber(digits[dIdx])); + } + significandLow = long_1.Long.fromNumber(digits[dIdx++]); + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(long_1.Long.fromNumber(10)); + significandLow = significandLow.add(long_1.Long.fromNumber(digits[dIdx])); + } + } + var significand = multiply64x2(significandHigh, long_1.Long.fromString('100000000000000000')); significand.low = significand.low.add(significandLow); - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); + significand.high = significand.high.add(long_1.Long.fromNumber(1)); } - // Biased exponent biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - + var dec = { low: long_1.Long.fromNumber(0), high: long_1.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)) - ); + if (significand.high.shiftRightUnsigned(49).and(long_1.Long.fromNumber(1)).equals(long_1.Long.fromNumber(1))) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(long_1.Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(long_1.Long.fromNumber(biasedExponent).and(long_1.Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(long_1.Long.fromNumber(0x7fffffffffff))); + } + else { + dec.high = dec.high.or(long_1.Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(long_1.Long.fromNumber(0x1ffffffffffff))); } - dec.low = significand.low; - // Encode sign if (isNegative) { - dec.high = dec.high.or(Long.fromString("9223372036854775808")); + dec.high = dec.high.or(long_1.Long.fromString('9223372036854775808')); } - // Encode into a buffer - var buffer = utils.allocBuffer(16); + var buffer = buffer_1.Buffer.alloc(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; + 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; - + 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; + 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; - + 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 () { + }; + /** Create a string representation of the raw Decimal128 value */ + 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; + 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) + // the most significant significand bits (50-46) var significand_msb; // temporary storage for significand decoding - var significand128 = { parts: new Array(4) }; + var significand128 = { parts: [0, 0, 0, 0] }; // 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); - + // bits 96 - 127 + var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 64 - 95 + var 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); - + // bits 32 - 63 + var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + // bits 0 - 31 + var 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), + low: new long_1.Long(low, midl), + high: new long_1.Long(midh, high) }; - - if (dec.high.lessThan(Long.ZERO)) { - string.push("-"); + if (dec.high.lessThan(long_1.Long.ZERO)) { + string.push('-'); } - // Decode combination field and exponent - combination = (high >> 26) & COMBINATION_MASK; - + // bits 1 - 5 + var 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; + // 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); + } } - - exponent = biased_exponent - EXPONENT_BIAS; - + else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + // unbiased exponent + var 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[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); + 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; + // Perform 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; - } + significand_digits = 1; + significand[index] = 0; } - - scientific_exponent = significand_digits - 1 + exponent; - + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + // the exponent if scientific notation is used + var scientific_exponent = significand_digits - 1 + exponent; // The scientific exponent checks are dictated by the string conversion // specification and are somewhat arbitrary cutoffs. // @@ -2693,665 +1815,1129 @@ // 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++]); + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + // if there are too many significant digits, we should just be treating numbers + // as + or - 0 and using the non-scientific exponent (this is for the "invalid + // representation should be treated as 0/-0" spec cases in decimal128-1.json) + if (significand_digits > 34) { + string.push("" + 0); + if (exponent > 0) + string.push('E+' + exponent); + else if (exponent < 0) + string.push('E' + exponent); + return string.join(''); + } + string.push("" + significand[index++]); + significand_digits = significand_digits - 1; + if (significand_digits) { + string.push('.'); } - } 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"); + for (var i = 0; i < significand_digits; i++) { + string.push("" + significand[index++]); } - - string.push("."); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push("0"); + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); } - - for ( - i = 0; - i < significand_digits - Math.max(radix_position - 1, 0); - i++ - ) { - string.push(significand[index++]); + else { + string.push("" + scientific_exponent); } - } } - - return string.join(""); - }; - - Decimal128.prototype.toJSON = function () { + else { + // Regular format with no decimal place + if (exponent >= 0) { + for (var 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 (var 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 (var 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() }; - }; + }; + /** @internal */ + Decimal128.prototype.toExtendedJSON = function () { + return { $numberDecimal: this.toString() }; + }; + /** @internal */ + Decimal128.fromExtendedJSON = function (doc) { + return Decimal128.fromString(doc.$numberDecimal); + }; + /** @internal */ + Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Decimal128.prototype.inspect = function () { + return "new Decimal128(\"" + this.toString() + "\")"; + }; + return Decimal128; +}()); +exports.Decimal128 = Decimal128; +Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' }); +//# sourceMappingURL=decimal128.js.map - module.exports = Decimal128; - module.exports.Decimal128 = Decimal128; +/***/ }), - /***/ - }, +/***/ 9732: +/***/ ((__unused_webpack_module, exports) => { - /***/ 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; - } +"use strict"; - /** - * Access the number value. - * - * @method - * @return {number} returns the wrapped double number. - */ - Double.prototype.valueOf = function () { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Double = void 0; +/** + * A class representation of the BSON Double type. + * @public + */ +var Double = /** @class */ (function () { + /** + * Create a Double type + * + * @param value - the number we want to represent as a double. + */ + function Double(value) { + if (!(this instanceof Double)) + return new Double(value); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + /** + * Access the number value. + * + * @returns returns the wrapped double number. + */ + Double.prototype.valueOf = function () { return this.value; - }; - - /** - * @ignore - */ - Double.prototype.toJSON = function () { + }; + 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; + }; + Double.prototype.toString = function (radix) { + return this.value.toString(radix); + }; + /** @internal */ + Double.prototype.toExtendedJSON = function (options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); - }; + // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user + // explicitly provided `-0` then we need to ensure the sign makes it into the output + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: "-" + this.value.toFixed(1) }; + } + var $numberDouble; + if (Number.isInteger(this.value)) { + $numberDouble = this.value.toFixed(1); + if ($numberDouble.length >= 13) { + $numberDouble = this.value.toExponential(13).toUpperCase(); + } + } + else { + $numberDouble = this.value.toString(); + } + return { $numberDouble: $numberDouble }; + }; + /** @internal */ + Double.fromExtendedJSON = function (doc, options) { + var doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + }; + /** @internal */ + Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Double.prototype.inspect = function () { + var eJSON = this.toExtendedJSON(); + return "new Double(" + eJSON.$numberDouble + ")"; + }; + return Double; +}()); +exports.Double = Double; +Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); +//# sourceMappingURL=double.js.map + +/***/ }), + +/***/ 6669: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ensureBuffer = void 0; +var buffer_1 = __nccwpck_require__(4293); +var error_1 = __nccwpck_require__(240); +var utils_1 = __nccwpck_require__(4419); +/** + * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer. + * + * @param potentialBuffer - The potential buffer + * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that + * wraps a passed in Uint8Array + * @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in + */ +function ensureBuffer(potentialBuffer) { + if (ArrayBuffer.isView(potentialBuffer)) { + return buffer_1.Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + if (utils_1.isAnyArrayBuffer(potentialBuffer)) { + return buffer_1.Buffer.from(potentialBuffer); + } + throw new error_1.BSONTypeError('Must use either Buffer or TypedArray'); +} +exports.ensureBuffer = ensureBuffer; +//# sourceMappingURL=ensure_buffer.js.map - 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) { +/***/ }), + +/***/ 240: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BSONTypeError = exports.BSONError = void 0; +/** @public */ +var BSONError = /** @class */ (function (_super) { + __extends(BSONError, _super); + function BSONError(message) { + var _this = _super.call(this, message) || this; + Object.setPrototypeOf(_this, BSONError.prototype); + return _this; + } + Object.defineProperty(BSONError.prototype, "name", { + get: function () { + return 'BSONError'; + }, + enumerable: false, + configurable: true + }); + return BSONError; +}(Error)); +exports.BSONError = BSONError; +/** @public */ +var BSONTypeError = /** @class */ (function (_super) { + __extends(BSONTypeError, _super); + function BSONTypeError(message) { + var _this = _super.call(this, message) || this; + Object.setPrototypeOf(_this, BSONTypeError.prototype); + return _this; + } + Object.defineProperty(BSONTypeError.prototype, "name", { + get: function () { + return 'BSONTypeError'; + }, + enumerable: false, + configurable: true + }); + return BSONTypeError; +}(TypeError)); +exports.BSONTypeError = BSONTypeError; +//# sourceMappingURL=error.js.map + +/***/ }), + +/***/ 6602: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.EJSON = exports.isBSONType = void 0; +var binary_1 = __nccwpck_require__(2214); +var code_1 = __nccwpck_require__(2393); +var db_ref_1 = __nccwpck_require__(6528); +var decimal128_1 = __nccwpck_require__(3640); +var double_1 = __nccwpck_require__(9732); +var error_1 = __nccwpck_require__(240); +var int_32_1 = __nccwpck_require__(8070); +var long_1 = __nccwpck_require__(2332); +var max_key_1 = __nccwpck_require__(2281); +var min_key_1 = __nccwpck_require__(5508); +var objectid_1 = __nccwpck_require__(1248); +var utils_1 = __nccwpck_require__(4419); +var regexp_1 = __nccwpck_require__(7709); +var symbol_1 = __nccwpck_require__(2922); +var timestamp_1 = __nccwpck_require__(7431); +function isBSONType(value) { + return (utils_1.isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string'); +} +exports.isBSONType = isBSONType; +// INT32 boundaries +var BSON_INT32_MAX = 0x7fffffff; +var BSON_INT32_MIN = -0x80000000; +// INT64 boundaries +var BSON_INT64_MAX = 0x7fffffffffffffff; +var BSON_INT64_MIN = -0x8000000000000000; +// all the types where we don't need to do any special processing and can just pass the EJSON +//straight to type.fromExtendedJSON +var keysToCodecs = { + $oid: objectid_1.ObjectId, + $binary: binary_1.Binary, + $uuid: binary_1.Binary, + $symbol: symbol_1.BSONSymbol, + $numberInt: int_32_1.Int32, + $numberDecimal: decimal128_1.Decimal128, + $numberDouble: double_1.Double, + $numberLong: long_1.Long, + $minKey: min_key_1.MinKey, + $maxKey: max_key_1.MaxKey, + $regex: regexp_1.BSONRegExp, + $regularExpression: regexp_1.BSONRegExp, + $timestamp: timestamp_1.Timestamp +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function deserializeValue(value, options) { + if (options === void 0) { options = {}; } + if (typeof value === 'number') { + if (options.relaxed || options.legacy) { + return value; + } + // if it's an integer, should interpret as smallest BSON integer + // that can represent it exactly. (if out of range, interpret as double.) + if (Math.floor(value) === value) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) + return new int_32_1.Int32(value); + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) + return long_1.Long.fromNumber(value); + } + // If the number is a non-integer or out of integer range, should interpret as BSON Double. + return new double_1.Double(value); + } + // from here on out we're looking for bson types, so bail if its not an object + if (value == null || typeof value !== 'object') + return value; + // upgrade deprecated undefined to null + if (value.$undefined) + return null; + var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; }); + for (var i = 0; i < keys.length; i++) { + var c = keysToCodecs[keys[i]]; + if (c) + return c.fromExtendedJSON(value, options); + } + if (value.$date != null) { + var d = value.$date; + var date = new Date(); + if (options.legacy) { + if (typeof d === 'number') + date.setTime(d); + else if (typeof d === 'string') + date.setTime(Date.parse(d)); + } + else { + if (typeof d === 'string') + date.setTime(Date.parse(d)); + else if (long_1.Long.isLong(d)) + date.setTime(d.toNumber()); + else if (typeof d === 'number' && options.relaxed) + date.setTime(d); + } + return date; + } + if (value.$code != null) { + var copy = Object.assign({}, value); + if (value.$scope) { + copy.$scope = deserializeValue(value.$scope); + } + return code_1.Code.fromExtendedJSON(value); + } + if (db_ref_1.isDBRefLike(value) || value.$dbPointer) { + var v = value.$ref ? value : value.$dbPointer; + // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped) + // because of the order JSON.parse goes through the document + if (v instanceof db_ref_1.DBRef) + return v; + var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); }); + var valid_1 = true; + dollarKeys.forEach(function (k) { + if (['$ref', '$id', '$db'].indexOf(k) === -1) + valid_1 = false; + }); + // only make DBRef if $ keys are all valid + if (valid_1) + return db_ref_1.DBRef.fromExtendedJSON(v); + } + return value; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeArray(array, options) { + return array.map(function (v, index) { + options.seenObjects.push({ propertyName: "index " + index, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); +} +function getISOString(date) { + var isoStr = date.toISOString(); + // we should only show milliseconds in timestamp if they're non-zero + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeValue(value, options) { + if ((typeof value === 'object' || typeof value === 'function') && value !== null) { + var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; }); + if (index !== -1) { + var props = options.seenObjects.map(function (entry) { return entry.propertyName; }); + var leadingPart = props + .slice(0, index) + .map(function (prop) { return prop + " -> "; }) + .join(''); + var alreadySeen = props[index]; + var circularPart = ' -> ' + + props + .slice(index + 1, props.length - 1) + .map(function (prop) { return prop + " -> "; }) + .join(''); + var current = props[props.length - 1]; + var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); + var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); + throw new error_1.BSONTypeError('Converting circular structure to EJSON:\n' + + (" " + leadingPart + alreadySeen + circularPart + current + "\n") + + (" " + leadingSpace + "\\" + dashes + "/")); + } + options.seenObjects[options.seenObjects.length - 1].obj = value; + } + if (Array.isArray(value)) + return serializeArray(value, options); + if (value === undefined) + return null; + if (value instanceof Date || utils_1.isDate(value)) { + var dateNum = value.getTime(), + // is it in year range 1970-9999? + inRange = dateNum > -1 && dateNum < 253402318800000; + if (options.legacy) { + return options.relaxed && inRange + ? { $date: value.getTime() } + : { $date: getISOString(value) }; + } + return options.relaxed && inRange + ? { $date: getISOString(value) } + : { $date: { $numberLong: value.getTime().toString() } }; + } + if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { + // it's an integer + if (Math.floor(value) === value) { + var int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX, int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX; + // interpret as being of the smallest BSON integer type that can represent the number exactly + if (int32Range) + return { $numberInt: value.toString() }; + if (int64Range) + return { $numberLong: value.toString() }; + } + return { $numberDouble: value.toString() }; + } + if (value instanceof RegExp || utils_1.isRegExp(value)) { + var flags = value.flags; + if (flags === undefined) { + var match = value.toString().match(/[gimuy]*$/); + if (match) { + flags = match[0]; + } + } + var rx = new regexp_1.BSONRegExp(value.source, flags); + return rx.toExtendedJSON(options); + } + if (value != null && typeof value === 'object') + return serializeDocument(value, options); + return value; +} +var BSON_TYPE_MAPPINGS = { + Binary: function (o) { return new binary_1.Binary(o.value(), o.sub_type); }, + Code: function (o) { return new code_1.Code(o.code, o.scope); }, + DBRef: function (o) { return new db_ref_1.DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); }, + Decimal128: function (o) { return new decimal128_1.Decimal128(o.bytes); }, + Double: function (o) { return new double_1.Double(o.value); }, + Int32: function (o) { return new int_32_1.Int32(o.value); }, + Long: function (o) { + return long_1.Long.fromBits( + // underscore variants for 1.x backwards compatibility + o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_); + }, + MaxKey: function () { return new max_key_1.MaxKey(); }, + MinKey: function () { return new min_key_1.MinKey(); }, + ObjectID: function (o) { return new objectid_1.ObjectId(o); }, + ObjectId: function (o) { return new objectid_1.ObjectId(o); }, + BSONRegExp: function (o) { return new regexp_1.BSONRegExp(o.pattern, o.options); }, + Symbol: function (o) { return new symbol_1.BSONSymbol(o.value); }, + Timestamp: function (o) { return timestamp_1.Timestamp.fromBits(o.low, o.high); } +}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new error_1.BSONError('not an object instance'); + var bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + // It's a regular object. Recursively serialize its property values. + var _doc = {}; + for (var name in doc) { + options.seenObjects.push({ propertyName: name, obj: null }); + try { + _doc[name] = serializeValue(doc[name], options); + } + finally { + options.seenObjects.pop(); + } + } + return _doc; + } + else if (isBSONType(doc)) { + // the "document" is really just a BSON type object + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + // There's no EJSON serialization function on the object. It's probably an + // object created by a previous version of this library (or another library) + // that's duck-typing objects to look like they were generated by this library). + // Copy the object into this library's version of that type. + var mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new error_1.BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + // Two BSON types may have nested objects that may need to be serialized too + if (bsontype === 'Code' && outDoc.scope) { + outDoc = new code_1.Code(outDoc.code, serializeValue(outDoc.scope, options)); + } + else if (bsontype === 'DBRef' && outDoc.oid) { + outDoc = new db_ref_1.DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); + } + return outDoc.toExtendedJSON(options); + } + else { + throw new error_1.BSONError('_bsontype must be a string, but was: ' + typeof bsontype); + } +} +/** + * EJSON parse / stringify API + * @public + */ +// the namespace here is used to emulate `export * as EJSON from '...'` +// which as of now (sept 2020) api-extractor does not support +// eslint-disable-next-line @typescript-eslint/no-namespace +var EJSON; +(function (EJSON) { + /** + * Parse an Extended JSON string, constructing the JavaScript value or object described by that + * string. + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const text = '{ "int32": { "$numberInt": "10" } }'; + * + * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } + * console.log(EJSON.parse(text, { relaxed: false })); + * + * // prints { int32: 10 } + * console.log(EJSON.parse(text)); + * ``` + */ + function parse(text, options) { + var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options); + // relaxed implies not strict + if (typeof finalOptions.relaxed === 'boolean') + finalOptions.strict = !finalOptions.relaxed; + if (typeof finalOptions.strict === 'boolean') + finalOptions.relaxed = !finalOptions.strict; + return JSON.parse(text, function (key, value) { + if (key.indexOf('\x00') !== -1) { + throw new error_1.BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key)); + } + return deserializeValue(value, finalOptions); + }); + } + EJSON.parse = parse; + /** + * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer + * function is specified or optionally including only the specified properties if a replacer array + * is specified. + * + * @param value - The value to convert to extended JSON + * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string + * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes. + * @param options - Optional settings + * + * @example + * ```js + * const { EJSON } = require('bson'); + * const Int32 = require('mongodb').Int32; + * const doc = { int32: new Int32(10) }; + * + * // prints '{"int32":{"$numberInt":"10"}}' + * console.log(EJSON.stringify(doc, { relaxed: false })); + * + * // prints '{"int32":10}' + * console.log(EJSON.stringify(doc)); + * ``` + */ + function stringify(value, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + replacer, space, options) { + if (space != null && typeof space === 'object') { + options = space; + space = 0; + } + if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { + options = replacer; + replacer = undefined; + space = 0; + } + var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + var doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); + } + EJSON.stringify = stringify; + /** + * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object. + * + * @param value - The object to serialize + * @param options - Optional settings passed to the `stringify` function + */ + function serialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); + } + EJSON.serialize = serialize; + /** + * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types + * + * @param ejson - The Extended JSON object to deserialize + * @param options - Optional settings passed to the parse method + */ + function deserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); + } + EJSON.deserialize = deserialize; +})(EJSON = exports.EJSON || (exports.EJSON = {})); +//# sourceMappingURL=extended_json.js.map + +/***/ }), + +/***/ 5742: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// 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 +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.writeIEEE754 = exports.readIEEE754 = void 0; +function readIEEE754(buffer, offset, endian, mLen, nBytes) { + var e; + var m; + var bBE = endian === 'big'; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = bBE ? 0 : nBytes - 1; + var d = bBE ? 1 : -1; + var 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); +} +exports.readIEEE754 = readIEEE754; +function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) { + var e; + var m; + var c; + var bBE = endian === 'big'; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = bBE ? nBytes - 1 : 0; + var d = bBE ? -1 : 1; + var 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) { + } + if (e + eBias >= 1) { value += rt / c; - } else { + } + else { value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { + } + if (value * c >= 2) { e++; c /= 2; - } - - if (e + eBias >= eMax) { + } + if (e + eBias >= eMax) { m = 0; e = eMax; - } else if (e + eBias >= 1) { + } + else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; - } else { + } + else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; - } } + } + if (isNaN(value)) + m = 0; + while (mLen >= 8) { + buffer[offset + i] = m & 0xff; + i += d; + m /= 256; + mLen -= 8; + } + e = (e << mLen) | m; + if (isNaN(value)) + e += 8; + eLen += mLen; + while (eLen > 0) { + buffer[offset + i] = e & 0xff; + i += d; + e /= 256; + eLen -= 8; + } + buffer[offset + i - d] |= s * 128; +} +exports.writeIEEE754 = writeIEEE754; +//# sourceMappingURL=float_parser.js.map - 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; +/***/ }), - /***/ - }, +/***/ 8070: +/***/ ((__unused_webpack_module, exports) => { - /***/ 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; - }; +"use strict"; - /** - * Access the number value. - * - * @method - * @return {number} returns the wrapped int32 number. - */ - Int32.prototype.valueOf = function () { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Int32 = void 0; +/** + * A class representation of a BSON Int32 type. + * @public + */ +var Int32 = /** @class */ (function () { + /** + * Create an Int32 type + * + * @param value - the number we want to represent as an int32. + */ + function Int32(value) { + if (!(this instanceof Int32)) + return new Int32(value); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value | 0; + } + /** + * Access the number value. + * + * @returns returns the wrapped int32 number. + */ + Int32.prototype.valueOf = function () { return this.value; - }; - - /** - * @ignore - */ - Int32.prototype.toJSON = function () { + }; + Int32.prototype.toString = function (radix) { + return this.value.toString(radix); + }; + 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(); - }; + }; + /** @internal */ + Int32.prototype.toExtendedJSON = function (options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + }; + /** @internal */ + Int32.fromExtendedJSON = function (doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + }; + /** @internal */ + Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Int32.prototype.inspect = function () { + return "new Int32(" + this.valueOf() + ")"; + }; + return Int32; +}()); +exports.Int32 = Int32; +Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' }); +//# sourceMappingURL=int_32.js.map - /** Converts the Long to a BigInt (arbitrary precision). */ - Long.prototype.toBigInt = function () { - return BigInt(this.toString()); - }; +/***/ }), - /** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ - Long.prototype.toJSON = function () { - return this.toString(); - }; +/***/ 2332: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * 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); - } +"use strict"; - if (this.isZero()) { - return "0"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Long = void 0; +var utils_1 = __nccwpck_require__(4419); +/** + * wasm optimizations, to do native i64 multiplication and divide + */ +var wasm = undefined; +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module( + // prettier-ignore + new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; +} +catch (_a) { + // no wasm support +} +var TWO_PWR_16_DBL = 1 << 16; +var TWO_PWR_24_DBL = 1 << 24; +var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; +/** A cache of the Long representations of small integer values. */ +var INT_CACHE = {}; +/** A cache of the Long representations of small unsigned integer values. */ +var UINT_CACHE = {}; +/** + * A class representing a 64-bit integer + * @public + * @remarks + * 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. + * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class. + */ +var Long = /** @class */ (function () { + /** + * 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. + * + * Acceptable signatures are: + * - Long(low, high, unsigned?) + * - Long(bigint, unsigned?) + * - Long(string, unsigned?) + * + * @param low - The low (signed) 32 bits of the long + * @param high - The high (signed) 32 bits of the long + * @param unsigned - Whether unsigned or not, defaults to signed + */ + function Long(low, high, unsigned) { + if (low === void 0) { low = 0; } + if (!(this instanceof Long)) + return new Long(low, high, unsigned); + if (typeof low === 'bigint') { + Object.assign(this, Long.fromBigInt(low, !!high)); + } + else if (typeof low === 'string') { + Object.assign(this, Long.fromString(low, !!high)); } - - 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); - } + else { + this.low = low | 0; + this.high = high | 0; + this.unsigned = !!unsigned; } - - // 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; - } + Object.defineProperty(this, '__isLong__', { + value: true, + configurable: false, + writable: false, + enumerable: false + }); + } + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. + * Each is assumed to use 32 bits. + * @param lowBits - The low 32 bits + * @param highBits - The high 32 bits + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBits = function (lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + }; + /** + * Returns a Long representing the given 32 bit integer value. + * @param value - The 32 bit integer in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromInt = function (value, unsigned) { + var obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if ((cache = 0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; } - }; - - /** - * 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; + else { + value |= 0; + if ((cache = -128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; } - }; - - /** - * 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; + }; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromNumber = function (value, unsigned) { + if (isNaN(value)) + return unsigned ? Long.UZERO : Long.ZERO; + if (unsigned) { + if (value < 0) + return Long.UZERO; + if (value >= TWO_PWR_64_DBL) + return Long.MAX_UNSIGNED_VALUE; } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; + else { + if (value <= -TWO_PWR_63_DBL) + return Long.MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return Long.MAX_VALUE; + } + if (value < 0) + return Long.fromNumber(-value, unsigned).neg(); + return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); + }; + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @param value - The number in question + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBigInt = function (value, unsigned) { + return Long.fromString(value.toString(), unsigned); + }; + /** + * Returns a Long representation of the given string, written using the specified radix. + * @param str - The textual representation of the Long + * @param unsigned - Whether unsigned or not, defaults to signed + * @param radix - The radix in which the text is written (2-36), defaults to 10 + * @returns The corresponding Long value + */ + Long.fromString = function (str, unsigned, radix) { + if (str.length === 0) + throw Error('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + // For goog.math.long compatibility + (radix = unsigned), (unsigned = false); } - if (!thisNeg && otherNeg) { - return 1; + else { + unsigned = !!unsigned; } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + var p; + if ((p = str.indexOf('-')) > 0) + throw Error('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); } - }; - - /** - * 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); + // 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), value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.mul(power).add(Long.fromNumber(value)); + } + else { + result = result.mul(radixToPower); + result = result.add(Long.fromNumber(value)); + } } - }; - - /** - * 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) { + result.unsigned = unsigned; + return result; + }; + /** + * Creates a Long from its byte representation. + * @param bytes - Byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @param le - Whether little or big endian, defaults to big endian + * @returns The corresponding Long value + */ + Long.fromBytes = function (bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + }; + /** + * Creates a Long from its little endian byte representation. + * @param bytes - Little endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBytesLE = function (bytes, unsigned) { + return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); + }; + /** + * Creates a Long from its big endian byte representation. + * @param bytes - Big endian byte representation + * @param unsigned - Whether unsigned or not, defaults to signed + * @returns The corresponding Long value + */ + Long.fromBytesBE = function (bytes, unsigned) { + return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); + }; + /** + * Tests if the specified object is a Long. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + Long.isLong = function (value) { + return utils_1.isObjectLike(value) && value['__isLong__'] === true; + }; + /** + * Converts the specified value to a Long. + * @param unsigned - Whether unsigned or not, defaults to signed + */ + Long.fromValue = function (val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + // Throws for non-objects, converts non-instanceof Long: + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + }; + /** Returns the sum of this and the specified Long. */ + Long.prototype.add = function (addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); // 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; + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = addend.high >>> 16; + var b32 = addend.high & 0xffff; + var b16 = addend.low >>> 16; + var b00 = addend.low & 0xffff; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 + b00; c16 += c00 >>> 16; c00 &= 0xffff; @@ -3363,75 +2949,315 @@ 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; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + /** + * Returns the sum of this and the specified Long. + * @returns Sum + */ + Long.prototype.and = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + }; + /** + * Compares this Long's value with the specified's. + * @returns 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 (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.eq(other)) + return 0; + var thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + // At this point the sign bits are the same + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + // Both are positive if at least one is unsigned + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + }; + /** This is an alias of {@link Long.compare} */ + Long.prototype.comp = function (other) { + return this.compare(other); + }; + /** + * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned. + * @returns Quotient + */ + Long.prototype.divide = function (divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw Error('division by zero'); + // use wasm support if present + if (wasm) { + // guard against signed division overflow: the largest + // negative number / -1 would be 1 larger than the largest + // positive number, due to two's complement. + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + // be consistent with non-wasm code path + return this; + } + var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (this.isZero()) + return this.unsigned ? Long.UZERO : Long.ZERO; + var approx, rem, res; + if (!this.unsigned) { + // This section is only relevant for signed longs and is derived from the + // closure library as a whole. + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + // recall that -MIN_VALUE == MIN_VALUE + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(Long.ZERO)) { + return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; + } + else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } + else if (divisor.eq(Long.MIN_VALUE)) + return this.unsigned ? Long.UZERO : Long.ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } + else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = 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; + else { + // The algorithm below has not been made for unsigned longs. It's therefore + // required to take special care of the MSB prior to running it. + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + // 15 >>> 1 = 7 ; with divisor = 8 ; true + return Long.UONE; + res = Long.UZERO; } - - 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(); + // 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. + rem = this; + while (rem.gte(divisor)) { + // 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() / divisor.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.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + // 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.sub(approxRem); } - - // 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()); + return res; + }; + /**This is an alias of {@link Long.divide} */ + Long.prototype.div = function (divisor) { + return this.divide(divisor); + }; + /** + * Tests if this Long's value equals the specified's. + * @param other - Other value + */ + Long.prototype.equals = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + }; + /** This is an alias of {@link Long.equals} */ + Long.prototype.eq = function (other) { + return this.equals(other); + }; + /** Gets the high 32 bits as a signed integer. */ + Long.prototype.getHighBits = function () { + return this.high; + }; + /** Gets the high 32 bits as an unsigned integer. */ + Long.prototype.getHighBitsUnsigned = function () { + return this.high >>> 0; + }; + /** Gets the low 32 bits as a signed integer. */ + Long.prototype.getLowBits = function () { + return this.low; + }; + /** Gets the low 32 bits as an unsigned integer. */ + Long.prototype.getLowBitsUnsigned = function () { + return this.low >>> 0; + }; + /** Gets the number of bits needed to represent the absolute value of this Long. */ + Long.prototype.getNumBitsAbs = function () { + if (this.isNegative()) { + // Unsigned Longs are never negative + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + var val = this.high !== 0 ? this.high : this.low; + var bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + }; + /** Tests if this Long's value is greater than the specified's. */ + Long.prototype.greaterThan = function (other) { + return this.comp(other) > 0; + }; + /** This is an alias of {@link Long.greaterThan} */ + Long.prototype.gt = function (other) { + return this.greaterThan(other); + }; + /** Tests if this Long's value is greater than or equal the specified's. */ + Long.prototype.greaterThanOrEqual = function (other) { + return this.comp(other) >= 0; + }; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + Long.prototype.gte = function (other) { + return this.greaterThanOrEqual(other); + }; + /** This is an alias of {@link Long.greaterThanOrEqual} */ + Long.prototype.ge = function (other) { + return this.greaterThanOrEqual(other); + }; + /** Tests if this Long's value is even. */ + Long.prototype.isEven = function () { + return (this.low & 1) === 0; + }; + /** Tests if this Long's value is negative. */ + Long.prototype.isNegative = function () { + return !this.unsigned && this.high < 0; + }; + /** Tests if this Long's value is odd. */ + Long.prototype.isOdd = function () { + return (this.low & 1) === 1; + }; + /** Tests if this Long's value is positive. */ + Long.prototype.isPositive = function () { + return this.unsigned || this.high >= 0; + }; + /** Tests if this Long's value equals zero. */ + Long.prototype.isZero = function () { + return this.high === 0 && this.low === 0; + }; + /** Tests if this Long's value is less than the specified's. */ + Long.prototype.lessThan = function (other) { + return this.comp(other) < 0; + }; + /** This is an alias of {@link Long#lessThan}. */ + Long.prototype.lt = function (other) { + return this.lessThan(other); + }; + /** Tests if this Long's value is less than or equal the specified's. */ + Long.prototype.lessThanOrEqual = function (other) { + return this.comp(other) <= 0; + }; + /** This is an alias of {@link Long.lessThanOrEqual} */ + Long.prototype.lte = function (other) { + return this.lessThanOrEqual(other); + }; + /** Returns this Long modulo the specified. */ + Long.prototype.modulo = function (divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + // use wasm support if present + if (wasm) { + var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + }; + /** This is an alias of {@link Long.modulo} */ + Long.prototype.mod = function (divisor) { + return this.modulo(divisor); + }; + /** This is an alias of {@link Long.modulo} */ + Long.prototype.rem = function (divisor) { + return this.modulo(divisor); + }; + /** + * Returns the product of this and the specified Long. + * @param multiplier - Multiplier + * @returns Product + */ + Long.prototype.multiply = function (multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + // use wasm support if present + if (wasm) { + var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); + } + if (multiplier.isZero()) + return Long.ZERO; + if (this.eq(Long.MIN_VALUE)) + return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (multiplier.eq(Long.MIN_VALUE)) + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } + else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + // If both longs are small, use float multiplication + if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + // 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; + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 0xffff; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 0xffff; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 * b00; c16 += c00 >>> 16; c00 &= 0xffff; @@ -3452,2770 +3278,2140 @@ 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; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); + }; + /** This is an alias of {@link Long.multiply} */ + Long.prototype.mul = function (multiplier) { + return this.multiply(multiplier); + }; + /** Returns the Negation of this Long's value. */ + Long.prototype.negate = function () { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + }; + /** This is an alias of {@link Long.negate} */ + Long.prototype.neg = function () { + return this.negate(); + }; + /** Returns the bitwise NOT of this Long. */ + Long.prototype.not = function () { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + }; + /** Tests if this Long's value differs from the specified's. */ + Long.prototype.notEquals = function (other) { + return !this.equals(other); + }; + /** This is an alias of {@link Long.notEquals} */ + Long.prototype.neq = function (other) { + return this.notEquals(other); + }; + /** This is an alias of {@link Long.notEquals} */ + Long.prototype.ne = function (other) { + return this.notEquals(other); + }; + /** + * Returns the bitwise OR of this Long and the specified. + */ + Long.prototype.or = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + }; + /** + * Returns this Long with bits shifted to the left by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftLeft = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); + else + return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); + }; + /** This is an alias of {@link Long.shiftLeft} */ + Long.prototype.shl = function (numBits) { + return this.shiftLeft(numBits); + }; + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftRight = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); + else + return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); + }; + /** This is an alias of {@link Long.shiftRight} */ + Long.prototype.shr = function (numBits) { + return this.shiftRight(numBits); + }; + /** + * Returns this Long with bits logically shifted to the right by the given amount. + * @param numBits - Number of bits + * @returns Shifted Long + */ + Long.prototype.shiftRightUnsigned = function (numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + 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, this.unsigned); } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; + else if (numBits === 32) + return Long.fromBits(high, 0, this.unsigned); + else + return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); } - + }; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + Long.prototype.shr_u = function (numBits) { + return this.shiftRightUnsigned(numBits); + }; + /** This is an alias of {@link Long.shiftRightUnsigned} */ + Long.prototype.shru = function (numBits) { + return this.shiftRightUnsigned(numBits); + }; + /** + * Returns the difference of this and the specified Long. + * @param subtrahend - Subtrahend + * @returns Difference + */ + Long.prototype.subtract = function (subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + }; + /** This is an alias of {@link Long.subtract} */ + Long.prototype.sub = function (subtrahend) { + return this.subtract(subtrahend); + }; + /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */ + Long.prototype.toInt = function () { + return this.unsigned ? this.low >>> 0 : this.low; + }; + /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */ + Long.prototype.toNumber = function () { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + }; + /** Converts the Long to a BigInt (arbitrary precision). */ + Long.prototype.toBigInt = function () { + return BigInt(this.toString()); + }; + /** + * Converts this Long to its byte representation. + * @param le - Whether little or big endian, defaults to big endian + * @returns Byte representation + */ + Long.prototype.toBytes = function (le) { + return le ? this.toBytesLE() : this.toBytesBE(); + }; + /** + * Converts this Long to its little endian byte representation. + * @returns Little endian byte representation + */ + Long.prototype.toBytesLE = function () { + var hi = this.high, lo = this.low; + return [ + lo & 0xff, + (lo >>> 8) & 0xff, + (lo >>> 16) & 0xff, + lo >>> 24, + hi & 0xff, + (hi >>> 8) & 0xff, + (hi >>> 16) & 0xff, + hi >>> 24 + ]; + }; + /** + * Converts this Long to its big endian byte representation. + * @returns Big endian byte representation + */ + Long.prototype.toBytesBE = function () { + var hi = this.high, lo = this.low; + return [ + hi >>> 24, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + lo >>> 24, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff + ]; + }; + /** + * Converts this Long to signed. + */ + Long.prototype.toSigned = function () { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + }; + /** + * Converts the Long to a string written in the specified radix. + * @param radix - Radix (2-36), defaults to 10 + * @throws RangeError If `radix` is out of range + */ + Long.prototype.toString = function (radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + if (this.isZero()) + return '0'; 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 given value, provided that it is a finite number. Otherwise, zero is returned. - * @param {bigint} value - The number in question - * @returns {Long} The corresponding Long value - */ - Long.fromBigInt = function (value) { - return Long.fromString(value.toString(10), 10); - }; - - /** - * 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); + // Unsigned Longs are never negative + if (this.eq(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), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } + else + return '-' + this.neg().toString(radix); } - - // Do several (8) digits each time through the loop, so as to + // 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, 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)); - } + var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + // eslint-disable-next-line @typescript-eslint/no-this-alias + var rem = this; + var result = ''; + // eslint-disable-next-line no-constant-condition + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; + var digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } + else { + while (digits.length < 6) + digits = '0' + digits; + result = '' + digits + result; + } + } + }; + /** Converts this Long to unsigned. */ + Long.prototype.toUnsigned = function () { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + }; + /** Returns the bitwise XOR of this Long and the given one. */ + Long.prototype.xor = function (other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + }; + /** This is an alias of {@link Long.isZero} */ + Long.prototype.eqz = function () { + return this.isZero(); + }; + /** This is an alias of {@link Long.lessThanOrEqual} */ + Long.prototype.le = function (other) { + return this.lessThanOrEqual(other); + }; + /* + **************************************************************** + * BSON SPECIFIC ADDITIONS * + **************************************************************** + */ + Long.prototype.toExtendedJSON = function (options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + }; + Long.fromExtendedJSON = function (doc, options) { + var result = Long.fromString(doc.$numberLong); + return options && options.relaxed ? result.toNumber() : result; + }; + /** @internal */ + Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Long.prototype.inspect = function () { + return "new Long(\"" + this.toString() + "\"" + (this.unsigned ? ', true' : '') + ")"; + }; + Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); + /** Maximum unsigned value. */ + Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); + /** Signed zero */ + Long.ZERO = Long.fromInt(0); + /** Unsigned zero. */ + Long.UZERO = Long.fromInt(0, true); + /** Signed one. */ + Long.ONE = Long.fromInt(1); + /** Unsigned one. */ + Long.UONE = Long.fromInt(1, true); + /** Signed negative one. */ + Long.NEG_ONE = Long.fromInt(-1); + /** Maximum signed value. */ + Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); + /** Minimum signed value. */ + Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + return Long; +}()); +exports.Long = Long; +Object.defineProperty(Long.prototype, '__isLong__', { value: true }); +Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' }); +//# sourceMappingURL=long.js.map + +/***/ }), + +/***/ 2935: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/* eslint-disable @typescript-eslint/no-explicit-any */ +// We have an ES6 Map available, return the native instance +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Map = void 0; +var global_1 = __nccwpck_require__(207); +/** @public */ +var bsonMap; +exports.Map = bsonMap; +var bsonGlobal = global_1.getGlobal(); +if (bsonGlobal.Map) { + exports.Map = bsonMap = bsonGlobal.Map; +} +else { + // We will return a polyfill + exports.Map = bsonMap = /** @class */ (function () { + function Map(array) { + if (array === void 0) { 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 }; + } } - 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 = {}; + 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; + 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, - }; - }, - }; + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? [key, _this._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); - } + 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; + return this._values[key] ? this._values[key].v : undefined; }; - Map.prototype.has = function (key) { - return this._values[key] != null; + 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, - }; - }, - }; + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._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; + 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; - } - - // 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(); + var _this = this; + var index = 0; + return { + next: function () { + var key = _this._keys[index++]; + return { + value: key !== undefined ? _this._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + Object.defineProperty(Map.prototype, "size", { + get: function () { + return this._keys.length; + }, + enumerable: false, + configurable: true + }); + return Map; + }()); +} +//# sourceMappingURL=map.js.map - this._bsontype = "MaxKey"; - } +/***/ }), - module.exports = MaxKey; - module.exports.MaxKey = MaxKey; +/***/ 2281: +/***/ ((__unused_webpack_module, exports) => { - /***/ - }, +"use strict"; - /***/ 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(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MaxKey = void 0; +/** + * A class representation of the BSON MaxKey type. + * @public + */ +var MaxKey = /** @class */ (function () { + function MaxKey() { + if (!(this instanceof MaxKey)) + return new MaxKey(); + } + /** @internal */ + MaxKey.prototype.toExtendedJSON = function () { + return { $maxKey: 1 }; + }; + /** @internal */ + MaxKey.fromExtendedJSON = function () { + return new MaxKey(); + }; + /** @internal */ + MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + MaxKey.prototype.inspect = function () { + return 'new MaxKey()'; + }; + return MaxKey; +}()); +exports.MaxKey = MaxKey; +Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); +//# sourceMappingURL=max_key.js.map - this._bsontype = "MinKey"; - } +/***/ }), - module.exports = MinKey; - module.exports.MinKey = MinKey; +/***/ 5508: +/***/ ((__unused_webpack_module, exports) => { - /***/ - }, +"use strict"; - /***/ 9502: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - // Custom inspect property name / symbol. - var inspect = "inspect"; - - var utils = __nccwpck_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 = __nccwpck_require__(1669).inspect.custom || "inspect"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MinKey = void 0; +/** + * A class representation of the BSON MinKey type. + * @public + */ +var MinKey = /** @class */ (function () { + function MinKey() { + if (!(this instanceof MinKey)) + return new MinKey(); + } + /** @internal */ + MinKey.prototype.toExtendedJSON = function () { + return { $minKey: 1 }; + }; + /** @internal */ + MinKey.fromExtendedJSON = function () { + return new MinKey(); + }; + /** @internal */ + MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + MinKey.prototype.inspect = function () { + return 'new MinKey()'; + }; + return MinKey; +}()); +exports.MinKey = MinKey; +Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' }); +//# sourceMappingURL=min_key.js.map + +/***/ }), + +/***/ 1248: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ObjectId = void 0; +var buffer_1 = __nccwpck_require__(4293); +var ensure_buffer_1 = __nccwpck_require__(6669); +var error_1 = __nccwpck_require__(240); +var utils_1 = __nccwpck_require__(4419); +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); +// Unique sequence for the current process (initialized on first use) +var PROCESS_UNIQUE = null; +var kId = Symbol('id'); +/** + * A class representation of the BSON ObjectId type. + * @public + */ +var ObjectId = /** @class */ (function () { + /** + * Create an ObjectId type + * + * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number. + */ + function ObjectId(inputId) { + if (!(this instanceof ObjectId)) + return new ObjectId(inputId); + // workingId is set based on type of input and whether valid id exists for the input + var workingId; + if (typeof inputId === 'object' && inputId && 'id' in inputId) { + if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { + throw new error_1.BSONTypeError('Argument passed in must have an id that is of type string or Buffer'); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = buffer_1.Buffer.from(inputId.toHexString(), 'hex'); + } + else { + workingId = inputId.id; + } } - } 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; + else { + workingId = inputId; + } + // the following cases use workingId to construct an ObjectId + if (workingId == null || typeof workingId === 'number') { + // The most common use case (blank id, new objectId instance) + // Generate a new id + this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); + } + else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { + this[kId] = ensure_buffer_1.ensureBuffer(workingId); + } + else if (typeof workingId === 'string') { + if (workingId.length === 12) { + var bytes = buffer_1.Buffer.from(workingId); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } + else { + throw new error_1.BSONTypeError('Argument passed in must be a string of 12 bytes'); + } + } + else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this[kId] = buffer_1.Buffer.from(workingId, 'hex'); + } + else { + throw new error_1.BSONTypeError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters'); + } } - - // 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" - ); + else { + throw new error_1.BSONTypeError('Argument passed in does not match the accepted types'); } - - 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 we are caching the hex string + if (ObjectId.cacheHexString) { + this.__id = this.id.toString('hex'); } - - if (this.id instanceof _Buffer) { - hexString = convertToHex(this.id); - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; + } + Object.defineProperty(ObjectId.prototype, "id", { + /** + * The ObjectId bytes + * @readonly + */ + get: function () { + return this[kId]; + }, + set: function (value) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = value.toString('hex'); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ObjectId.prototype, "generationTime", { + /** + * The generation time of this ObjectId instance + * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch + */ + get: function () { + return this.id.readInt32BE(0); + }, + set: function (value) { + // Encode time into first 4 bytes + this.id.writeUInt32BE(value, 0); + }, + enumerable: false, + configurable: true + }); + /** Returns the ObjectId id as a 24 character hex string representation */ + ObjectId.prototype.toHexString = function () { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; } - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; + var hexString = this.id.toString('hex'); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; } - - 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 + }; + /** + * Update the ObjectId index + * @privateRemarks + * Used in generating new ObjectId's on the driver + * @internal + */ + ObjectId.getInc = function () { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + }; + /** + * Generate a 12 byte id buffer used in ObjectId's + * + * @param time - pass in a second based timestamp. + */ + ObjectId.generate = function (time) { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + var inc = ObjectId.getInc(); + var buffer = buffer_1.Buffer.alloc(12); + // 4-byte timestamp + buffer.writeUInt32BE(time, 0); + // set PROCESS_UNIQUE if yet not initialized + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = utils_1.randomBytes(5); + } + // 5-byte process unique + buffer[4] = PROCESS_UNIQUE[0]; + buffer[5] = PROCESS_UNIQUE[1]; + buffer[6] = PROCESS_UNIQUE[2]; + buffer[7] = PROCESS_UNIQUE[3]; + buffer[8] = PROCESS_UNIQUE[4]; + // 3-byte counter 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) { + }; + /** + * Converts the id into a 24 character hex string for printing + * + * @param format - The Buffer toString format parameter. + */ + 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 ) + if (format) + return this.id.toString(format); 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 () { + }; + /** Converts to its JSON the 24 character hex string representation. */ + 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; + }; + /** + * Compares the equality of this ObjectId with `otherID`. + * + * @param otherId - ObjectId instance to compare against. + */ + ObjectId.prototype.equals = function (otherId) { + if (otherId === undefined || otherId === null) { + 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 () { + if (otherId instanceof ObjectId) { + return this.toString() === otherId.toString(); + } + if (typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + utils_1.isUint8Array(this.id)) { + return otherId === buffer_1.Buffer.prototype.toString.call(this.id, 'latin1'); + } + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } + if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { + return buffer_1.Buffer.from(otherId).equals(this.id); + } + if (typeof otherId === 'object' && + 'toHexString' in otherId && + typeof otherId.toHexString === 'function') { + return otherId.toHexString() === this.toHexString(); + } + return false; + }; + /** Returns the generation date (accurate up to the second) that this ID was generated. */ + 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); + var time = this.id.readUInt32BE(0); 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]); + }; + /** @internal */ + ObjectId.createPk = function () { + 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. + * + * @param time - an integer number representing a number of seconds. + */ + ObjectId.createFromTime = function (time) { + var buffer = buffer_1.Buffer.from([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; + buffer.writeUInt32BE(time, 0); // 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) { + return new ObjectId(buffer); + }; + /** + * Creates an ObjectId from a hex string representation of an ObjectId. + * + * @param hexString - create a ObjectId from a passed in 24 character hexstring. + */ + ObjectId.createFromHexString = function (hexString) { // 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++)]; + if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { + throw new error_1.BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); } - - 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; + return new ObjectId(buffer_1.Buffer.from(hexString, 'hex')); + }; + /** + * Checks if a value is a valid bson ObjectId + * + * @param id - ObjectId instance to validate. + */ + ObjectId.isValid = function (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 (typeof id === 'string') { + return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); } - - if (id instanceof ObjectID) { - return true; + if (id instanceof ObjectId) { + return true; } - - if (id instanceof _Buffer) { - return true; + if (utils_1.isUint8Array(id) && id.length === 12) { + 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)) - ); + if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') { + if (typeof id.id === 'string') { + return id.id.length === 12; + } + return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex')); } - 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, - __nccwpck_require__ - ) => { - "use strict"; - - var Long = __nccwpck_require__(8522).Long, - Double = __nccwpck_require__(972).Double, - Timestamp = __nccwpck_require__(1031).Timestamp, - ObjectID = __nccwpck_require__(9502).ObjectID, - Symbol = __nccwpck_require__(2259).Symbol, - BSONRegExp = __nccwpck_require__(4636).BSONRegExp, - Code = __nccwpck_require__(7113).Code, - Decimal128 = __nccwpck_require__(414), - MinKey = __nccwpck_require__(5325).MinKey, - MaxKey = __nccwpck_require__(5846).MaxKey, - DBRef = __nccwpck_require__(3797).DBRef, - Binary = __nccwpck_require__(5497).Binary; - - var normalizedFunctionString = - __nccwpck_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 - ); - } + }; + /** @internal */ + ObjectId.prototype.toExtendedJSON = function () { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + }; + /** @internal */ + ObjectId.fromExtendedJSON = function (doc) { + return new ObjectId(doc.$oid); + }; + /** + * Converts to a string representation of this Id. + * + * @returns return the 24 character hex string representation. + * @internal + */ + ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + ObjectId.prototype.inspect = function () { + return "new ObjectId(\"" + this.toHexString() + "\")"; + }; + /** @internal */ + ObjectId.index = Math.floor(Math.random() * 0xffffff); + return ObjectId; +}()); +exports.ObjectId = ObjectId; +// Deprecated methods +Object.defineProperty(ObjectId.prototype, 'generate', { + value: utils_1.deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead') +}); +Object.defineProperty(ObjectId.prototype, 'getInc', { + value: utils_1.deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') +}); +Object.defineProperty(ObjectId.prototype, 'get_inc', { + value: utils_1.deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') +}); +Object.defineProperty(ObjectId, 'get_inc', { + value: utils_1.deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') +}); +Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); +//# sourceMappingURL=objectid.js.map + +/***/ }), + +/***/ 7426: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.calculateObjectSize = void 0; +var buffer_1 = __nccwpck_require__(4293); +var binary_1 = __nccwpck_require__(2214); +var constants = __nccwpck_require__(5419); +var utils_1 = __nccwpck_require__(4419); +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); } - - return totalLength; - }; - - /** - * @ignore - * @api private - */ - function calculateElement( - name, - value, - serializeFunctions, - isArray, - ignoreUndefined - ) { + } + else { // 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) - ); + if (object.toBSON) { + object = object.toBSON(); + } + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; +} +exports.calculateObjectSize = calculateObjectSize; +/** @internal */ +function calculateElement(name, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +value, serializeFunctions, isArray, ignoreUndefined) { + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (isArray === void 0) { isArray = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = false; } + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + buffer_1.Buffer.byteLength(name, 'utf8') + 1 + 4 + buffer_1.Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && + value >= constants.JS_INT_MIN && + value <= constants.JS_INT_MAX) { + if (value >= constants.BSON_INT32_MIN && value <= constants.BSON_INT32_MAX) { + // 32 bit + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } + else { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } } - case "undefined": + else { + // 64 bit + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': if (isArray || !ignoreUndefined) - return ( - (name != null ? Buffer.byteLength(name, "utf8") + 1 : 0) + 1 - ); + return (name != null ? buffer_1.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 'boolean': + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || utils_1.isDate(value)) { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + utils_1.isAnyArrayBuffer(value)) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value['_bsontype'] === 'Long' || + value['_bsontype'] === 'Double' || + value['_bsontype'] === 'Timestamp') { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + else if (value['_bsontype'] === 'Decimal128') { + return (name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } + else if (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_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + buffer_1.Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + buffer_1.Buffer.byteLength(value.code.toString(), 'utf8') + + 1); + } + } + else if (value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === binary_1.Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + (value.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1)); + } } - case "function": + else if (value['_bsontype'] === 'Symbol') { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + buffer_1.Buffer.byteLength(value.value, 'utf8') + + 4 + + 1 + + 1); + } + else if (value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + // Add db reference if it exists + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || utils_1.isRegExp(value)) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value['_bsontype'] === 'BSONRegExp') { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_1.Buffer.byteLength(value.pattern, 'utf8') + + 1 + + buffer_1.Buffer.byteLength(value.options, 'utf8') + + 1); + } + else { + return ((name != null ? buffer_1.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 - ); - } + if (value instanceof RegExp || utils_1.isRegExp(value) || String.call(value) === '[object RegExp]') { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + buffer_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_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + buffer_1.Buffer.byteLength(utils_1.normalizedFunctionString(value), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else if (serializeFunctions) { + return ((name != null ? buffer_1.Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + buffer_1.Buffer.byteLength(utils_1.normalizedFunctionString(value), 'utf8') + + 1); + } } - } - - return 0; - } - - var BSON = {}; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; + } + return 0; +} +//# sourceMappingURL=calculate_size.js.map - // 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; +/***/ 719: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - /***/ - }, +"use strict"; - /***/ 2139: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - var Long = __nccwpck_require__(8522).Long, - Double = __nccwpck_require__(972).Double, - Timestamp = __nccwpck_require__(1031).Timestamp, - ObjectID = __nccwpck_require__(9502).ObjectID, - Symbol = __nccwpck_require__(2259).Symbol, - Code = __nccwpck_require__(7113).Code, - MinKey = __nccwpck_require__(5325).MinKey, - MaxKey = __nccwpck_require__(5846).MaxKey, - Decimal128 = __nccwpck_require__(414), - Int32 = __nccwpck_require__(6142), - DBRef = __nccwpck_require__(3797).DBRef, - BSONRegExp = __nccwpck_require__(4636).BSONRegExp, - Binary = __nccwpck_require__(5497).Binary; - - var utils = __nccwpck_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" - ); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; } - - // 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) { + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.deserialize = void 0; +var buffer_1 = __nccwpck_require__(4293); +var binary_1 = __nccwpck_require__(2214); +var code_1 = __nccwpck_require__(2393); +var constants = __nccwpck_require__(5419); +var db_ref_1 = __nccwpck_require__(6528); +var decimal128_1 = __nccwpck_require__(3640); +var double_1 = __nccwpck_require__(9732); +var error_1 = __nccwpck_require__(240); +var int_32_1 = __nccwpck_require__(8070); +var long_1 = __nccwpck_require__(2332); +var max_key_1 = __nccwpck_require__(2281); +var min_key_1 = __nccwpck_require__(5508); +var objectid_1 = __nccwpck_require__(1248); +var regexp_1 = __nccwpck_require__(7709); +var symbol_1 = __nccwpck_require__(2922); +var timestamp_1 = __nccwpck_require__(7431); +var validate_utf8_1 = __nccwpck_require__(9675); +// Internal long versions +var JS_INT_MAX_LONG = long_1.Long.fromNumber(constants.JS_INT_MAX); +var JS_INT_MIN_LONG = long_1.Long.fromNumber(constants.JS_INT_MIN); +var functionCache = {}; +function deserialize(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); + if (size < 5) { + throw new error_1.BSONError("bson size must be >= 5, is " + size); + } + if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { + throw new error_1.BSONError("buffer length " + buffer.length + " must be >= bson size " + size); + } + if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { + throw new error_1.BSONError("buffer length " + buffer.length + " must === bson size " + size); + } + if (size + index > buffer.byteLength) { + throw new error_1.BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")"); + } + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new error_1.BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); +} +exports.deserialize = deserialize; +var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; +function deserializeObject(buffer, index, options, isArray) { + if (isArray === void 0) { isArray = false; } + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + 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']; + // Ensures default validation option if none given + var validation = options.validation == null ? { utf8: true } : options.validation; + // Shows if global utf-8 validation is enabled or disabled + var globalUTFValidation = true; + // Reflects utf-8 validation setting regardless of global or specific key validation + var validationSetting; + // Set of keys either to enable or disable validation on + var utf8KeysSet = new Set(); + // Check for boolean uniformity and empty validation option + var utf8ValidatedKeys = validation.utf8; + if (typeof utf8ValidatedKeys === 'boolean') { + validationSetting = utf8ValidatedKeys; + } + else { + globalUTFValidation = false; + var utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { + return utf8ValidatedKeys[key]; + }); + if (utf8ValidationValues.length === 0) { + throw new error_1.BSONError('UTF-8 validation setting cannot be empty'); + } + if (typeof utf8ValidationValues[0] !== 'boolean') { + throw new error_1.BSONError('Invalid UTF-8 validation option, must specify boolean values'); + } + validationSetting = utf8ValidationValues[0]; + // Ensures boolean uniformity in utf-8 validation (all true or all false) + if (!utf8ValidationValues.every(function (item) { return item === validationSetting; })) { + throw new error_1.BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); + } + } + // Add keys to set that will either be validated or not based on validationSetting + if (!globalUTFValidation) { + for (var _i = 0, _a = Object.keys(utf8ValidatedKeys); _i < _a.length; _i++) { + var key = _a[_i]; + utf8KeysSet.add(key); + } + } + // Set the start index + var startIndex = index; + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) + throw new error_1.BSONError('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_1.BSONError('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; + var isPossibleDBRef = isArray ? false : null; + // While we have more left data left keep parsing + 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 - ); + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.byteLength) + throw new error_1.BSONError('Bad BSON Document: illegal CString'); + // Represents the key + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + // shouldValidateKey is true if the key should be validated, false otherwise + var shouldValidateKey = true; + if (globalUTFValidation || utf8KeysSet.has(name)) { + shouldValidateKey = validationSetting; + } + else { + shouldValidateKey = !validationSetting; + } + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + var value = void 0; + index = i + 1; + if (elementType === constants.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_1.BSONError('bad string length in bson'); + } + value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_OID) { - var oid = utils.allocBuffer(12); + } + else if (elementType === constants.BSON_DATA_OID) { + var oid = buffer_1.Buffer.alloc(12); buffer.copy(oid, 0, index, index + 12); - object[name] = new ObjectID(oid); + value = new objectid_1.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)); + } + else if (elementType === constants.BSON_DATA_INT && promoteValues === false) { + value = new int_32_1.Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); + } + else if (elementType === constants.BSON_DATA_INT) { + value = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } + else if (elementType === constants.BSON_DATA_NUMBER && promoteValues === false) { + value = new double_1.Double(buffer.readDoubleLE(index)); index = index + 8; - } else if (elementType === BSON.BSON_DATA_NUMBER) { - object[name] = buffer.readDoubleLE(index); + } + else if (elementType === constants.BSON_DATA_NUMBER) { + value = 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) { + } + else if (elementType === constants.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); + value = new Date(new long_1.Long(lowBits, highBits).toNumber()); + } + else if (elementType === constants.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) { + throw new error_1.BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === constants.BSON_DATA_OBJECT) { var _index = index; - var objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); + 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"); - + throw new error_1.BSONError('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); + value = buffer.slice(index, index + objectSize); + } + else { + var objectOptions = options; + if (!globalUTFValidation) { + objectOptions = __assign(__assign({}, options), { validation: { utf8: shouldValidateKey } }); + } + value = deserializeObject(buffer, _index, objectOptions, 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); + } + else if (elementType === constants.BSON_DATA_ARRAY) { + var _index = index; + var 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; + arrayOptions = {}; + for (var n in options) { + arrayOptions[n] = options[n]; + } + arrayOptions['raw'] = true; } - - object[name] = deserializeObject( - buffer, - _index, - arrayOptions, - true - ); + if (!globalUTFValidation) { + arrayOptions = __assign(__assign({}, arrayOptions), { validation: { utf8: shouldValidateKey } }); + } + value = 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) { + throw new error_1.BSONError('invalid array terminator byte'); + if (index !== stopIndex) + throw new error_1.BSONError('corrupted array bson'); + } + else if (elementType === constants.BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === constants.BSON_DATA_NULL) { + value = null; + } + else if (elementType === constants.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); + 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); + var long = new long_1.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; + value = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } + else { + value = long; } - } else if (elementType === BSON.BSON_DATA_DECIMAL128) { + } + else if (elementType === constants.BSON_DATA_DECIMAL128) { // Buffer to contain the decimal bytes - var bytes = utils.allocBuffer(16); + var bytes = buffer_1.Buffer.alloc(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); + var decimal128 = new decimal128_1.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); + if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { + value = decimal128.toObject(); + } + else { + value = decimal128; + } + } + else if (elementType === constants.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"); - + throw new error_1.BSONError('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"); - + if (binarySize > buffer.byteLength) + throw new error_1.BSONError('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); - } + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === binary_1.Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new error_1.BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new error_1.BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new error_1.BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + if (promoteBuffers && promoteValues) { + value = buffer.slice(index, index + binarySize); + } + else { + value = new binary_1.Binary(buffer.slice(index, index + binarySize), subType); + } + } + else { + var _buffer = buffer_1.Buffer.alloc(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === binary_1.Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new error_1.BSONError('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new error_1.BSONError('Binary type with subtype 0x02 contains too long binary size'); + if (binarySize < totalBinarySize - 4) + throw new error_1.BSONError('Binary type with subtype 0x02 contains too short binary size'); + } + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + if (promoteBuffers && promoteValues) { + value = _buffer; + } + else { + value = new binary_1.Binary(_buffer, subType); + } } - // Update the index index = index + binarySize; - } else if ( - elementType === BSON.BSON_DATA_REGEXP && - bsonRegExp === false - ) { + } + else if (elementType === constants.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++; + 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"); + throw new error_1.BSONError('Bad BSON Document: illegal CString'); // Return the C string - var source = buffer.toString("utf8", index, i); + 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++; + 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"); + throw new error_1.BSONError('Bad BSON Document: illegal CString'); // Return the C string - var regExpOptions = buffer.toString("utf8", index, i); + 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; - } + 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 - ) { + value = new RegExp(source, optionsArray.join('')); + } + else if (elementType === constants.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++; + 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"); + throw new error_1.BSONError('Bad BSON Document: illegal CString'); // Return the C string - source = buffer.toString("utf8", index, i); + var 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++; + 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"); + throw new error_1.BSONError('Bad BSON Document: illegal CString'); // Return the C string - regExpOptions = buffer.toString("utf8", index, i); + var 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) - ); + value = new regexp_1.BSONRegExp(source, regExpOptions); + } + else if (elementType === constants.BSON_DATA_SYMBOL) { + 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_1.BSONError('bad string length in bson'); + } + var symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); + value = promoteValues ? symbol : new symbol_1.BSONSymbol(symbol); 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 - ); - + } + else if (elementType === constants.BSON_DATA_TIMESTAMP) { + 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); + value = new timestamp_1.Timestamp(lowBits, highBits); + } + else if (elementType === constants.BSON_DATA_MIN_KEY) { + value = new min_key_1.MinKey(); + } + else if (elementType === constants.BSON_DATA_MAX_KEY) { + value = new max_key_1.MaxKey(); + } + else if (elementType === constants.BSON_DATA_CODE) { + 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_1.BSONError('bad string length in bson'); + } + var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); // 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); + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } + else { + value = isolateEval(functionString); + } + } + else { + value = new code_1.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); - + } + else if (elementType === constants.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" - ); + throw new error_1.BSONError('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); + var 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"); - + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) { + throw new error_1.BSONError('bad string length in bson'); + } // Javascript function - functionString = buffer.toString( - "utf8", - index, - index + stringSize - 1 - ); + var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); // Update parse index position index = index + stringSize; // Parse the element - _index = index; + var _index = index; // Decode the size of the object document - objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); + var 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 + // Check if field length is too short if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new Error( - "code_w_scope total size is to short, truncating scope" - ); + throw new error_1.BSONError('code_w_scope total size is too short, truncating scope'); } - - // Check if totalSize field is to long + // Check if totalSize field is too long if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new Error( - "code_w_scope total size is to long, clips outer document" - ); + throw new error_1.BSONError('code_w_scope total size is too 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); + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + // Got to do this to avoid V8 deoptimizing the call due to finding eval + value = isolateEval(functionString, functionCache, object); + } + else { + value = isolateEval(functionString); + } + value.scope = scopeObject; + } + else { + value = new code_1.Code(functionString, scopeObject); } - } else if (elementType === BSON.BSON_DATA_DBPOINTER) { + } + else if (elementType === constants.BSON_DATA_DBPOINTER) { // Get the code string size - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); + var 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"); + if (stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0) + throw new error_1.BSONError('bad string length in bson'); // Namespace - var namespace = buffer.toString( - "utf8", - index, - index + stringSize - 1 - ); + if (validation != null && validation.utf8) { + if (!validate_utf8_1.validateUtf8(buffer, index, index + stringSize - 1)) { + throw new error_1.BSONError('Invalid UTF-8 string in BSON document'); + } + } + var namespace = buffer.toString('utf8', index, index + stringSize - 1); // Update parse index position index = index + stringSize; - // Read the oid - var oidBuffer = utils.allocBuffer(12); + var oidBuffer = buffer_1.Buffer.alloc(12); buffer.copy(oidBuffer, 0, index, index + 12); - oid = new ObjectID(oidBuffer); - + var oid = new objectid_1.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' - ); - } + value = new db_ref_1.DBRef(namespace, oid); } - - // 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"); + else { + throw new error_1.BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"'); } - - // Check if we have a db ref object - if (object["$id"] != null) - object = new DBRef(object["$ref"], object["$id"], object["$db"]); + if (name === '__proto__') { + Object.defineProperty(object, name, { + value: value, + writable: true, + enumerable: true, + configurable: true + }); + } + else { + object[name] = value; + } + } + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) + throw new error_1.BSONError('corrupt array bson'); + throw new error_1.BSONError('corrupt object bson'); + } + // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef + if (!isPossibleDBRef) 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, - __nccwpck_require__ - ) => { - "use strict"; - - var writeIEEE754 = __nccwpck_require__(7281) /* .writeIEEE754 */.P, - Long = __nccwpck_require__(8522).Long, - Map = __nccwpck_require__(3639), - Binary = __nccwpck_require__(5497).Binary; - - var normalizedFunctionString = - __nccwpck_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; + if (db_ref_1.isDBRefLike(object)) { + var copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new db_ref_1.DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; +} +/** + * Ensure eval is isolated, store the result in functionCache. + * + * @internal + */ +function isolateEval(functionString, functionCache, object) { + if (!functionCache) + return new Function(functionString); + // Check for cache hit, eval if missing and return cached function + if (functionCache[functionString] == null) { + functionCache[functionString] = new Function(functionString); + } + // Set the object + return functionCache[functionString].bind(object); +} +function getValidatedString(buffer, start, end, shouldValidateUtf8) { + var value = buffer.toString('utf8', start, end); + // if utf8 validation is on, do the check + if (shouldValidateUtf8) { + for (var i = 0; i < value.length; i++) { + if (value.charCodeAt(i) === 0xfffd) { + if (!validate_utf8_1.validateUtf8(buffer, start, end)) { + throw new error_1.BSONError('Invalid UTF-8 string in BSON document'); + } + break; + } + } + } + return value; +} +//# sourceMappingURL=deserializer.js.map + +/***/ }), + +/***/ 673: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.serializeInto = void 0; +var binary_1 = __nccwpck_require__(2214); +var constants = __nccwpck_require__(5419); +var ensure_buffer_1 = __nccwpck_require__(6669); +var error_1 = __nccwpck_require__(240); +var extended_json_1 = __nccwpck_require__(6602); +var float_parser_1 = __nccwpck_require__(5742); +var long_1 = __nccwpck_require__(2332); +var map_1 = __nccwpck_require__(2935); +var utils_1 = __nccwpck_require__(4419); +var regexp = /\x00/; // eslint-disable-line no-control-regex +var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); +/* + * isArray indicates if we are writing to a BSON array (type 0x04) + * which forces the "key" which really an array index as a string to be written as ascii + * This will catch any errors in index as a string generation + */ +function serializeString(buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = constants.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, undefined, '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; +} +function serializeNumber(buffer, key, value, index, isArray) { + // We have an integer value + // TODO(NODE-2529): Add support for big int + if (Number.isInteger(value) && + value >= constants.BSON_INT32_MIN && + value <= constants.BSON_INT32_MAX) { + // If the value fits in 32 bits encode as int32 + // Set int type 32 bits or less + buffer[index++] = constants.BSON_DATA_INT; // Number of written bytes var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, "utf8") - : buffer.write(key, index, "ascii"); + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, '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 + index = index + numberOfWrittenBytes; 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; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } + else { + // Encode as double + buffer[index++] = constants.BSON_DATA_NUMBER; // Number of written bytes var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, "utf8") - : buffer.write(key, index, "ascii"); + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; - return index; - }; - - var serializeBoolean = function (buffer, key, value, index, isArray) { + // Write float + float_parser_1.writeIEEE754(buffer, value, index, 'little', 52, 8); + // Adjust index + index = index + 8; + } + return index; +} +function serializeNull(buffer, key, _, index, isArray) { + // Set long type + buffer[index++] = constants.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeBoolean(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +} +function serializeDate(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var dateInMilis = long_1.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; +} +function serializeRegExp(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, '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, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.ignoreCase) + buffer[index++] = 0x69; // i + if (value.global) + buffer[index++] = 0x73; // s + if (value.multiline) + buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; +} +function serializeBSONRegExp(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, '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, undefined, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; +} +function serializeMinMax(buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = constants.BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = constants.BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = constants.BSON_DATA_MAX_KEY; + } + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeObjectId(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, '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, undefined, 'binary'); + } + else if (utils_1.isUint8Array(value.id)) { + // Use the standard JS methods here because buffer.copy() is buggy with the + // browser polyfill + buffer.set(value.id.subarray(0, 12), index); + } + else { + throw new error_1.BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + // Adjust index + return index + 12; +} +function serializeBuffer(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, '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++] = constants.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + buffer.set(ensure_buffer_1.ensureBuffer(value), index); + // Adjust the index + index = index + size; + return index; +} +function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { + if (checkKeys === void 0) { checkKeys = false; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (isArray === void 0) { isArray = false; } + if (path === void 0) { path = []; } + for (var i = 0; i < path.length; i++) { + if (path[i] === value) + throw new error_1.BSONError('cyclic dependency detected'); + } + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? constants.BSON_DATA_ARRAY : constants.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, '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(); + return endIndex; +} +function serializeDecimal128(buffer, key, value, index, isArray) { + buffer[index++] = constants.BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + // Prefer the standard JS methods because their typechecking is not buggy, + // unlike the `buffer` polyfill's. + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; +} +function serializeLong(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = + value._bsontype === 'Long' ? constants.BSON_DATA_LONG : constants.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, '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; +} +function serializeInt32(buffer, key, value, index, isArray) { + value = value.valueOf(); + // Set int type 32 bits or less + buffer[index++] = constants.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, '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; +} +function serializeDouble(buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = constants.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + float_parser_1.writeIEEE754(buffer, value.value, index, 'little', 52, 8); + // Adjust index + index = index + 8; + return index; +} +function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) { + if (_checkKeys === void 0) { _checkKeys = false; } + if (_depth === void 0) { _depth = 0; } + buffer[index++] = constants.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = utils_1.normalizedFunctionString(value); + // Write the string + var size = buffer.write(functionString, index + 4, undefined, '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; +} +function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { + if (checkKeys === void 0) { checkKeys = false; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (isArray === void 0) { isArray = false; } + if (value.scope && typeof value.scope === 'object') { // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; + buffer[index++] = constants.BSON_DATA_CODE_W_SCOPE; // Number of written bytes var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, "utf8") - : buffer.write(key, index, "ascii"); + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, '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; + // 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, undefined, '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++] = constants.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; - - // 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"); + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Function string - var functionString = normalizedFunctionString(value); - + var functionString = value.code.toString(); // Write the string - var size = buffer.write(functionString, index + 4, "utf8") + 1; + var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1; // Write the size of the string to buffer buffer[index] = size & 0xff; buffer[index + 1] = (size >> 8) & 0xff; @@ -6225,13974 +5421,10803 @@ 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 + } + return index; +} +function serializeBinary(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, '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_1.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_1.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 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; + } + // Write the data to the object + buffer.set(data, index); + // Adjust the index + index = index + value.position; + return index; +} +function serializeSymbol(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, undefined, '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; +} +function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = constants.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, undefined, 'utf8') + : buffer.write(key, index, undefined, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var startIndex = index; + var output = { + $ref: value.collection || value.namespace, + $id: value.oid + }; + if (value.db != null) { + output.$db = value.db; + } + output = Object.assign(output, value.fields); + var endIndex = serializeInto(buffer, output, 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; +} +function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (checkKeys === void 0) { checkKeys = false; } + if (startingIndex === void 0) { startingIndex = 0; } + if (depth === void 0) { depth = 0; } + if (serializeFunctions === void 0) { serializeFunctions = false; } + if (ignoreUndefined === void 0) { ignoreUndefined = true; } + if (path === void 0) { path = []; } + startingIndex = startingIndex || 0; + path = path || []; + // Push the object to the path + path.push(object); + // Start place to serialize into + var index = startingIndex + 4; + // 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(); + if (typeof value.toBSON !== 'function') + throw new error_1.BSONTypeError('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 === "bigint") { - throw new TypeError( - "Unsupported type BigInt, please use Decimal128" - ); - } 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"] - ); + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index, true); } - } - } else if (object instanceof Map) { - var iterator = object.entries(); - var done = false; - - while (!done) { + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } + else if (typeof value === 'bigint') { + throw new error_1.BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } + else if (value instanceof Date || utils_1.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 (utils_1.isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } + else if (value instanceof RegExp || utils_1.isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } + else if (typeof value === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); + } + else if (typeof value === 'object' && + extended_json_1.isBSONType(value) && + 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, 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 error_1.BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); + } + } + } + else if (object instanceof map_1.Map || utils_1.isMap(object)) { + var iterator = object.entries(); + var done = false; + while (!done) { // Unpack the next entry var entry = iterator.next(); - done = entry.done; + done = !!entry.done; // Are we done, then skip and terminate - if (done) continue; - + if (done) + continue; // Get the entry values - key = entry.value[0]; - value = entry.value[1]; - + var key = entry.value[0]; + var value = entry.value[1]; // Check the type of the value - type = typeof value; - + var 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 (typeof key === 'string' && !ignoreKeys.has(key)) { + 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 === "bigint") { - throw new TypeError( - "Unsupported type BigInt, please use Decimal128" - ); - } 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"] - ); + if (type === 'string') { + index = serializeString(buffer, key, value, index); } - } - } 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(); + else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); } - - // 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 '.'"); - } - } + else if (type === 'bigint' || utils_1.isBigInt64Array(value) || utils_1.isBigUInt64Array(value)) { + throw new error_1.BSONTypeError('Unsupported type BigInt, please use Decimal128'); } - - if (type === "string") { - index = serializeString(buffer, key, value, index); - } else if (type === "number") { - index = serializeNumber(buffer, key, value, index); - } else if (type === "bigint") { - throw new TypeError( - "Unsupported type BigInt, please use Decimal128" - ); - } 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) + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || utils_1.isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === null || (value === undefined && 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"] - ); } - } + else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } + else if (utils_1.isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || utils_1.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 error_1.BSONTypeError('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_1.BSONTypeError('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') + throw new error_1.BSONTypeError('toBSON function did not return an object'); + } + // Iterate over all the keys + for (var key in object) { + var value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') + throw new error_1.BSONTypeError('toBSON is not a function'); + value = value.toBSON(); + } + // Check the type of the value + var type = typeof value; + // Check the key and throw error if it's illegal + if (typeof key === 'string' && !ignoreKeys.has(key)) { + 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 === 'bigint') { + throw new error_1.BSONTypeError('Unsupported type BigInt, please use Decimal128'); + } + else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || utils_1.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 (utils_1.isUint8Array(value)) { + index = serializeBuffer(buffer, key, value, index); + } + else if (value instanceof RegExp || utils_1.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 error_1.BSONTypeError('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; +} +exports.serializeInto = serializeInto; +//# sourceMappingURL=serializer.js.map + +/***/ }), + +/***/ 4419: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.deprecate = exports.isObjectLike = exports.isDate = exports.haveBuffer = exports.isMap = exports.isRegExp = exports.isBigUInt64Array = exports.isBigInt64Array = exports.isUint8Array = exports.isAnyArrayBuffer = exports.randomBytes = exports.normalizedFunctionString = void 0; +var buffer_1 = __nccwpck_require__(4293); +var global_1 = __nccwpck_require__(207); +/** + * Normalizes our expected stringified form of a function across versions of node + * @param fn - The function to stringify + */ +function normalizedFunctionString(fn) { + return fn.toString().replace('function(', 'function ('); +} +exports.normalizedFunctionString = normalizedFunctionString; +function isReactNative() { + var g = global_1.getGlobal(); + return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative'; +} +var insecureRandomBytes = function insecureRandomBytes(size) { + var insecureWarning = isReactNative() + ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' + : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.'; + console.warn(insecureWarning); + var result = buffer_1.Buffer.alloc(size); + for (var i = 0; i < size; ++i) + result[i] = Math.floor(Math.random() * 256); + return result; +}; +var detectRandomBytes = function () { + if (typeof window !== 'undefined') { + // browser crypto implementation(s) + var target_1 = window.crypto || window.msCrypto; // allow for IE11 + if (target_1 && target_1.getRandomValues) { + return function (size) { return target_1.getRandomValues(buffer_1.Buffer.alloc(size)); }; + } + } + if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) { + // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global + return function (size) { return global.crypto.getRandomValues(buffer_1.Buffer.alloc(size)); }; + } + var requiredRandomBytes; + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + requiredRandomBytes = __nccwpck_require__(6417).randomBytes; + } + catch (e) { + // keep the fallback + } + // NOTE: in transpiled cases the above require might return null/undefined + return requiredRandomBytes || insecureRandomBytes; +}; +exports.randomBytes = detectRandomBytes(); +function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); +} +exports.isAnyArrayBuffer = isAnyArrayBuffer; +function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} +exports.isUint8Array = isUint8Array; +function isBigInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigInt64Array]'; +} +exports.isBigInt64Array = isBigInt64Array; +function isBigUInt64Array(value) { + return Object.prototype.toString.call(value) === '[object BigUint64Array]'; +} +exports.isBigUInt64Array = isBigUInt64Array; +function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; +function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; +} +exports.isMap = isMap; +/** Call to check if your environment has `Buffer` */ +function haveBuffer() { + return typeof global !== 'undefined' && typeof global.Buffer !== 'undefined'; +} +exports.haveBuffer = haveBuffer; +// To ensure that 0.4 of node works correctly +function isDate(d) { + return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; +} +exports.isDate = isDate; +/** + * @internal + * this is to solve the `'someKey' in x` problem where x is unknown. + * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753 + */ +function isObjectLike(candidate) { + return typeof candidate === 'object' && candidate !== null; +} +exports.isObjectLike = isObjectLike; +function deprecate(fn, message) { + var warned = false; + function deprecated() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (!warned) { + console.warn(message); + warned = true; + } + return fn.apply(this, args); + } + return deprecated; +} +exports.deprecate = deprecate; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 7709: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BSONRegExp = void 0; +var error_1 = __nccwpck_require__(240); +function alphabetize(str) { + return str.split('').sort().join(''); +} +/** + * A class representation of the BSON RegExp type. + * @public + */ +var BSONRegExp = /** @class */ (function () { + /** + * @param pattern - The regular expression pattern to match + * @param options - The regular expression options + */ + function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) + return new BSONRegExp(pattern, options); + this.pattern = pattern; + this.options = alphabetize(options !== null && options !== void 0 ? options : ''); + if (this.pattern.indexOf('\x00') !== -1) { + throw new error_1.BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern)); + } + if (this.options.indexOf('\x00') !== -1) { + throw new error_1.BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options)); } - - // 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" - ); - } + 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_1.BSONError("The regular expression option [" + this.options[i] + "] is not supported"); + } } - } + } + BSONRegExp.parseOptions = function (options) { + return options ? options.split('').sort().join('') : ''; + }; + /** @internal */ + BSONRegExp.prototype.toExtendedJSON = function (options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + }; + /** @internal */ + BSONRegExp.fromExtendedJSON = function (doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + // This is for $regex query operators that have extended json values. + if (doc.$regex._bsontype === 'BSONRegExp') { + return doc; + } + } + else { + return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); + } + } + if ('$regularExpression' in doc) { + return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); + } + throw new error_1.BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc)); + }; + return BSONRegExp; +}()); +exports.BSONRegExp = BSONRegExp; +Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); +//# sourceMappingURL=regexp.js.map - module.exports = BSONRegExp; - module.exports.BSONRegExp = BSONRegExp; +/***/ }), - /***/ - }, +/***/ 2922: +/***/ ((__unused_webpack_module, exports) => { - /***/ 2259: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - // Custom inspect property name / symbol. - var inspect = Buffer - ? __nccwpck_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; - } +"use strict"; - /** - * Access the wrapped string value. - * - * @method - * @return {String} returns the wrapped string. - */ - Symbol.prototype.valueOf = function () { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BSONSymbol = void 0; +/** + * A class representation of the BSON Symbol type. + * @public + */ +var BSONSymbol = /** @class */ (function () { + /** + * @param value - the string representing the symbol. + */ + function BSONSymbol(value) { + if (!(this instanceof BSONSymbol)) + return new BSONSymbol(value); + this.value = value; + } + /** Access the wrapped string value. */ + BSONSymbol.prototype.valueOf = function () { return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype.toString = function () { + }; + BSONSymbol.prototype.toString = function () { return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype[inspect] = function () { + }; + /** @internal */ + BSONSymbol.prototype.inspect = function () { + return "new BSONSymbol(\"" + this.value + "\")"; + }; + BSONSymbol.prototype.toJSON = function () { return this.value; - }; + }; + /** @internal */ + BSONSymbol.prototype.toExtendedJSON = function () { + return { $symbol: this.value }; + }; + /** @internal */ + BSONSymbol.fromExtendedJSON = function (doc) { + return new BSONSymbol(doc.$symbol); + }; + /** @internal */ + BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + return BSONSymbol; +}()); +exports.BSONSymbol = BSONSymbol; +Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); +//# sourceMappingURL=symbol.js.map - /** - * @ignore - */ - Symbol.prototype.toJSON = function () { - return this.value; - }; +/***/ }), - module.exports = Symbol; - module.exports.Symbol = Symbol; +/***/ 7431: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - /***/ - }, +"use strict"; - /***/ 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"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Timestamp = exports.LongWithoutOverridesClass = void 0; +var long_1 = __nccwpck_require__(2332); +var utils_1 = __nccwpck_require__(4419); +/** @public */ +exports.LongWithoutOverridesClass = long_1.Long; +/** @public */ +var Timestamp = /** @class */ (function (_super) { + __extends(Timestamp, _super); + function Timestamp(low, high) { + var _this = this; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + ///@ts-expect-error + if (!(_this instanceof Timestamp)) + return new Timestamp(low, high); + if (long_1.Long.isLong(low)) { + _this = _super.call(this, low.low, low.high, true) || this; + } + else if (utils_1.isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') { + _this = _super.call(this, low.i, low.t, true) || this; + } + else { + _this = _super.call(this, low, high, true) || this; + } + Object.defineProperty(_this, '_bsontype', { + value: 'Timestamp', + writable: false, + configurable: false, + enumerable: false + }); + return _this; + } + Timestamp.prototype.toJSON = function () { + return { + $timestamp: this.toString() + }; + }; + /** Returns a Timestamp represented by the given (32-bit) integer value. */ + Timestamp.fromInt = function (value) { + return new Timestamp(long_1.Long.fromInt(value, true)); + }; + /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */ + Timestamp.fromNumber = function (value) { + return new Timestamp(long_1.Long.fromNumber(value, true)); + }; + /** + * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits. + * + * @param lowBits - the low 32-bits. + * @param highBits - the high 32-bits. + */ + Timestamp.fromBits = function (lowBits, highBits) { + return new Timestamp(lowBits, highBits); + }; + /** + * Returns a Timestamp from the given string, optionally using the given radix. + * + * @param str - the textual representation of the Timestamp. + * @param optRadix - the radix in which the text is written. + */ + Timestamp.fromString = function (str, optRadix) { + return new Timestamp(long_1.Long.fromString(str, true, optRadix)); + }; + /** @internal */ + Timestamp.prototype.toExtendedJSON = function () { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + }; + /** @internal */ + Timestamp.fromExtendedJSON = function (doc) { + return new Timestamp(doc.$timestamp); + }; + /** @internal */ + Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + Timestamp.prototype.inspect = function () { + return "new Timestamp({ t: " + this.getHighBits() + ", i: " + this.getLowBits() + " })"; + }; + Timestamp.MAX_VALUE = long_1.Long.MAX_UNSIGNED_VALUE; + return Timestamp; +}(exports.LongWithoutOverridesClass)); +exports.Timestamp = Timestamp; +//# sourceMappingURL=timestamp.js.map + +/***/ }), + +/***/ 207: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getGlobal = void 0; +function checkForMath(potentialGlobal) { + // eslint-disable-next-line eqeqeq + return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal; +} +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +function getGlobal() { + // eslint-disable-next-line no-undef + return (checkForMath(typeof globalThis === 'object' && globalThis) || + checkForMath(typeof window === 'object' && window) || + checkForMath(typeof self === 'object' && self) || + checkForMath(typeof global === 'object' && global) || + Function('return this')()); +} +exports.getGlobal = getGlobal; +//# sourceMappingURL=global.js.map + +/***/ }), + +/***/ 2568: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.UUID = void 0; +var buffer_1 = __nccwpck_require__(4293); +var ensure_buffer_1 = __nccwpck_require__(6669); +var binary_1 = __nccwpck_require__(2214); +var uuid_utils_1 = __nccwpck_require__(3152); +var utils_1 = __nccwpck_require__(4419); +var error_1 = __nccwpck_require__(240); +var BYTE_LENGTH = 16; +var kId = Symbol('id'); +/** + * A class representation of the BSON UUID type. + * @public + */ +var UUID = /** @class */ (function () { + /** + * Create an UUID type + * + * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer. + */ + function UUID(input) { + if (typeof input === 'undefined') { + // The most common use case (blank id, new UUID() instance) + this.id = UUID.generate(); + } + else if (input instanceof UUID) { + this[kId] = buffer_1.Buffer.from(input.id); + this.__id = input.__id; + } + else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { + this.id = ensure_buffer_1.ensureBuffer(input); + } + else if (typeof input === 'string') { + this.id = uuid_utils_1.uuidHexStringToBuffer(input); + } + else { + throw new error_1.BSONTypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); + } + } + Object.defineProperty(UUID.prototype, "id", { /** - * @type {number} - * @ignore + * The UUID bytes + * @readonly */ - this.low_ = low | 0; // force into 32 signed bits. + get: function () { + return this[kId]; + }, + set: function (value) { + this[kId] = value; + if (UUID.cacheHexString) { + this.__id = uuid_utils_1.bufferToUuidHexString(value); + } + }, + enumerable: false, + configurable: true + }); + /** + * Generate a 16 byte uuid v4 buffer used in UUIDs + */ + /** + * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated) + * @param includeDashes - should the string exclude dash-separators. + * */ + UUID.prototype.toHexString = function (includeDashes) { + if (includeDashes === void 0) { includeDashes = true; } + if (UUID.cacheHexString && this.__id) { + return this.__id; + } + var uuidHexString = uuid_utils_1.bufferToUuidHexString(this.id, includeDashes); + if (UUID.cacheHexString) { + this.__id = uuidHexString; + } + return uuidHexString; + }; + /** + * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified. + */ + UUID.prototype.toString = function (encoding) { + return encoding ? this.id.toString(encoding) : this.toHexString(); + }; + /** + * Converts the id into its JSON string representation. + * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + */ + UUID.prototype.toJSON = function () { + return this.toHexString(); + }; + /** + * Compares the equality of this UUID with `otherID`. + * + * @param otherId - UUID instance to compare against. + */ + UUID.prototype.equals = function (otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return otherId.id.equals(this.id); + } + try { + return new UUID(otherId).id.equals(this.id); + } + catch (_a) { + return false; + } + }; + /** + * Creates a Binary instance from the current UUID. + */ + UUID.prototype.toBinary = function () { + return new binary_1.Binary(this.id, binary_1.Binary.SUBTYPE_UUID); + }; + /** + * Generates a populated buffer containing a v4 uuid + */ + UUID.generate = function () { + var bytes = utils_1.randomBytes(BYTE_LENGTH); + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return buffer_1.Buffer.from(bytes); + }; + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + UUID.isValid = function (input) { + if (!input) { + return false; + } + if (input instanceof UUID) { + return true; + } + if (typeof input === 'string') { + return uuid_utils_1.uuidValidateString(input); + } + if (utils_1.isUint8Array(input)) { + // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3) + if (input.length !== BYTE_LENGTH) { + return false; + } + try { + // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx + // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx + return parseInt(input[6].toString(16)[0], 10) === binary_1.Binary.SUBTYPE_UUID; + } + catch (_a) { + return false; + } + } + return false; + }; + /** + * Creates an UUID from a hex string representation of an UUID. + * @param hexString - 32 or 36 character hex string (dashes excluded/included). + */ + UUID.createFromHexString = function (hexString) { + var buffer = uuid_utils_1.uuidHexStringToBuffer(hexString); + return new UUID(buffer); + }; + /** + * Converts to a string representation of this Id. + * + * @returns return the 36 character hex string representation. + * @internal + */ + UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { + return this.inspect(); + }; + UUID.prototype.inspect = function () { + return "new UUID(\"" + this.toHexString() + "\")"; + }; + return UUID; +}()); +exports.UUID = UUID; +Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); +//# sourceMappingURL=uuid.js.map + +/***/ }), + +/***/ 3152: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.bufferToUuidHexString = exports.uuidHexStringToBuffer = exports.uuidValidateString = void 0; +var buffer_1 = __nccwpck_require__(4293); +var error_1 = __nccwpck_require__(240); +// Validation regex for v4 uuid (validates with or without dashes) +var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; +var uuidValidateString = function (str) { + return typeof str === 'string' && VALIDATION_REGEX.test(str); +}; +exports.uuidValidateString = uuidValidateString; +var uuidHexStringToBuffer = function (hexString) { + if (!exports.uuidValidateString(hexString)) { + throw new error_1.BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'); + } + var sanitizedHexString = hexString.replace(/-/g, ''); + return buffer_1.Buffer.from(sanitizedHexString, 'hex'); +}; +exports.uuidHexStringToBuffer = uuidHexStringToBuffer; +var bufferToUuidHexString = function (buffer, includeDashes) { + if (includeDashes === void 0) { includeDashes = true; } + return includeDashes + ? buffer.toString('hex', 0, 4) + + '-' + + buffer.toString('hex', 4, 6) + + '-' + + buffer.toString('hex', 6, 8) + + '-' + + buffer.toString('hex', 8, 10) + + '-' + + buffer.toString('hex', 10, 16) + : buffer.toString('hex'); +}; +exports.bufferToUuidHexString = bufferToUuidHexString; +//# sourceMappingURL=uuid_utils.js.map + +/***/ }), + +/***/ 9675: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.validateUtf8 = void 0; +var FIRST_BIT = 0x80; +var FIRST_TWO_BITS = 0xc0; +var FIRST_THREE_BITS = 0xe0; +var FIRST_FOUR_BITS = 0xf0; +var FIRST_FIVE_BITS = 0xf8; +var TWO_BIT_CHAR = 0xc0; +var THREE_BIT_CHAR = 0xe0; +var FOUR_BIT_CHAR = 0xf0; +var CONTINUING_CHAR = 0x80; +/** + * Determines if the passed in bytes are valid utf8 + * @param bytes - An array of 8-bit bytes. Must be indexable and have length property + * @param start - The index to start validating + * @param end - The index to end validating + */ +function validateUtf8(bytes, start, end) { + var continuation = 0; + for (var i = start; i < end; i += 1) { + var byte = bytes[i]; + if (continuation) { + if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { + return false; + } + continuation -= 1; + } + else if (byte & FIRST_BIT) { + if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { + continuation = 1; + } + else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { + continuation = 2; + } + else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { + continuation = 3; + } + else { + return false; + } + } + } + return !continuation; +} +exports.validateUtf8 = validateUtf8; +//# sourceMappingURL=validate_utf8.js.map - /** - * @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_; - }; +/***/ 4697: +/***/ ((module) => { - /** - * 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() - ); - }; +/** + * Helpers. + */ - /** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ - Timestamp.prototype.toJSON = function () { - return this.toString(); - }; +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; - /** - * 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); - } +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ - if (this.isZero()) { - return "0"; - } +module.exports = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - 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); - } - } +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} - // 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)); +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - rem = this; - var result = ""; +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = "0" + digits; - } - result = "" + digits + result; - } - } - }; +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} - /** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ - Timestamp.prototype.getHighBits = function () { - return this.high_; - }; +/** + * Pluralization helper. + */ - /** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ - Timestamp.prototype.getLowBits = function () { - return this.low_; - }; +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} - /** - * 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; - }; +/***/ 8222: +/***/ ((module, exports, __nccwpck_require__) => { - /** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ - Timestamp.prototype.isNegative = function () { - return this.high_ < 0; - }; +/* eslint-env browser */ - /** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ - Timestamp.prototype.isOdd = function () { - return (this.low_ & 1) === 1; - }; +/** + * This is the web browser implementation of `debug()`. + */ - /** - * 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_; - }; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); - /** - * 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_; - }; +/** + * Colors. + */ - /** - * 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; - }; +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ - /** - * 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; - }; +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ - /** - * 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; - }; +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ +function log(...args) { + // This hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return typeof console === 'object' && + console.log && + console.log(...args); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ - /** - * 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; - }; +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} - /** - * 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; - } +module.exports = __nccwpck_require__(6243)(exports); - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } +const {formatters} = module.exports; - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } - }; +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ - /** - * 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); - } - }; +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; - /** - * 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; +/***/ 6243: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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()); - }; +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ - /** - * 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; - } +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __nccwpck_require__(4697); + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * Active `debug` instances. + */ + createDebug.instances = []; + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return match; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = createDebug.enabled(namespace); + debug.useColors = createDebug.useColors(); + debug.color = selectColor(namespace); + debug.destroy = destroy; + debug.extend = extend; + // Debug.formatArgs = formatArgs; + // debug.rawLog = rawLog; + + // env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + createDebug.instances.push(debug); + + return debug; + } + + function destroy() { + const index = createDebug.instances.indexOf(this); + if (index !== -1) { + createDebug.instances.splice(index, 1); + return true; + } + return false; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + + for (i = 0; i < createDebug.instances.length; i++) { + const instance = createDebug.instances[i]; + instance.enabled = createDebug.enabled(instance.namespace); + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +module.exports = setup; + + +/***/ }), + +/***/ 8237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ - 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 (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(8222); +} else { + module.exports = __nccwpck_require__(5332); +} - 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. +/***/ 5332: +/***/ ((module, exports, __nccwpck_require__) => { - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; +/** + * Module dependencies. + */ - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; +const tty = __nccwpck_require__(3867); +const util = __nccwpck_require__(1669); - 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); - }; +/** + * This is the Node.js implementation of `debug()`. + */ - /** - * 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; - } +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; - 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(); - } +/** + * Colors. + */ - // 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); - } +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __nccwpck_require__(9318); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - // 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; - } +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; - }; +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} - /** - * 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)); - }; +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ - /** - * 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_); - }; +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ - /** - * 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_ - ); - }; +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} - /** - * 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_ - ); - }; +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - /** - * 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_ - ); - }; +function load() { + return process.env.DEBUG; +} - /** - * 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)); - } - } - }; +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ - /** - * 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 - ); - } - } - }; +function init(debug) { + debug.inspectOpts = {}; - /** - * 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); - } - } - }; + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} - /** - * 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; - } - } +module.exports = __nccwpck_require__(6243)(exports); - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; - }; +const {formatters} = module.exports; - /** - * 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 - ); - } - }; +/** + * Map %o to `util.inspect()`, all on a single line. + */ - /** - * 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); - }; +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .replace(/\s*\n\s*/g, ' '); +}; - /** - * 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"); - } +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error("radix out of range: " + radix); - } +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; - 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; - }; +/***/ 2342: +/***/ ((module) => { - // 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; - - /***/ - }, +"use strict"; - /***/ 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()`. +/** + * Custom implementation of a double ended queue. + */ +function Denque(array, options) { + var options = options || {}; + + this._head = 0; + this._tail = 0; + this._capacity = options.capacity; + this._capacityMask = 0x3; + this._list = new Array(4); + if (Array.isArray(array)) { + this._fromArray(array); + } +} - function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === "[object Array]"; - } - exports.isArray = isArray; +/** + * -------------- + * PUBLIC API + * ------------- + */ - function isBoolean(arg) { - return typeof arg === "boolean"; - } - exports.isBoolean = isBoolean; +/** + * 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 peekAt() + * @param i + * @returns {*} + */ +Denque.prototype.get = function get(i) { + return this.peekAt(i); +}; - function isNull(arg) { - return arg === null; - } - exports.isNull = isNull; +/** + * 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(); +}; - function isNullOrUndefined(arg) { - return arg == null; - } - exports.isNullOrUndefined = isNullOrUndefined; +/** + * 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); +}; - function isNumber(arg) { - return typeof arg === "number"; - } - exports.isNumber = isNumber; +/** + * Returns the current length of the queue + * @return {Number} + */ +Object.defineProperty(Denque.prototype, 'length', { + get: function length() { + return this.size(); + } +}); - function isString(arg) { - return typeof arg === "string"; +/** + * 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 (arguments.length === 0) 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._capacity && this.size() > this._capacity) this.pop(); + 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 (arguments.length === 0) 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._capacity && this.size() > this._capacity) { + this.shift(); + } + 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; } - exports.isString = isString; - - function isSymbol(arg) { - return typeof arg === "symbol"; + while (arg_len > arguments_index) { + this.unshift(arguments[--arg_len]); } - exports.isSymbol = isSymbol; - - function isUndefined(arg) { - return arg === void 0; + for (k = i; k > 0; k--) { + this.unshift(temp[k - 1]); } - exports.isUndefined = isUndefined; - - function isRegExp(re) { - return objectToString(re) === "[object RegExp]"; + } 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]; } - exports.isRegExp = isRegExp; - - function isObject(arg) { - return typeof arg === "object" && arg !== null; + 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; } - exports.isObject = isObject; - - function isDate(d) { - return objectToString(d) === "[object Date]"; + while (arguments_index < arg_len) { + this.push(arguments[arguments_index++]); } - exports.isDate = isDate; - - function isError(e) { - return objectToString(e) === "[object Error]" || e instanceof Error; + for (k = 0; k < leng; k++) { + this.push(temp[k]); } - exports.isError = isError; + } + return removed; + } else { + return this.remove(i, count); + } +}; - function isFunction(arg) { - return typeof arg === "function"; - } - exports.isFunction = isFunction; +/** + * 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; +}; - 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; +/** + * Returns an array of all queue items. + * @returns {Array} + */ +Denque.prototype.toArray = function toArray() { + return this._copyArray(false); +}; + +/** + * ------------- + * INTERNALS + * ------------- + */ - exports.isBuffer = Buffer.isBuffer; +/** + * 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]); +}; - function objectToString(o) { - return Object.prototype.toString.call(o); - } +/** + * + * @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; + } - /***/ 4697: /***/ (module) => { - /** - * Helpers. - */ - - var s = 1000; - var m = s * 60; - var h = m * 60; - var d = h * 24; - var w = d * 7; - var y = d * 365.25; - - /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - - module.exports = function (val, options) { - options = options || {}; - var type = typeof val; - if (type === "string" && val.length > 0) { - return parse(val); - } else if (type === "number" && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - "val is not a non-empty string or a valid number. val=" + - JSON.stringify(val) - ); - }; + // head is at 0 and array is now full, safe to extend + this._tail = this._list.length; - /** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - - function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = - /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || "ms").toLowerCase(); - switch (type) { - case "years": - case "year": - case "yrs": - case "yr": - case "y": - return n * y; - case "weeks": - case "week": - case "w": - return n * w; - case "days": - case "day": - case "d": - return n * d; - case "hours": - case "hour": - case "hrs": - case "hr": - case "h": - return n * h; - case "minutes": - case "minute": - case "mins": - case "min": - case "m": - return n * m; - case "seconds": - case "second": - case "secs": - case "sec": - case "s": - return n * s; - case "milliseconds": - case "millisecond": - case "msecs": - case "msec": - case "ms": - return n; - default: - return undefined; - } - } + this._list.length <<= 1; + this._capacityMask = (this._capacityMask << 1) | 1; +}; - /** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +/** + * Shrinks the internal list array. + * @private + */ +Denque.prototype._shrinkArray = function _shrinkArray() { + this._list.length >>>= 1; + this._capacityMask >>>= 1; +}; - function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + "d"; - } - if (msAbs >= h) { - return Math.round(ms / h) + "h"; - } - if (msAbs >= m) { - return Math.round(ms / m) + "m"; - } - if (msAbs >= s) { - return Math.round(ms / s) + "s"; - } - return ms + "ms"; - } - /** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +module.exports = Denque; - function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, "day"); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, "hour"); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, "minute"); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, "second"); - } - return ms + " ms"; - } - /** - * Pluralization helper. - */ +/***/ }), - function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); - } +/***/ 1621: +/***/ ((module) => { - /***/ - }, +"use strict"; - /***/ 8222: /***/ (module, exports, __nccwpck_require__) => { - /* eslint-env browser */ - - /** - * This is the web browser implementation of `debug()`. - */ - - exports.log = log; - exports.formatArgs = formatArgs; - exports.save = save; - exports.load = load; - exports.useColors = useColors; - exports.storage = localstorage(); - - /** - * Colors. - */ - - exports.colors = [ - "#0000CC", - "#0000FF", - "#0033CC", - "#0033FF", - "#0066CC", - "#0066FF", - "#0099CC", - "#0099FF", - "#00CC00", - "#00CC33", - "#00CC66", - "#00CC99", - "#00CCCC", - "#00CCFF", - "#3300CC", - "#3300FF", - "#3333CC", - "#3333FF", - "#3366CC", - "#3366FF", - "#3399CC", - "#3399FF", - "#33CC00", - "#33CC33", - "#33CC66", - "#33CC99", - "#33CCCC", - "#33CCFF", - "#6600CC", - "#6600FF", - "#6633CC", - "#6633FF", - "#66CC00", - "#66CC33", - "#9900CC", - "#9900FF", - "#9933CC", - "#9933FF", - "#99CC00", - "#99CC33", - "#CC0000", - "#CC0033", - "#CC0066", - "#CC0099", - "#CC00CC", - "#CC00FF", - "#CC3300", - "#CC3333", - "#CC3366", - "#CC3399", - "#CC33CC", - "#CC33FF", - "#CC6600", - "#CC6633", - "#CC9900", - "#CC9933", - "#CCCC00", - "#CCCC33", - "#FF0000", - "#FF0033", - "#FF0066", - "#FF0099", - "#FF00CC", - "#FF00FF", - "#FF3300", - "#FF3333", - "#FF3366", - "#FF3399", - "#FF33CC", - "#FF33FF", - "#FF6600", - "#FF6633", - "#FF9900", - "#FF9933", - "#FFCC00", - "#FFCC33", - ]; - /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - - // eslint-disable-next-line complexity - function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if ( - typeof window !== "undefined" && - window.process && - (window.process.type === "renderer" || window.process.__nwjs) - ) { - return true; - } +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; - // Internet Explorer and Edge do not support colors. - if ( - typeof navigator !== "undefined" && - navigator.userAgent && - navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/) - ) { - return false; - } - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return ( - (typeof document !== "undefined" && - document.documentElement && - document.documentElement.style && - document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== "undefined" && - window.console && - (window.console.firebug || - (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== "undefined" && - navigator.userAgent && - navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && - parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== "undefined" && - navigator.userAgent && - navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)) - ); - } +/***/ }), - /** - * Colorize log arguments if enabled. - * - * @api public - */ +/***/ 716: +/***/ ((module) => { - function formatArgs(args) { - args[0] = - (this.useColors ? "%c" : "") + - this.namespace + - (this.useColors ? " %c" : " ") + - args[0] + - (this.useColors ? "%c " : " ") + - "+" + - module.exports.humanize(this.diff); +"use strict"; - if (!this.useColors) { - return; - } - const c = "color: " + this.color; - args.splice(1, 0, c, "color: inherit"); +function Kareem() { + this._pres = new Map(); + this._posts = new Map(); +} - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, (match) => { - if (match === "%%") { - return; +Kareem.prototype.execPre = function(name, context, args, callback) { + if (arguments.length === 3) { + callback = args; + args = []; + } + var pres = get(this._pres, name, []); + var numPres = pres.length; + var numAsyncPres = pres.numAsync || 0; + var currentPre = 0; + var asyncPresLeft = numAsyncPres; + var done = false; + var $args = args; + + if (!numPres) { + return process.nextTick(function() { + callback(null); + }); + } + + var next = function() { + if (currentPre >= numPres) { + return; + } + var pre = pres[currentPre]; + + if (pre.isAsync) { + var args = [ + decorateNextFn(_next), + decorateNextFn(function(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); } - index++; - if (match === "%c") { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; + if (--asyncPresLeft === 0 && currentPre >= numPres) { + return callback(null); } - }); + }) + ]; - args.splice(lastC, 0, c); + callMiddlewareFunction(pre.fn, context, args, args[0]); + } else if (pre.fn.length > 0) { + var args = [decorateNextFn(_next)]; + var _args = arguments.length >= 2 ? arguments : [null].concat($args); + for (var i = 1; i < _args.length; ++i) { + args.push(_args[i]); } - /** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - function log(...args) { - // This hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return ( - typeof console === "object" && console.log && console.log(...args) - ); + callMiddlewareFunction(pre.fn, context, args, args[0]); + } else { + let maybePromise = null; + try { + maybePromise = pre.fn.call(context); + } catch (err) { + if (err != null) { + return callback(err); + } } - /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem("debug", namespaces); + if (isPromise(maybePromise)) { + maybePromise.then(() => _next(), err => _next(err)); + } else { + if (++currentPre >= numPres) { + if (asyncPresLeft > 0) { + // Leave parallel hooks to run + return; } else { - exports.storage.removeItem("debug"); + return process.nextTick(function() { + callback(null); + }); } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? } + next(); } + } + }; - /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - function load() { - let r; - try { - r = exports.storage.getItem("debug"); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } + next.apply(null, [null].concat(args)); - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== "undefined" && "env" in process) { - r = process.env.DEBUG; - } + function _next(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); + } - return r; + if (++currentPre >= numPres) { + if (asyncPresLeft > 0) { + // Leave parallel hooks to run + return; + } else { + return callback(null); } + } - /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ + next.apply(context, arguments); + } +}; - function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - } +Kareem.prototype.execPreSync = function(name, context, args) { + var pres = get(this._pres, name, []); + var numPres = pres.length; - module.exports = __nccwpck_require__(6243)(exports); + for (var i = 0; i < numPres; ++i) { + pres[i].fn.apply(context, args || []); + } +}; - const { formatters } = module.exports; +Kareem.prototype.execPost = function(name, context, args, options, callback) { + if (arguments.length < 5) { + callback = options; + options = null; + } + var posts = get(this._posts, name, []); + var numPosts = posts.length; + var currentPost = 0; - /** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + var firstError = null; + if (options && options.error) { + firstError = options.error; + } - formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return "[UnexpectedJSONParseError]: " + error.message; - } - }; + if (!numPosts) { + return process.nextTick(function() { + callback.apply(null, [firstError].concat(args)); + }); + } - /***/ - }, + var next = function() { + var post = posts[currentPost].fn; + var numArgs = 0; + var argLength = args.length; + var newArgs = []; + for (var i = 0; i < argLength; ++i) { + numArgs += args[i] && args[i]._kareemIgnore ? 0 : 1; + if (!args[i] || !args[i]._kareemIgnore) { + newArgs.push(args[i]); + } + } - /***/ 6243: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - - function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(4697); - - Object.keys(env).forEach((key) => { - createDebug[key] = env[key]; + if (firstError) { + if (post.length === numArgs + 2) { + var _cb = decorateNextFn(function(error) { + if (error) { + firstError = error; + } + if (++currentPost >= numPosts) { + return callback.call(null, firstError); + } + next(); }); - /** - * Active `debug` instances. - */ - createDebug.instances = []; - - /** - * The currently active debug mode names, and names to skip. - */ + callMiddlewareFunction(post, context, + [firstError].concat(newArgs).concat([_cb]), _cb); + } else { + if (++currentPost >= numPosts) { + return callback.call(null, firstError); + } + next(); + } + } else { + const _cb = decorateNextFn(function(error) { + if (error) { + firstError = error; + return next(); + } - createDebug.names = []; - createDebug.skips = []; + if (++currentPost >= numPosts) { + return callback.apply(null, [null].concat(args)); + } - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; + next(); + }); - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; + if (post.length === numArgs + 2) { + // Skip error handlers if no error + if (++currentPost >= numPosts) { + return callback.apply(null, [null].concat(args)); + } + return next(); + } + if (post.length === numArgs + 1) { + callMiddlewareFunction(post, context, newArgs.concat([_cb]), _cb); + } else { + let error; + let maybePromise; + try { + maybePromise = post.apply(context, newArgs); + } catch (err) { + error = err; + firstError = err; + } - for (let i = 0; i < namespace.length; i++) { - hash = (hash << 5) - hash + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + if (isPromise(maybePromise)) { + return maybePromise.then(() => _cb(), err => _cb(err)); + } - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + if (++currentPost >= numPosts) { + return callback.apply(null, [error].concat(args)); } - createDebug.selectColor = selectColor; - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; + next(error); + } + } + }; - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } + next(); +}; - const self = debug; +Kareem.prototype.execPostSync = function(name, context, args) { + const posts = get(this._posts, name, []); + const numPosts = posts.length; - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + for (let i = 0; i < numPosts; ++i) { + posts[i].fn.apply(context, args || []); + } +}; - args[0] = createDebug.coerce(args[0]); +Kareem.prototype.createWrapperSync = function(name, fn) { + var kareem = this; + return function syncWrapper() { + kareem.execPreSync(name, this, arguments); - if (typeof args[0] !== "string") { - // Anything else let's inspect with %O - args.unshift("%O"); - } + var toReturn = fn.apply(this, arguments); - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === "%%") { - return match; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === "function") { - const val = args[index]; - match = formatter.call(self, val); - - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + kareem.execPostSync(name, this, [toReturn]); - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); + return toReturn; + }; +} - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } +function _handleWrapError(instance, error, name, context, args, options, callback) { + if (options.useErrorHandlers) { + var _options = { error: error }; + return instance.execPost(name, context, args, _options, function(error) { + return typeof callback === 'function' && callback(error); + }); + } else { + return typeof callback === 'function' ? + callback(error) : + undefined; + } +} + +Kareem.prototype.wrap = function(name, fn, context, args, options) { + const lastArg = (args.length > 0 ? args[args.length - 1] : null); + const argsWithoutCb = typeof lastArg === 'function' ? + args.slice(0, args.length - 1) : + args; + const _this = this; + + options = options || {}; + const checkForPromise = options.checkForPromise; + + this.execPre(name, context, args, function(error) { + if (error) { + const numCallbackParams = options.numCallbackParams || 0; + const errorArgs = options.contextParameter ? [context] : []; + for (var i = errorArgs.length; i < numCallbackParams; ++i) { + errorArgs.push(null); + } + return _handleWrapError(_this, error, name, context, errorArgs, + options, lastArg); + } - debug.namespace = namespace; - debug.enabled = createDebug.enabled(namespace); - debug.useColors = createDebug.useColors(); - debug.color = selectColor(namespace); - debug.destroy = destroy; - debug.extend = extend; - // Debug.formatArgs = formatArgs; - // debug.rawLog = rawLog; - - // env-specific initialization logic for debug instances - if (typeof createDebug.init === "function") { - createDebug.init(debug); - } + const end = (typeof lastArg === 'function' ? args.length - 1 : args.length); + const numParameters = fn.length; + let ret; + try { + ret = fn.apply(context, args.slice(0, end).concat(_cb)); + } catch (err) { + return _cb(err); + } - createDebug.instances.push(debug); + if (checkForPromise) { + if (ret != null && typeof ret.then === 'function') { + // Thenable, use it + return ret.then( + res => _cb(null, res), + err => _cb(err) + ); + } - return debug; - } + // If `fn()` doesn't have a callback argument and doesn't return a + // promise, assume it is sync + if (numParameters < end + 1) { + return _cb(null, ret); + } + } - function destroy() { - const index = createDebug.instances.indexOf(this); - if (index !== -1) { - createDebug.instances.splice(index, 1); - return true; + function _cb() { + const args = arguments; + const argsWithoutError = Array.prototype.slice.call(arguments, 1); + if (options.nullResultByDefault && argsWithoutError.length === 0) { + argsWithoutError.push(null); + } + if (arguments[0]) { + // Assume error + return _handleWrapError(_this, arguments[0], name, context, + argsWithoutError, options, lastArg); + } else { + _this.execPost(name, context, argsWithoutError, function() { + if (arguments[0]) { + return typeof lastArg === 'function' ? + lastArg(arguments[0]) : + undefined; } - return false; - } - function extend(namespace, delimiter) { - const newDebug = createDebug( - this.namespace + - (typeof delimiter === "undefined" ? ":" : delimiter) + - namespace - ); - newDebug.log = this.log; - return newDebug; - } + return typeof lastArg === 'function' ? + lastArg.apply(context, arguments) : + undefined; + }); + } + } + }); +}; - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); +Kareem.prototype.filter = function(fn) { + const clone = this.clone(); - createDebug.names = []; - createDebug.skips = []; + const pres = Array.from(clone._pres.keys()); + for (const name of pres) { + const hooks = this._pres.get(name). + map(h => Object.assign({}, h, { name: name })). + filter(fn); - let i; - const split = ( - typeof namespaces === "string" ? namespaces : "" - ).split(/[\s,]+/); - const len = split.length; + if (hooks.length === 0) { + clone._pres.delete(name); + continue; + } - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } + hooks.numAsync = hooks.filter(h => h.isAsync).length; - namespaces = split[i].replace(/\*/g, ".*?"); + clone._pres.set(name, hooks); + } - if (namespaces[0] === "-") { - createDebug.skips.push( - new RegExp("^" + namespaces.substr(1) + "$") - ); - } else { - createDebug.names.push(new RegExp("^" + namespaces + "$")); - } - } + const posts = Array.from(clone._posts.keys()); + for (const name of posts) { + const hooks = this._posts.get(name). + map(h => Object.assign({}, h, { name: name })). + filter(fn); - for (i = 0; i < createDebug.instances.length; i++) { - const instance = createDebug.instances[i]; - instance.enabled = createDebug.enabled(instance.namespace); - } - } + if (hooks.length === 0) { + clone._posts.delete(name); + continue; + } - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips - .map(toNamespace) - .map((namespace) => "-" + namespace), - ].join(","); - createDebug.enable(""); - return namespaces; - } + clone._posts.set(name, hooks); + } - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === "*") { - return true; - } + return clone; +}; - let i; - let len; +Kareem.prototype.hasHooks = function(name) { + return this._pres.has(name) || this._posts.has(name); +}; - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } +Kareem.prototype.createWrapper = function(name, fn, context, options) { + var _this = this; + if (!this.hasHooks(name)) { + // Fast path: if there's no hooks for this function, just return the + // function wrapped in a nextTick() + return function() { + process.nextTick(() => fn.apply(this, arguments)); + }; + } + return function() { + var _context = context || this; + var args = Array.prototype.slice.call(arguments); + _this.wrap(name, fn, _context, args, options); + }; +}; + +Kareem.prototype.pre = function(name, isAsync, fn, error, unshift) { + let options = {}; + if (typeof isAsync === 'object' && isAsync != null) { + options = isAsync; + isAsync = options.isAsync; + } else if (typeof arguments[1] !== 'boolean') { + error = fn; + fn = isAsync; + isAsync = false; + } - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } + const pres = get(this._pres, name, []); + this._pres.set(name, pres); - return false; - } + if (isAsync) { + pres.numAsync = pres.numAsync || 0; + ++pres.numAsync; + } - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp - .toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, "*"); - } + if (typeof fn !== 'function') { + throw new Error('pre() requires a function, got "' + typeof fn + '"'); + } - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } + if (unshift) { + pres.unshift(Object.assign({}, options, { fn: fn, isAsync: isAsync })); + } else { + pres.push(Object.assign({}, options, { fn: fn, isAsync: isAsync })); + } - createDebug.enable(createDebug.load()); + return this; +}; - return createDebug; - } +Kareem.prototype.post = function(name, options, fn, unshift) { + const hooks = get(this._posts, name, []); - module.exports = setup; + if (typeof options === 'function') { + unshift = !!fn; + fn = options; + options = {}; + } - /***/ - }, + if (typeof fn !== 'function') { + throw new Error('post() requires a function, got "' + typeof fn + '"'); + } - /***/ 8237: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - /** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ - - if ( - typeof process === "undefined" || - process.type === "renderer" || - process.browser === true || - process.__nwjs - ) { - module.exports = __nccwpck_require__(8222); - } else { - module.exports = __nccwpck_require__(5332); - } + if (unshift) { + hooks.unshift(Object.assign({}, options, { fn: fn })); + } else { + hooks.push(Object.assign({}, options, { fn: fn })); + } + this._posts.set(name, hooks); + return this; +}; - /***/ - }, +Kareem.prototype.clone = function() { + const n = new Kareem(); - /***/ 5332: /***/ (module, exports, __nccwpck_require__) => { - /** - * Module dependencies. - */ + for (let key of this._pres.keys()) { + const clone = this._pres.get(key).slice(); + clone.numAsync = this._pres.get(key).numAsync; + n._pres.set(key, clone); + } + for (let key of this._posts.keys()) { + n._posts.set(key, this._posts.get(key).slice()); + } - const tty = __nccwpck_require__(3867); - const util = __nccwpck_require__(1669); + return n; +}; + +Kareem.prototype.merge = function(other, clone) { + clone = arguments.length === 1 ? true : clone; + var ret = clone ? this.clone() : this; + + for (let key of other._pres.keys()) { + const sourcePres = get(ret._pres, key, []); + const deduplicated = other._pres.get(key). + // Deduplicate based on `fn` + filter(p => sourcePres.map(_p => _p.fn).indexOf(p.fn) === -1); + const combined = sourcePres.concat(deduplicated); + combined.numAsync = sourcePres.numAsync || 0; + combined.numAsync += deduplicated.filter(p => p.isAsync).length; + ret._pres.set(key, combined); + } + for (let key of other._posts.keys()) { + const sourcePosts = get(ret._posts, key, []); + const deduplicated = other._posts.get(key). + filter(p => sourcePosts.indexOf(p) === -1); + ret._posts.set(key, sourcePosts.concat(deduplicated)); + } - /** - * This is the Node.js implementation of `debug()`. - */ + return ret; +}; - exports.init = init; - exports.log = log; - exports.formatArgs = formatArgs; - exports.save = save; - exports.load = load; - exports.useColors = useColors; +function get(map, key, def) { + if (map.has(key)) { + return map.get(key); + } + return def; +} + +function callMiddlewareFunction(fn, context, args, next) { + let maybePromise; + try { + maybePromise = fn.apply(context, args); + } catch (error) { + return next(error); + } - /** - * Colors. - */ + if (isPromise(maybePromise)) { + maybePromise.then(() => next(), err => next(err)); + } +} + +function isPromise(v) { + return v != null && typeof v.then === 'function'; +} + +function decorateNextFn(fn) { + var called = false; + var _this = this; + return function() { + // Ensure this function can only be called once + if (called) { + return; + } + called = true; + // Make sure to clear the stack so try/catch doesn't catch errors + // in subsequent middleware + return process.nextTick(() => fn.apply(_this, arguments)); + }; +} - exports.colors = [6, 2, 3, 4, 5, 1]; +module.exports = Kareem; - try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(9318); - if ( - supportsColor && - (supportsColor.stderr || supportsColor).level >= 2 - ) { - exports.colors = [ - 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, - 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, - 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, - 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, - 214, 215, 220, 221, - ]; - } - } catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. - } +/***/ }), - /** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ +/***/ 7147: +/***/ ((module) => { - exports.inspectOpts = Object.keys(process.env) - .filter((key) => { - return /^debug_/i.test(key); - }) - .reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); +module.exports = Pager - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === "null") { - val = null; - } else { - val = Number(val); - } +function Pager (pageSize, opts) { + if (!(this instanceof Pager)) return new Pager(pageSize, opts) - obj[prop] = val; - return obj; - }, {}); + 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 +} - /** - * Is stdout a TTY? Colored output is enabled when `true`. - */ +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) + } - function useColors() { - return "colors" in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(process.stderr.fd); - } + factor(i, this.path) - /** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ + var arr = this.pages - function formatArgs(args) { - const { namespace: name, useColors } = this; + for (var j = this.level; j > 0; j--) { + var p = this.path[j] + var next = arr[p] - if (useColors) { - const c = this.color; - const colorCode = "\u001B[3" + (c < 8 ? c : "8;5;" + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; + if (!next) { + if (noAllocate) return + next = arr[p] = new Array(32768) + } - args[0] = prefix + args[0].split("\n").join("\n" + prefix); - args.push( - colorCode + "m+" + module.exports.humanize(this.diff) + "\u001B[0m" - ); - } else { - args[0] = getDate() + name + " " + args[0]; - } - } + arr = next + } - function getDate() { - if (exports.inspectOpts.hideDate) { - return ""; - } - return new Date().toISOString() + " "; - } + return arr +} - /** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ +Pager.prototype.get = function (i, noAllocate) { + var arr = this._array(i, noAllocate) + var first = this.path[0] + var page = arr && arr[first] - function log(...args) { - return process.stderr.write(util.format(...args) + "\n"); - } + if (!page && !noAllocate) { + page = arr[first] = new Page(i, alloc(this.pageSize)) + if (i >= this.length) this.length = i + 1 + } - /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } - } + if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) { + page.buffer = copy(page.buffer) + page.deduplicate = 0 + } - /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + return page +} - function load() { - return process.env.DEBUG; - } +Pager.prototype.set = function (i, buf) { + var arr = this._array(i, false) + var first = this.path[0] - /** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ + if (i >= this.length) this.length = i + 1 - function init(debug) { - debug.inspectOpts = {}; + if (!buf || (this.zeros && buf.equals && buf.equals(this.zeros))) { + arr[first] = undefined + return + } - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } - } + if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) { + buf = this.deduplicate + } - module.exports = __nccwpck_require__(6243)(exports); + var page = arr[first] + var b = truncate(buf, this.pageSize) - const { formatters } = module.exports; + if (page) page.buffer = b + else arr[first] = new Page(i, b) +} - /** - * Map %o to `util.inspect()`, all on a single line. - */ +Pager.prototype.toBuffer = function () { + var list = new Array(this.length) + var empty = alloc(this.pageSize) + var ptr = 0 - formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts).replace(/\s*\n\s*/g, " "); - }; - - /** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ + 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 + } + } - formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); - }; + 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 +} + + +/***/ }), + +/***/ 4927: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CommaAndColonSeparatedRecord = exports.redactConnectionString = void 0; +const whatwg_url_1 = __nccwpck_require__(9197); +const redact_1 = __nccwpck_require__(8678); +Object.defineProperty(exports, "redactConnectionString", ({ enumerable: true, get: function () { return redact_1.redactConnectionString; } })); +const DUMMY_HOSTNAME = '__this_is_a_placeholder__'; +const HOSTS_REGEX = new RegExp(String.raw `^(?mongodb(?:\+srv|)):\/\/(?:(?[^:]*)(?::(?[^@]*))?@)?(?(?!:)[^\/?@]+)(?.*)`); +class CaseInsensitiveMap extends Map { + delete(name) { + return super.delete(this._normalizeKey(name)); + } + get(name) { + return super.get(this._normalizeKey(name)); + } + has(name) { + return super.has(this._normalizeKey(name)); + } + set(name, value) { + return super.set(this._normalizeKey(name), value); + } + _normalizeKey(name) { + name = `${name}`; + for (const key of this.keys()) { + if (key.toLowerCase() === name.toLowerCase()) { + name = key; + break; + } + } + return name; + } +} +function caseInsenstiveURLSearchParams(Ctor) { + return class CaseInsenstiveURLSearchParams extends Ctor { + append(name, value) { + return super.append(this._normalizeKey(name), value); + } + delete(name) { + return super.delete(this._normalizeKey(name)); + } + get(name) { + return super.get(this._normalizeKey(name)); + } + getAll(name) { + return super.getAll(this._normalizeKey(name)); + } + has(name) { + return super.has(this._normalizeKey(name)); + } + set(name, value) { + return super.set(this._normalizeKey(name), value); + } + keys() { + return super.keys(); + } + values() { + return super.values(); + } + entries() { + return super.entries(); + } + [Symbol.iterator]() { + return super[Symbol.iterator](); + } + _normalizeKey(name) { + return CaseInsensitiveMap.prototype._normalizeKey.call(this, name); + } + }; +} +class URLWithoutHost extends whatwg_url_1.URL { +} +class MongoParseError extends Error { + get name() { + return 'MongoParseError'; + } +} +class ConnectionString extends URLWithoutHost { + constructor(uri) { + var _a; + const match = uri.match(HOSTS_REGEX); + if (!match) { + throw new MongoParseError(`Invalid connection string "${uri}"`); + } + const { protocol, username, password, hosts, rest } = (_a = match.groups) !== null && _a !== void 0 ? _a : {}; + if (!protocol || !hosts) { + throw new MongoParseError(`Protocol and host list are required in "${uri}"`); + } + try { + decodeURIComponent(username !== null && username !== void 0 ? username : ''); + decodeURIComponent(password !== null && password !== void 0 ? password : ''); + } + catch (err) { + throw new MongoParseError(err.message); + } + const illegalCharacters = new RegExp(String.raw `[:/?#\[\]@]`, 'gi'); + if (username === null || username === void 0 ? void 0 : username.match(illegalCharacters)) { + throw new MongoParseError(`Username contains unescaped characters ${username}`); + } + if (!username || !password) { + const uriWithoutProtocol = uri.replace(`${protocol}://`, ''); + if (uriWithoutProtocol.startsWith('@') || uriWithoutProtocol.startsWith(':')) { + throw new MongoParseError('URI contained empty userinfo section'); + } + } + if (password === null || password === void 0 ? void 0 : password.match(illegalCharacters)) { + throw new MongoParseError('Password contains unescaped characters'); + } + let authString = ''; + if (typeof username === 'string') + authString += username; + if (typeof password === 'string') + authString += `:${password}`; + if (authString) + authString += '@'; + super(`${protocol.toLowerCase()}://${authString}${DUMMY_HOSTNAME}${rest}`); + this._hosts = hosts.split(','); + if (this.isSRV && this.hosts.length !== 1) { + throw new MongoParseError('mongodb+srv URI cannot have multiple service names'); + } + if (this.isSRV && this.hosts.some(host => host.includes(':'))) { + throw new MongoParseError('mongodb+srv URI cannot have port number'); + } + if (!this.pathname) { + this.pathname = '/'; + } + Object.setPrototypeOf(this.searchParams, caseInsenstiveURLSearchParams(this.searchParams.constructor).prototype); + } + get host() { return DUMMY_HOSTNAME; } + set host(_ignored) { throw new Error('No single host for connection string'); } + get hostname() { return DUMMY_HOSTNAME; } + set hostname(_ignored) { throw new Error('No single host for connection string'); } + get port() { return ''; } + set port(_ignored) { throw new Error('No single host for connection string'); } + get href() { return this.toString(); } + set href(_ignored) { throw new Error('Cannot set href for connection strings'); } + get isSRV() { + return this.protocol.includes('srv'); + } + get hosts() { + return this._hosts; + } + set hosts(list) { + this._hosts = list; + } + toString() { + return super.toString().replace(DUMMY_HOSTNAME, this.hosts.join(',')); + } + clone() { + return new ConnectionString(this.toString()); + } + redact(options) { + return (0, redact_1.redactValidConnectionString)(this, options); + } + typedSearchParams() { + const sametype = false && 0; + return this.searchParams; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + const { href, origin, protocol, username, password, hosts, pathname, search, searchParams, hash } = this; + return { href, origin, protocol, username, password, hosts, pathname, search, searchParams, hash }; + } +} +exports.default = ConnectionString; +class CommaAndColonSeparatedRecord extends CaseInsensitiveMap { + constructor(from) { + super(); + for (const entry of (from !== null && from !== void 0 ? from : '').split(',')) { + if (!entry) + continue; + const colonIndex = entry.indexOf(':'); + if (colonIndex === -1) { + this.set(entry, ''); + } + else { + this.set(entry.slice(0, colonIndex), entry.slice(colonIndex + 1)); + } + } + } + toString() { + return [...this].map(entry => entry.join(':')).join(','); + } +} +exports.CommaAndColonSeparatedRecord = CommaAndColonSeparatedRecord; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 8678: +/***/ (function(__unused_webpack_module, exports, __nccwpck_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; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.redactConnectionString = exports.redactValidConnectionString = void 0; +const index_1 = __importStar(__nccwpck_require__(4927)); +function redactValidConnectionString(inputUrl, options) { + var _a, _b; + const url = inputUrl.clone(); + const replacementString = (_a = options === null || options === void 0 ? void 0 : options.replacementString) !== null && _a !== void 0 ? _a : '_credentials_'; + const redactUsernames = (_b = options === null || options === void 0 ? void 0 : options.redactUsernames) !== null && _b !== void 0 ? _b : true; + if ((url.username || url.password) && redactUsernames) { + url.username = replacementString; + url.password = ''; + } + else if (url.password) { + url.password = replacementString; + } + if (url.searchParams.has('authMechanismProperties')) { + const props = new index_1.CommaAndColonSeparatedRecord(url.searchParams.get('authMechanismProperties')); + if (props.get('AWS_SESSION_TOKEN')) { + props.set('AWS_SESSION_TOKEN', replacementString); + url.searchParams.set('authMechanismProperties', props.toString()); + } + } + if (url.searchParams.has('tlsCertificateKeyFilePassword')) { + url.searchParams.set('tlsCertificateKeyFilePassword', replacementString); + } + if (url.searchParams.has('proxyUsername') && redactUsernames) { + url.searchParams.set('proxyUsername', replacementString); + } + if (url.searchParams.has('proxyPassword')) { + url.searchParams.set('proxyPassword', replacementString); + } + return url; +} +exports.redactValidConnectionString = redactValidConnectionString; +function redactConnectionString(uri, options) { + var _a, _b; + const replacementString = (_a = options === null || options === void 0 ? void 0 : options.replacementString) !== null && _a !== void 0 ? _a : ''; + const redactUsernames = (_b = options === null || options === void 0 ? void 0 : options.redactUsernames) !== null && _b !== void 0 ? _b : true; + let parsed; + try { + parsed = new index_1.default(uri); + } + catch (_c) { } + if (parsed) { + options = { ...options, replacementString: '___credentials___' }; + return parsed.redact(options).toString().replace(/___credentials___/g, replacementString); + } + const regexes = [ + redactUsernames ? /(?<=\/\/)(.*)(?=@)/g : /(?<=\/\/[^@]+:)(.*)(?=@)/g, + /(?<=AWS_SESSION_TOKEN(:|%3A))([^,&]+)/gi, + /(?<=tlsCertificateKeyFilePassword=)([^&]+)/gi, + redactUsernames ? /(?<=proxyUsername=)([^&]+)/gi : null, + /(?<=proxyPassword=)([^&]+)/gi + ]; + for (const r of regexes) { + if (r !== null) { + uri = uri.replace(r, replacementString); + } + } + return uri; +} +exports.redactConnectionString = redactConnectionString; +//# sourceMappingURL=redact.js.map - /***/ 2342: /***/ (module) => { - "use strict"; - - /** - * Custom implementation of a double ended queue. - */ - function Denque(array, options) { - var options = options || {}; - - this._head = 0; - this._tail = 0; - this._capacity = options.capacity; - 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 peekAt() - * @param i - * @returns {*} - */ - Denque.prototype.get = function get(i) { - return this.peekAt(i); - }; +/***/ 1504: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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]; - }; +"use strict"; - /** - * 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); - }; +const punycode = __nccwpck_require__(4213); +const regexes = __nccwpck_require__(7734); +const mappingTable = __nccwpck_require__(4650); +const { STATUS_MAPPING } = __nccwpck_require__(9416); - /** - * Returns the current length of the queue - * @return {Number} - */ - Object.defineProperty(Denque.prototype, "length", { - get: function length() { - return this.size(); - }, - }); +function containsNonASCII(str) { + return /[^\x00-\x7F]/u.test(str); +} - /** - * 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); - }; +function findStatus(val, { useSTD3ASCIIRules }) { + let start = 0; + let end = mappingTable.length - 1; - /** - * 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._capacity && this.size() > this._capacity) this.pop(); - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); - }; + while (start <= end) { + const mid = Math.floor((start + end) / 2); - /** - * 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; - }; + const target = mappingTable[mid]; + const min = Array.isArray(target[0]) ? target[0][0] : target[0]; + const max = Array.isArray(target[0]) ? target[0][1] : target[0]; - /** - * 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._capacity && this.size() > this._capacity) { - this.shift(); - } - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); - }; + if (min <= val && max >= val) { + if (useSTD3ASCIIRules && + (target[1] === STATUS_MAPPING.disallowed_STD3_valid || target[1] === STATUS_MAPPING.disallowed_STD3_mapped)) { + return [STATUS_MAPPING.disallowed, ...target.slice(2)]; + } else if (target[1] === STATUS_MAPPING.disallowed_STD3_valid) { + return [STATUS_MAPPING.valid, ...target.slice(2)]; + } else if (target[1] === STATUS_MAPPING.disallowed_STD3_mapped) { + return [STATUS_MAPPING.mapped, ...target.slice(2)]; + } - /** - * 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; - }; + return target.slice(1); + } else if (min > val) { + end = mid - 1; + } else { + start = mid + 1; + } + } - /** - * 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; + return null; +} + +function mapChars(domainName, { useSTD3ASCIIRules, processingOption }) { + let hasError = false; + let processed = ""; + + for (const ch of domainName) { + const [status, mapping] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules }); + + switch (status) { + case STATUS_MAPPING.disallowed: + hasError = true; + processed += ch; + break; + case STATUS_MAPPING.ignored: + break; + case STATUS_MAPPING.mapped: + processed += mapping; + break; + case STATUS_MAPPING.deviation: + if (processingOption === "transitional") { + processed += mapping; } 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; + processed += ch; } - return item; - }; + break; + case STATUS_MAPPING.valid: + processed += ch; + break; + } + } - /** - * 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; - }; + return { + string: processed, + error: hasError + }; +} - /** - * 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); - } - }; +function validateLabel(label, { checkHyphens, checkBidi, checkJoiners, processingOption, useSTD3ASCIIRules }) { + if (label.normalize("NFC") !== label) { + return false; + } - /** - * Soft clear - does not reset capacity. - */ - Denque.prototype.clear = function clear() { - this._head = 0; - this._tail = 0; - }; + const codePoints = Array.from(label); - /** - * Returns true or false whether the list is empty. - * @returns {boolean} - */ - Denque.prototype.isEmpty = function isEmpty() { - return this._head === this._tail; - }; + if (checkHyphens) { + if ((codePoints[2] === "-" && codePoints[3] === "-") || + (label.startsWith("-") || label.endsWith("-"))) { + return false; + } + } - /** - * Returns an array of all queue items. - * @returns {Array} - */ - Denque.prototype.toArray = function toArray() { - return this._copyArray(false); - }; + if (label.includes(".") || + (codePoints.length > 0 && regexes.combiningMarks.test(codePoints[0]))) { + return 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]); - }; + for (const ch of codePoints) { + const [status] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules }); + if ((processingOption === "transitional" && status !== STATUS_MAPPING.valid) || + (processingOption === "nontransitional" && + status !== STATUS_MAPPING.valid && status !== STATUS_MAPPING.deviation)) { + return false; + } + } - /** - * - * @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]); + // https://tools.ietf.org/html/rfc5892#appendix-A + if (checkJoiners) { + let last = 0; + for (const [i, ch] of codePoints.entries()) { + if (ch === "\u200C" || ch === "\u200D") { + if (i > 0) { + if (regexes.combiningClassVirama.test(codePoints[i - 1])) { + continue; + } + if (ch === "\u200C") { + // TODO: make this more efficient + const next = codePoints.indexOf("\u200C", i + 1); + const test = next < 0 ? codePoints.slice(last) : codePoints.slice(last, next); + if (regexes.validZWNJ.test(test.join(""))) { + last = i + 1; + continue; + } + } } - return newArray; - }; + return false; + } + } + } - /** - * 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; - } + // https://tools.ietf.org/html/rfc5893#section-2 + if (checkBidi) { + let rtl; + + // 1 + if (regexes.bidiS1LTR.test(codePoints[0])) { + rtl = false; + } else if (regexes.bidiS1RTL.test(codePoints[0])) { + rtl = true; + } else { + return false; + } - // head is at 0 and array is now full, safe to extend - this._tail = this._list.length; + if (rtl) { + // 2-4 + if (!regexes.bidiS2.test(label) || + !regexes.bidiS3.test(label) || + (regexes.bidiS4EN.test(label) && regexes.bidiS4AN.test(label))) { + return false; + } + } else if (!regexes.bidiS5.test(label) || + !regexes.bidiS6.test(label)) { // 5-6 + return false; + } + } - this._list.length <<= 1; - this._capacityMask = (this._capacityMask << 1) | 1; - }; + return true; +} - /** - * Shrinks the internal list array. - * @private - */ - Denque.prototype._shrinkArray = function _shrinkArray() { - this._list.length >>>= 1; - this._capacityMask >>>= 1; - }; +function isBidiDomain(labels) { + const domain = labels.map(label => { + if (label.startsWith("xn--")) { + try { + return punycode.decode(label.substring(4)); + } catch (err) { + return ""; + } + } + return label; + }).join("."); + return regexes.bidiDomain.test(domain); +} - module.exports = Denque; +function processing(domainName, options) { + const { processingOption } = options; - /***/ - }, + // 1. Map. + let { string, error } = mapChars(domainName, options); - /***/ 1621: /***/ (module) => { - "use strict"; - - module.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith("-") - ? "" - : flag.length === 1 - ? "-" - : "--"; - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf("--"); - return ( - position !== -1 && - (terminatorPosition === -1 || position < terminatorPosition) - ); - }; + // 2. Normalize. + string = string.normalize("NFC"); - /***/ - }, + // 3. Break. + const labels = string.split("."); + const isBidi = isBidiDomain(labels); + + // 4. Convert/Validate. + for (const [i, origLabel] of labels.entries()) { + let label = origLabel; + let curProcessing = processingOption; + if (label.startsWith("xn--")) { + try { + label = punycode.decode(label.substring(4)); + labels[i] = label; + } catch (err) { + error = true; + continue; + } + curProcessing = "nontransitional"; + } + + // No need to validate if we already know there is an error. + if (error) { + continue; + } + const validation = validateLabel(label, { + ...options, + processingOption: curProcessing, + checkBidi: options.checkBidi && isBidi + }); + if (!validation) { + error = true; + } + } + + return { + string: labels.join("."), + error + }; +} + +function toASCII(domainName, { + checkHyphens = false, + checkBidi = false, + checkJoiners = false, + useSTD3ASCIIRules = false, + processingOption = "nontransitional", + verifyDNSLength = false +} = {}) { + if (processingOption !== "transitional" && processingOption !== "nontransitional") { + throw new RangeError("processingOption must be either transitional or nontransitional"); + } - /***/ 4124: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { + const result = processing(domainName, { + processingOption, + checkHyphens, + checkBidi, + checkJoiners, + useSTD3ASCIIRules + }); + let labels = result.string.split("."); + labels = labels.map(l => { + if (containsNonASCII(l)) { try { - var util = __nccwpck_require__(1669); - /* istanbul ignore next */ - if (typeof util.inherits !== "function") throw ""; - module.exports = util.inherits; + return `xn--${punycode.encode(l)}`; } catch (e) { - /* istanbul ignore next */ - module.exports = __nccwpck_require__(8544); + result.error = true; } + } + return l; + }); - /***/ - }, + if (verifyDNSLength) { + const total = labels.join(".").length; + if (total > 253 || total === 0) { + result.error = true; + } - /***/ 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; - } - }; + for (let i = 0; i < labels.length; ++i) { + if (labels[i].length > 63 || labels[i].length === 0) { + result.error = true; + break; } + } + } - /***/ - }, + if (result.error) { + return null; + } + return labels.join("."); +} + +function toUnicode(domainName, { + checkHyphens = false, + checkBidi = false, + checkJoiners = false, + useSTD3ASCIIRules = false, + processingOption = "nontransitional" +} = {}) { + const result = processing(domainName, { + processingOption, + checkHyphens, + checkBidi, + checkJoiners, + useSTD3ASCIIRules + }); + + return { + domain: result.string, + error: result.error + }; +} - /***/ 893: /***/ (module) => { - var toString = {}.toString; +module.exports = { + toASCII, + toUnicode +}; - module.exports = - Array.isArray || - function (arr) { - return toString.call(arr) == "[object Array]"; - }; - /***/ - }, +/***/ }), - /***/ 716: /***/ (module) => { - "use strict"; +/***/ 7734: +/***/ ((module) => { - function Kareem() { - this._pres = new Map(); - this._posts = new Map(); - } +"use strict"; - Kareem.prototype.execPre = function (name, context, args, callback) { - if (arguments.length === 3) { - callback = args; - args = []; - } - var pres = get(this._pres, name, []); - var numPres = pres.length; - var numAsyncPres = pres.numAsync || 0; - var currentPre = 0; - var asyncPresLeft = numAsyncPres; - var done = false; - var $args = args; - if (!numPres) { - return process.nextTick(function () { - callback(null); - }); - } +const combiningMarks = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11000}-\u{11002}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11082}\u{110B0}-\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{11134}\u{11145}\u{11146}\u{11173}\u{11180}-\u{11182}\u{111B3}-\u{111C0}\u{111C9}-\u{111CC}\u{111CE}\u{111CF}\u{1122C}-\u{11237}\u{1123E}\u{112DF}-\u{112EA}\u{11300}-\u{11303}\u{1133B}\u{1133C}\u{1133E}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11357}\u{11362}\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11435}-\u{11446}\u{1145E}\u{114B0}-\u{114C3}\u{115AF}-\u{115B5}\u{115B8}-\u{115C0}\u{115DC}\u{115DD}\u{11630}-\u{11640}\u{116AB}-\u{116B7}\u{1171D}-\u{1172B}\u{1182C}-\u{1183A}\u{11930}-\u{11935}\u{11937}\u{11938}\u{1193B}-\u{1193E}\u{11940}\u{11942}\u{11943}\u{119D1}-\u{119D7}\u{119DA}-\u{119E0}\u{119E4}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A39}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A5B}\u{11A8A}-\u{11A99}\u{11C2F}-\u{11C36}\u{11C38}-\u{11C3F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D8A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D97}\u{11EF3}-\u{11EF6}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F51}-\u{16F87}\u{16F8F}-\u{16F92}\u{16FE4}\u{16FF0}\u{16FF1}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D165}-\u{1D169}\u{1D16D}-\u{1D172}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]/u; +const combiningClassVirama = /[\u094D\u09CD\u0A4D\u0ACD\u0B4D\u0BCD\u0C4D\u0CCD\u0D3B\u0D3C\u0D4D\u0DCA\u0E3A\u0EBA\u0F84\u1039\u103A\u1714\u1734\u17D2\u1A60\u1B44\u1BAA\u1BAB\u1BF2\u1BF3\u2D7F\uA806\uA8C4\uA953\uA9C0\uAAF6\uABED\u{10A3F}\u{11046}\u{1107F}\u{110B9}\u{11133}\u{11134}\u{111C0}\u{11235}\u{112EA}\u{1134D}\u{11442}\u{114C2}\u{115BF}\u{1163F}\u{116B6}\u{1172B}\u{11839}\u{119E0}\u{11A34}\u{11A47}\u{11A99}\u{11C3F}\u{11D44}\u{11D45}\u{11D97}]/u; +const validZWNJ = /[\u0620\u0626\u0628\u062A-\u062E\u0633-\u063F\u0641-\u0647\u0649\u064A\u066E\u066F\u0678-\u0687\u069A-\u06BF\u06C1\u06C2\u06CC\u06CE\u06D0\u06D1\u06FA-\u06FC\u06FF\u0712-\u0714\u071A-\u071D\u071F-\u0727\u0729\u072B\u072D\u072E\u074E-\u0758\u075C-\u076A\u076D-\u0770\u0772\u0775-\u0777\u077A-\u077F\u07CA-\u07EA\u0841-\u0845\u0848\u084A-\u0853\u0855\u0860\u0862-\u0865\u0868\u08A0-\u08A9\u08AF\u08B0\u08B3\u08B4\u08B6-\u08B8\u08BA-\u08BD\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA872\u{10AC0}-\u{10AC4}\u{10ACD}\u{10AD3}-\u{10ADC}\u{10ADE}-\u{10AE0}\u{10AEB}-\u{10AEE}\u{10B80}\u{10B82}\u{10B86}-\u{10B88}\u{10B8A}\u{10B8B}\u{10B8D}\u{10B90}\u{10BAD}\u{10BAE}\u{10D00}-\u{10D21}\u{10D23}\u{10F30}-\u{10F32}\u{10F34}-\u{10F44}\u{10F51}-\u{10F53}\u{1E900}-\u{1E943}][\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{13430}-\u{13438}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*\u200C[\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{13430}-\u{13438}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*[\u0620\u0622-\u063F\u0641-\u064A\u066E\u066F\u0671-\u0673\u0675-\u06D3\u06D5\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u077F\u07CA-\u07EA\u0840-\u0855\u0860\u0862-\u0865\u0867-\u086A\u08A0-\u08AC\u08AE-\u08B4\u08B6-\u08BD\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA871\u{10AC0}-\u{10AC5}\u{10AC7}\u{10AC9}\u{10ACA}\u{10ACE}-\u{10AD6}\u{10AD8}-\u{10AE1}\u{10AE4}\u{10AEB}-\u{10AEF}\u{10B80}-\u{10B91}\u{10BA9}-\u{10BAE}\u{10D01}-\u{10D23}\u{10F30}-\u{10F44}\u{10F51}-\u{10F54}\u{1E900}-\u{1E943}]/u; +const bidiDomain = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u08A0-\u08C9\u08E2\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u; +const bidiS1LTR = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C66-\u0C6F\u0C77\u0C7F\u0C80\u0C82-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u1711\u1715\u171F-\u1731\u1734-\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4C\u1B50-\u1B6A\u1B74-\u1B7E\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u249C-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BF\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB69\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11071}\u{11072}\u{11075}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11147}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111CE}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{1145B}\u{1145D}\u{1145F}-\u{11461}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116B9}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{11720}\u{11721}\u{11726}\u{11730}-\u{11746}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193D}\u{1193F}-\u{11942}\u{11944}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11FB0}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{1342E}\u{13430}-\u{13438}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18D00}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B150}-\u{1B152}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D800}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1DF00}-\u{1DF1E}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AD}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B738}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u; +const bidiS1RTL = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u08A0-\u08C9\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u; +const bidiS2 = /^[\0-\x08\x0E-\x1B!-@\[-`\{-\x84\x86-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02B9\u02BA\u02C2-\u02CF\u02D2-\u02DF\u02E5-\u02ED\u02EF-\u036F\u0374\u0375\u037E\u0384\u0385\u0387\u03F6\u0483-\u0489\u058A\u058D-\u058F\u0591-\u05C7\u05D0-\u05EA\u05EF-\u05F4\u0600-\u070D\u070F-\u074A\u074D-\u07B1\u07C0-\u07FA\u07FD-\u082D\u0830-\u083E\u0840-\u085B\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u0898-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09F2\u09F3\u09FB\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AF1\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0BF3-\u0BFA\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C78-\u0C7E\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E3F\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39-\u0F3D\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1390-\u1399\u1400\u169B\u169C\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DB\u17DD\u17F0-\u17F9\u1800-\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1940\u1944\u1945\u19DE-\u19FF\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u200B-\u200D\u200F-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2070\u2074-\u207E\u2080-\u208E\u20A0-\u20C0\u20D0-\u20F0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u2150-\u215F\u2189-\u218B\u2190-\u2335\u237B-\u2394\u2396-\u2426\u2440-\u244A\u2460-\u249B\u24EA-\u26AB\u26AD-\u27FF\u2900-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2CEF-\u2CF1\u2CF9-\u2CFF\u2D7F\u2DE0-\u2E5D\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u3004\u3008-\u3020\u302A-\u302D\u3030\u3036\u3037\u303D-\u303F\u3099-\u309C\u30A0\u30FB\u31C0-\u31E3\u321D\u321E\u3250-\u325F\u327C-\u327E\u32B1-\u32BF\u32CC-\u32CF\u3377-\u337A\u33DE\u33DF\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA60D-\uA60F\uA66F-\uA67F\uA69E\uA69F\uA6F0\uA6F1\uA700-\uA721\uA788\uA802\uA806\uA80B\uA825\uA826\uA828-\uA82C\uA838\uA839\uA874-\uA877\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uAB6A\uAB6B\uABE5\uABE8\uABED\uFB1D-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD8F\uFD92-\uFDC7\uFDCF\uFDF0-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFE70-\uFE74\uFE76-\uFEFC\uFEFF\uFF01-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10101}\u{10140}-\u{1018C}\u{10190}-\u{1019C}\u{101A0}\u{101FD}\u{102E0}-\u{102FB}\u{10376}-\u{1037A}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{1091F}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A38}-\u{10A3A}\u{10A3F}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE6}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B39}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D27}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAB}-\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F59}\u{10F70}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{11001}\u{11038}-\u{11046}\u{11052}-\u{11065}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{11660}-\u{1166C}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11FD5}-\u{11FF1}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE2}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D1E9}\u{1D1EA}\u{1D200}-\u{1D245}\u{1D300}-\u{1D356}\u{1D6DB}\u{1D715}\u{1D74F}\u{1D789}\u{1D7C3}\u{1D7CE}-\u{1D7FF}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E2FF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8D6}\u{1E900}-\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F10F}\u{1F12F}\u{1F16A}-\u{1F16F}\u{1F1AD}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D7}\u{1F6DD}-\u{1F6EC}\u{1F6F0}-\u{1F6FC}\u{1F700}-\u{1F773}\u{1F780}-\u{1F7D8}\u{1F7E0}-\u{1F7EB}\u{1F7F0}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F8B0}\u{1F8B1}\u{1F900}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7C}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAAC}\u{1FAB0}-\u{1FABA}\u{1FAC0}-\u{1FAC5}\u{1FAD0}-\u{1FAD9}\u{1FAE0}-\u{1FAE7}\u{1FAF0}-\u{1FAF6}\u{1FB00}-\u{1FB92}\u{1FB94}-\u{1FBCA}\u{1FBF0}-\u{1FBF9}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*$/u; +const bidiS3 = /[0-9\xB2\xB3\xB9\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u0870-\u088E\u0890\u0891\u08A0-\u08C9\u08E2\u200F\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC2\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\u{102E1}-\u{102FB}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10E80}-\u{10EA9}\u{10EAD}\u{10EB0}\u{10EB1}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10F70}-\u{10F81}\u{10F86}-\u{10F89}\u{10FB0}-\u{10FCB}\u{10FE0}-\u{10FF6}\u{1D7CE}-\u{1D7FF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1F100}-\u{1F10A}\u{1FBF0}-\u{1FBF9}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u; +const bidiS4EN = /[0-9\xB2\xB3\xB9\u06F0-\u06F9\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFF10-\uFF19\u{102E1}-\u{102FB}\u{1D7CE}-\u{1D7FF}\u{1F100}-\u{1F10A}\u{1FBF0}-\u{1FBF9}]/u; +const bidiS4AN = /[\u0600-\u0605\u0660-\u0669\u066B\u066C\u06DD\u0890\u0891\u08E2\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}]/u; +const bidiS5 = /^[\0-\x08\x0E-\x1B!-\x84\x86-\u0377\u037A-\u037F\u0384-\u038A\u038C\u038E-\u03A1\u03A3-\u052F\u0531-\u0556\u0559-\u058A\u058D-\u058F\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0606\u0607\u0609\u060A\u060C\u060E-\u061A\u064B-\u065F\u066A\u0670\u06D6-\u06DC\u06DE-\u06E4\u06E7-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07F6-\u07F9\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09FE\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A76\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AF1\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B77\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BFA\u0C00-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3C-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C5D\u0C60-\u0C63\u0C66-\u0C6F\u0C77-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDD\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4F\u0D54-\u0D63\u0D66-\u0D7F\u0D81-\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E3A\u0E3F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F47\u0F49-\u0F6C\u0F71-\u0F97\u0F99-\u0FBC\u0FBE-\u0FCC\u0FCE-\u0FDA\u1000-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u137C\u1380-\u1399\u13A0-\u13F5\u13F8-\u13FD\u1400-\u167F\u1681-\u169C\u16A0-\u16F8\u1700-\u1715\u171F-\u1736\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17DD\u17E0-\u17E9\u17F0-\u17F9\u1800-\u1819\u1820-\u1878\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1940\u1944-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u19DE-\u1A1B\u1A1E-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1AB0-\u1ACE\u1B00-\u1B4C\u1B50-\u1B7E\u1B80-\u1BF3\u1BFC-\u1C37\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD0-\u1CFA\u1D00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FC4\u1FC6-\u1FD3\u1FD6-\u1FDB\u1FDD-\u1FEF\u1FF2-\u1FF4\u1FF6-\u1FFE\u200B-\u200E\u2010-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2071\u2074-\u208E\u2090-\u209C\u20A0-\u20C0\u20D0-\u20F0\u2100-\u218B\u2190-\u2426\u2440-\u244A\u2460-\u2B73\u2B76-\u2B95\u2B97-\u2CF3\u2CF9-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2E5D\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u303F\u3041-\u3096\u3099-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31E3\u31F0-\u321E\u3220-\uA48C\uA490-\uA4C6\uA4D0-\uA62B\uA640-\uA6F7\uA700-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA82C\uA830-\uA839\uA840-\uA877\uA880-\uA8C5\uA8CE-\uA8D9\uA8E0-\uA953\uA95F-\uA97C\uA980-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA5C-\uAAC2\uAADB-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB6B\uAB70-\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1E\uFB29\uFD3E-\uFD4F\uFDCF\uFDFD-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFEFF\uFF01-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}-\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1018E}\u{10190}-\u{1019C}\u{101A0}\u{101D0}-\u{101FD}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E0}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{1037A}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{1091F}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10B39}-\u{10B3F}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11000}-\u{1104D}\u{11052}-\u{11075}\u{1107F}-\u{110C2}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11100}-\u{11134}\u{11136}-\u{11147}\u{11150}-\u{11176}\u{11180}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1123E}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112EA}\u{112F0}-\u{112F9}\u{11300}-\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133B}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11400}-\u{1145B}\u{1145D}-\u{11461}\u{11480}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B5}\u{115B8}-\u{115DD}\u{11600}-\u{11644}\u{11650}-\u{11659}\u{11660}-\u{1166C}\u{11680}-\u{116B9}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{1171D}-\u{1172B}\u{11730}-\u{11746}\u{11800}-\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193B}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D7}\u{119DA}-\u{119E4}\u{11A00}-\u{11A47}\u{11A50}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C36}\u{11C38}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D47}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF8}\u{11FB0}\u{11FC0}-\u{11FF1}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{1342E}\u{13430}-\u{13438}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF0}-\u{16AF5}\u{16B00}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F4F}-\u{16F87}\u{16F8F}-\u{16F9F}\u{16FE0}-\u{16FE4}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18D00}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B150}-\u{1B152}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}-\u{1BCA3}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D1EA}\u{1D200}-\u{1D245}\u{1D2E0}-\u{1D2F3}\u{1D300}-\u{1D356}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D7CB}\u{1D7CE}-\u{1DA8B}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1DF00}-\u{1DF1E}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E100}-\u{1E12C}\u{1E130}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AE}\u{1E2C0}-\u{1E2F9}\u{1E2FF}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F1AD}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D7}\u{1F6DD}-\u{1F6EC}\u{1F6F0}-\u{1F6FC}\u{1F700}-\u{1F773}\u{1F780}-\u{1F7D8}\u{1F7E0}-\u{1F7EB}\u{1F7F0}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F8B0}\u{1F8B1}\u{1F900}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7C}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAAC}\u{1FAB0}-\u{1FABA}\u{1FAC0}-\u{1FAC5}\u{1FAD0}-\u{1FAD9}\u{1FAE0}-\u{1FAE7}\u{1FAF0}-\u{1FAF6}\u{1FB00}-\u{1FB92}\u{1FB94}-\u{1FBCA}\u{1FBF0}-\u{1FBF9}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B738}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]*$/u; +const bidiS6 = /[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u06F0-\u06F9\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C66-\u0C6F\u0C77\u0C7F\u0C80\u0C82-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u1711\u1715\u171F-\u1731\u1734-\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4C\u1B50-\u1B6A\u1B74-\u1B7E\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u2488-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BF\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB69\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E1}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}-\u{1057A}\u{1057C}-\u{1058A}\u{1058C}-\u{10592}\u{10594}\u{10595}\u{10597}-\u{105A1}\u{105A3}-\u{105B1}\u{105B3}-\u{105B9}\u{105BB}\u{105BC}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{10780}-\u{10785}\u{10787}-\u{107B0}\u{107B2}-\u{107BA}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11071}\u{11072}\u{11075}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11147}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111CE}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{1145B}\u{1145D}\u{1145F}-\u{11461}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116B9}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{11720}\u{11721}\u{11726}\u{11730}-\u{11746}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}-\u{11906}\u{11909}\u{1190C}-\u{11913}\u{11915}\u{11916}\u{11918}-\u{11935}\u{11937}\u{11938}\u{1193D}\u{1193F}-\u{11942}\u{11944}-\u{11946}\u{11950}-\u{11959}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AB0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11FB0}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{12F90}-\u{12FF2}\u{13000}-\u{1342E}\u{13430}-\u{13438}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}-\u{16ABE}\u{16AC0}-\u{16AC9}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{16FF0}\u{16FF1}\u{17000}-\u{187F7}\u{18800}-\u{18CD5}\u{18D00}-\u{18D08}\u{1AFF0}-\u{1AFF3}\u{1AFF5}-\u{1AFFB}\u{1AFFD}\u{1AFFE}\u{1B000}-\u{1B122}\u{1B150}-\u{1B152}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1CF50}-\u{1CFC3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D7CE}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1DF00}-\u{1DF1E}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E290}-\u{1E2AD}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1E7E0}-\u{1E7E6}\u{1E7E8}-\u{1E7EB}\u{1E7ED}\u{1E7EE}\u{1E7F0}-\u{1E7FE}\u{1F100}-\u{1F10A}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1FBF0}-\u{1FBF9}\u{20000}-\u{2A6DF}\u{2A700}-\u{2B738}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{30000}-\u{3134A}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B55\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3C\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0D81\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732\u1733\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ACE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA82C\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10EAB}\u{10EAC}\u{10F46}-\u{10F50}\u{10F82}-\u{10F85}\u{11001}\u{11038}-\u{11046}\u{11070}\u{11073}\u{11074}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{110C2}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{111CF}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{1193B}\u{1193C}\u{1193E}\u{11943}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE4}\u{1BC9D}\u{1BC9E}\u{1CF00}-\u{1CF2D}\u{1CF30}-\u{1CF46}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2AE}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u; - var next = function () { - if (currentPre >= numPres) { - return; - } - var pre = pres[currentPre]; +module.exports = { + combiningMarks, + combiningClassVirama, + validZWNJ, + bidiDomain, + bidiS1LTR, + bidiS1RTL, + bidiS2, + bidiS3, + bidiS4EN, + bidiS4AN, + bidiS5, + bidiS6 +}; - if (pre.isAsync) { - var args = [ - decorateNextFn(_next), - decorateNextFn(function (error) { - if (error) { - if (done) { - return; - } - done = true; - return callback(error); - } - if (--asyncPresLeft === 0 && currentPre >= numPres) { - return callback(null); - } - }), - ]; - callMiddlewareFunction(pre.fn, context, args, args[0]); - } else if (pre.fn.length > 0) { - var args = [decorateNextFn(_next)]; - var _args = - arguments.length >= 2 ? arguments : [null].concat($args); - for (var i = 1; i < _args.length; ++i) { - args.push(_args[i]); - } +/***/ }), - callMiddlewareFunction(pre.fn, context, args, args[0]); - } else { - let maybePromise = null; - try { - maybePromise = pre.fn.call(context); - } catch (err) { - if (err != null) { - return callback(err); - } - } +/***/ 9416: +/***/ ((module) => { - if (isPromise(maybePromise)) { - maybePromise.then( - () => _next(), - (err) => _next(err) - ); - } else { - if (++currentPre >= numPres) { - if (asyncPresLeft > 0) { - // Leave parallel hooks to run - return; - } else { - return process.nextTick(function () { - callback(null); - }); - } - } - next(); - } - } - }; +"use strict"; - next.apply(null, [null].concat(args)); - function _next(error) { - if (error) { - if (done) { - return; - } - done = true; - return callback(error); - } +module.exports.STATUS_MAPPING = { + mapped: 1, + valid: 2, + disallowed: 3, + disallowed_STD3_valid: 4, + disallowed_STD3_mapped: 5, + deviation: 6, + ignored: 7 +}; - if (++currentPre >= numPres) { - if (asyncPresLeft > 0) { - // Leave parallel hooks to run - return; - } else { - return callback(null); - } - } - next.apply(context, arguments); - } - }; +/***/ }), - Kareem.prototype.execPreSync = function (name, context, args) { - var pres = get(this._pres, name, []); - var numPres = pres.length; +/***/ 6362: +/***/ ((__unused_webpack_module, exports) => { - for (var i = 0; i < numPres; ++i) { - pres[i].fn.apply(context, args || []); - } - }; +"use strict"; - Kareem.prototype.execPost = function ( - name, - context, - args, - options, - callback - ) { - if (arguments.length < 5) { - callback = options; - options = null; - } - var posts = get(this._posts, name, []); - var numPosts = posts.length; - var currentPost = 0; - - var firstError = null; - if (options && options.error) { - firstError = options.error; - } - - if (!numPosts) { - return process.nextTick(function () { - callback.apply(null, [firstError].concat(args)); - }); - } - var next = function () { - var post = posts[currentPost].fn; - var numArgs = 0; - var argLength = args.length; - var newArgs = []; - for (var i = 0; i < argLength; ++i) { - numArgs += args[i] && args[i]._kareemIgnore ? 0 : 1; - if (!args[i] || !args[i]._kareemIgnore) { - newArgs.push(args[i]); - } - } +function makeException(ErrorType, message, options) { + if (options.globals) { + ErrorType = options.globals[ErrorType.name]; + } + return new ErrorType(`${options.context ? options.context : "Value"} ${message}.`); +} - if (firstError) { - if (post.length === numArgs + 2) { - var _cb = decorateNextFn(function (error) { - if (error) { - firstError = error; - } - if (++currentPost >= numPosts) { - return callback.call(null, firstError); - } - next(); - }); +function toNumber(value, options) { + if (typeof value === "bigint") { + throw makeException(TypeError, "is a BigInt which cannot be converted to a number", options); + } + if (!options.globals) { + return Number(value); + } + return options.globals.Number(value); +} + +// Round x to the nearest integer, choosing the even integer if it lies halfway between two. +function evenRound(x) { + // There are four cases for numbers with fractional part being .5: + // + // case | x | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 | example + // 1 | 2n + 0.5 | 2n | 2n + 1 | 2n | > | 0.5 | 0 | 0.5 -> 0 + // 2 | 2n + 1.5 | 2n + 1 | 2n + 2 | 2n + 2 | > | 0.5 | 1 | 1.5 -> 2 + // 3 | -2n - 0.5 | -2n - 1 | -2n | -2n | < | -0.5 | 0 | -0.5 -> 0 + // 4 | -2n - 1.5 | -2n - 2 | -2n - 1 | -2n - 2 | < | -0.5 | 1 | -1.5 -> -2 + // (where n is a non-negative integer) + // + // Branch here for cases 1 and 4 + if ((x > 0 && (x % 1) === +0.5 && (x & 1) === 0) || + (x < 0 && (x % 1) === -0.5 && (x & 1) === 1)) { + return censorNegativeZero(Math.floor(x)); + } - callMiddlewareFunction( - post, - context, - [firstError].concat(newArgs).concat([_cb]), - _cb - ); - } else { - if (++currentPost >= numPosts) { - return callback.call(null, firstError); - } - next(); - } - } else { - const _cb = decorateNextFn(function (error) { - if (error) { - firstError = error; - return next(); - } + return censorNegativeZero(Math.round(x)); +} - if (++currentPost >= numPosts) { - return callback.apply(null, [null].concat(args)); - } +function integerPart(n) { + return censorNegativeZero(Math.trunc(n)); +} - next(); - }); +function sign(x) { + return x < 0 ? -1 : 1; +} - if (post.length === numArgs + 2) { - // Skip error handlers if no error - if (++currentPost >= numPosts) { - return callback.apply(null, [null].concat(args)); - } - return next(); - } - if (post.length === numArgs + 1) { - callMiddlewareFunction(post, context, newArgs.concat([_cb]), _cb); - } else { - let error; - let maybePromise; - try { - maybePromise = post.apply(context, newArgs); - } catch (err) { - error = err; - firstError = err; - } +function modulo(x, y) { + // https://tc39.github.io/ecma262/#eqn-modulo + // Note that http://stackoverflow.com/a/4467559/3191 does NOT work for large modulos + const signMightNotMatch = x % y; + if (sign(y) !== sign(signMightNotMatch)) { + return signMightNotMatch + y; + } + return signMightNotMatch; +} + +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} + +function createIntegerConversion(bitLength, { unsigned }) { + let lowerBound, upperBound; + if (unsigned) { + lowerBound = 0; + upperBound = 2 ** bitLength - 1; + } else { + lowerBound = -(2 ** (bitLength - 1)); + upperBound = 2 ** (bitLength - 1) - 1; + } - if (isPromise(maybePromise)) { - return maybePromise.then( - () => _cb(), - (err) => _cb(err) - ); - } + const twoToTheBitLength = 2 ** bitLength; + const twoToOneLessThanTheBitLength = 2 ** (bitLength - 1); - if (++currentPost >= numPosts) { - return callback.apply(null, [error].concat(args)); - } + return (value, options = {}) => { + let x = toNumber(value, options); + x = censorNegativeZero(x); - next(error); - } - } - }; + if (options.enforceRange) { + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite number", options); + } - next(); - }; + x = integerPart(x); - Kareem.prototype.execPostSync = function (name, context, args) { - const posts = get(this._posts, name, []); - const numPosts = posts.length; + if (x < lowerBound || x > upperBound) { + throw makeException( + TypeError, + `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, + options + ); + } - for (let i = 0; i < numPosts; ++i) { - posts[i].fn.apply(context, args || []); - } - }; + return x; + } - Kareem.prototype.createWrapperSync = function (name, fn) { - var kareem = this; - return function syncWrapper() { - kareem.execPreSync(name, this, arguments); + if (!Number.isNaN(x) && options.clamp) { + x = Math.min(Math.max(x, lowerBound), upperBound); + x = evenRound(x); + return x; + } - var toReturn = fn.apply(this, arguments); + if (!Number.isFinite(x) || x === 0) { + return 0; + } + x = integerPart(x); - kareem.execPostSync(name, this, [toReturn]); + // Math.pow(2, 64) is not accurately representable in JavaScript, so try to avoid these per-spec operations if + // possible. Hopefully it's an optimization for the non-64-bitLength cases too. + if (x >= lowerBound && x <= upperBound) { + return x; + } - return toReturn; - }; - }; + // These will not work great for bitLength of 64, but oh well. See the README for more details. + x = modulo(x, twoToTheBitLength); + if (!unsigned && x >= twoToOneLessThanTheBitLength) { + return x - twoToTheBitLength; + } + return x; + }; +} - function _handleWrapError( - instance, - error, - name, - context, - args, - options, - callback - ) { - if (options.useErrorHandlers) { - var _options = { error: error }; - return instance.execPost( - name, - context, - args, - _options, - function (error) { - return typeof callback === "function" && callback(error); - } - ); - } else { - return typeof callback === "function" ? callback(error) : undefined; - } - } +function createLongLongConversion(bitLength, { unsigned }) { + const upperBound = Number.MAX_SAFE_INTEGER; + const lowerBound = unsigned ? 0 : Number.MIN_SAFE_INTEGER; + const asBigIntN = unsigned ? BigInt.asUintN : BigInt.asIntN; - Kareem.prototype.wrap = function (name, fn, context, args, options) { - const lastArg = args.length > 0 ? args[args.length - 1] : null; - const argsWithoutCb = - typeof lastArg === "function" ? args.slice(0, args.length - 1) : args; - const _this = this; + return (value, options = {}) => { + let x = toNumber(value, options); + x = censorNegativeZero(x); - options = options || {}; - const checkForPromise = options.checkForPromise; + if (options.enforceRange) { + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite number", options); + } - this.execPre(name, context, args, function (error) { - if (error) { - const numCallbackParams = options.numCallbackParams || 0; - const errorArgs = options.contextParameter ? [context] : []; - for (var i = errorArgs.length; i < numCallbackParams; ++i) { - errorArgs.push(null); - } - return _handleWrapError( - _this, - error, - name, - context, - errorArgs, - options, - lastArg - ); - } + x = integerPart(x); - const end = - typeof lastArg === "function" ? args.length - 1 : args.length; - const numParameters = fn.length; - const ret = fn.apply(context, args.slice(0, end).concat(_cb)); - - if (checkForPromise) { - if (ret != null && typeof ret.then === "function") { - // Thenable, use it - return ret.then( - (res) => _cb(null, res), - (err) => _cb(err) - ); - } + if (x < lowerBound || x > upperBound) { + throw makeException( + TypeError, + `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, + options + ); + } - // If `fn()` doesn't have a callback argument and doesn't return a - // promise, assume it is sync - if (numParameters < end + 1) { - return _cb(null, ret); - } - } + return x; + } - function _cb() { - const args = arguments; - const argsWithoutError = Array.prototype.slice.call(arguments, 1); - if (options.nullResultByDefault && argsWithoutError.length === 0) { - argsWithoutError.push(null); - } - if (arguments[0]) { - // Assume error - return _handleWrapError( - _this, - arguments[0], - name, - context, - argsWithoutError, - options, - lastArg - ); - } else { - _this.execPost(name, context, argsWithoutError, function () { - if (arguments[0]) { - return typeof lastArg === "function" - ? lastArg(arguments[0]) - : undefined; - } + if (!Number.isNaN(x) && options.clamp) { + x = Math.min(Math.max(x, lowerBound), upperBound); + x = evenRound(x); + return x; + } - return typeof lastArg === "function" - ? lastArg.apply(context, arguments) - : undefined; - }); - } - } - }); - }; + if (!Number.isFinite(x) || x === 0) { + return 0; + } - Kareem.prototype.filter = function (fn) { - const clone = this.clone(); + let xBigInt = BigInt(integerPart(x)); + xBigInt = asBigIntN(bitLength, xBigInt); + return Number(xBigInt); + }; +} - const pres = Array.from(clone._pres.keys()); - for (const name of pres) { - const hooks = this._pres - .get(name) - .map((h) => Object.assign({}, h, { name: name })) - .filter(fn); +exports.any = value => { + return value; +}; - if (hooks.length === 0) { - clone._pres.delete(name); - continue; - } +exports.undefined = () => { + return undefined; +}; - hooks.numAsync = hooks.filter((h) => h.isAsync).length; +exports.boolean = value => { + return Boolean(value); +}; - clone._pres.set(name, hooks); - } +exports.byte = createIntegerConversion(8, { unsigned: false }); +exports.octet = createIntegerConversion(8, { unsigned: true }); - const posts = Array.from(clone._posts.keys()); - for (const name of posts) { - const hooks = this._posts - .get(name) - .map((h) => Object.assign({}, h, { name: name })) - .filter(fn); +exports.short = createIntegerConversion(16, { unsigned: false }); +exports["unsigned short"] = createIntegerConversion(16, { unsigned: true }); - if (hooks.length === 0) { - clone._posts.delete(name); - continue; - } +exports.long = createIntegerConversion(32, { unsigned: false }); +exports["unsigned long"] = createIntegerConversion(32, { unsigned: true }); - clone._posts.set(name, hooks); - } +exports["long long"] = createLongLongConversion(64, { unsigned: false }); +exports["unsigned long long"] = createLongLongConversion(64, { unsigned: true }); - return clone; - }; +exports.double = (value, options = {}) => { + const x = toNumber(value, options); - Kareem.prototype.hasHooks = function (name) { - return this._pres.has(name) || this._posts.has(name); - }; + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite floating-point value", options); + } - Kareem.prototype.createWrapper = function (name, fn, context, options) { - var _this = this; - if (!this.hasHooks(name)) { - // Fast path: if there's no hooks for this function, just return the - // function wrapped in a nextTick() - return function () { - process.nextTick(() => fn.apply(this, arguments)); - }; - } - return function () { - var _context = context || this; - var args = Array.prototype.slice.call(arguments); - _this.wrap(name, fn, _context, args, options); - }; - }; + return x; +}; - Kareem.prototype.pre = function (name, isAsync, fn, error, unshift) { - let options = {}; - if (typeof isAsync === "object" && isAsync != null) { - options = isAsync; - isAsync = options.isAsync; - } else if (typeof arguments[1] !== "boolean") { - error = fn; - fn = isAsync; - isAsync = false; - } +exports["unrestricted double"] = (value, options = {}) => { + const x = toNumber(value, options); - const pres = get(this._pres, name, []); - this._pres.set(name, pres); + return x; +}; - if (isAsync) { - pres.numAsync = pres.numAsync || 0; - ++pres.numAsync; - } +exports.float = (value, options = {}) => { + const x = toNumber(value, options); - if (typeof fn !== "function") { - throw new Error('pre() requires a function, got "' + typeof fn + '"'); - } + if (!Number.isFinite(x)) { + throw makeException(TypeError, "is not a finite floating-point value", options); + } - if (unshift) { - pres.unshift( - Object.assign({}, options, { fn: fn, isAsync: isAsync }) - ); - } else { - pres.push(Object.assign({}, options, { fn: fn, isAsync: isAsync })); - } + if (Object.is(x, -0)) { + return x; + } - return this; - }; + const y = Math.fround(x); - Kareem.prototype.post = function (name, options, fn, unshift) { - const hooks = get(this._posts, name, []); + if (!Number.isFinite(y)) { + throw makeException(TypeError, "is outside the range of a single-precision floating-point value", options); + } - if (typeof options === "function") { - unshift = !!fn; - fn = options; - options = {}; - } + return y; +}; - if (typeof fn !== "function") { - throw new Error( - 'post() requires a function, got "' + typeof fn + '"' - ); - } +exports["unrestricted float"] = (value, options = {}) => { + const x = toNumber(value, options); - if (unshift) { - hooks.unshift(Object.assign({}, options, { fn: fn })); - } else { - hooks.push(Object.assign({}, options, { fn: fn })); - } - this._posts.set(name, hooks); - return this; - }; + if (isNaN(x)) { + return x; + } - Kareem.prototype.clone = function () { - const n = new Kareem(); + if (Object.is(x, -0)) { + return x; + } - for (let key of this._pres.keys()) { - const clone = this._pres.get(key).slice(); - clone.numAsync = this._pres.get(key).numAsync; - n._pres.set(key, clone); - } - for (let key of this._posts.keys()) { - n._posts.set(key, this._posts.get(key).slice()); - } + return Math.fround(x); +}; - return n; - }; +exports.DOMString = (value, options = {}) => { + if (options.treatNullAsEmptyString && value === null) { + return ""; + } - Kareem.prototype.merge = function (other, clone) { - clone = arguments.length === 1 ? true : clone; - var ret = clone ? this.clone() : this; - - for (let key of other._pres.keys()) { - const sourcePres = get(ret._pres, key, []); - const deduplicated = other._pres - .get(key) - // Deduplicate based on `fn` - .filter((p) => sourcePres.map((_p) => _p.fn).indexOf(p.fn) === -1); - const combined = sourcePres.concat(deduplicated); - combined.numAsync = sourcePres.numAsync || 0; - combined.numAsync += deduplicated.filter((p) => p.isAsync).length; - ret._pres.set(key, combined); - } - for (let key of other._posts.keys()) { - const sourcePosts = get(ret._posts, key, []); - const deduplicated = other._posts - .get(key) - .filter((p) => sourcePosts.indexOf(p) === -1); - ret._posts.set(key, sourcePosts.concat(deduplicated)); - } - - return ret; - }; + if (typeof value === "symbol") { + throw makeException(TypeError, "is a symbol, which cannot be converted to a string", options); + } - function get(map, key, def) { - if (map.has(key)) { - return map.get(key); - } - return def; - } + const StringCtor = options.globals ? options.globals.String : String; + return StringCtor(value); +}; - function callMiddlewareFunction(fn, context, args, next) { - let maybePromise; - try { - maybePromise = fn.apply(context, args); - } catch (error) { - return next(error); - } +exports.ByteString = (value, options = {}) => { + const x = exports.DOMString(value, options); + let c; + for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { + if (c > 255) { + throw makeException(TypeError, "is not a valid ByteString", options); + } + } - if (isPromise(maybePromise)) { - maybePromise.then( - () => next(), - (err) => next(err) - ); - } + return x; +}; + +exports.USVString = (value, options = {}) => { + const S = exports.DOMString(value, options); + const n = S.length; + const U = []; + for (let i = 0; i < n; ++i) { + const c = S.charCodeAt(i); + if (c < 0xD800 || c > 0xDFFF) { + U.push(String.fromCodePoint(c)); + } else if (0xDC00 <= c && c <= 0xDFFF) { + U.push(String.fromCodePoint(0xFFFD)); + } else if (i === n - 1) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + const d = S.charCodeAt(i + 1); + if (0xDC00 <= d && d <= 0xDFFF) { + const a = c & 0x3FF; + const b = d & 0x3FF; + U.push(String.fromCodePoint((2 << 15) + ((2 << 9) * a) + b)); + ++i; + } else { + U.push(String.fromCodePoint(0xFFFD)); } + } + } - function isPromise(v) { - return v != null && typeof v.then === "function"; - } + return U.join(""); +}; - function decorateNextFn(fn) { - var called = false; - var _this = this; - return function () { - // Ensure this function can only be called once - if (called) { - return; - } - called = true; - // Make sure to clear the stack so try/catch doesn't catch errors - // in subsequent middleware - return process.nextTick(() => fn.apply(_this, arguments)); - }; - } +exports.object = (value, options = {}) => { + if (value === null || (typeof value !== "object" && typeof value !== "function")) { + throw makeException(TypeError, "is not an object", options); + } - module.exports = Kareem; + return value; +}; + +const abByteLengthGetter = + Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; +const sabByteLengthGetter = + typeof SharedArrayBuffer === "function" ? + Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, "byteLength").get : + null; + +function isNonSharedArrayBuffer(value) { + try { + // This will throw on SharedArrayBuffers, but not detached ArrayBuffers. + // (The spec says it should throw, but the spec conflicts with implementations: https://github.com/tc39/ecma262/issues/678) + abByteLengthGetter.call(value); + + return true; + } catch { + return false; + } +} + +function isSharedArrayBuffer(value) { + try { + sabByteLengthGetter.call(value); + return true; + } catch { + return false; + } +} + +function isArrayBufferDetached(value) { + try { + // eslint-disable-next-line no-new + new Uint8Array(value); + return false; + } catch { + return true; + } +} - /***/ - }, +exports.ArrayBuffer = (value, options = {}) => { + if (!isNonSharedArrayBuffer(value)) { + if (options.allowShared && !isSharedArrayBuffer(value)) { + throw makeException(TypeError, "is not an ArrayBuffer or SharedArrayBuffer", options); + } + throw makeException(TypeError, "is not an ArrayBuffer", options); + } + if (isArrayBufferDetached(value)) { + throw makeException(TypeError, "is a detached ArrayBuffer", options); + } - /***/ 7147: /***/ (module) => { - module.exports = Pager; + return value; +}; - function Pager(pageSize, opts) { - if (!(this instanceof Pager)) return new Pager(pageSize, opts); +const dvByteLengthGetter = + Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get; +exports.DataView = (value, options = {}) => { + try { + dvByteLengthGetter.call(value); + } catch (e) { + throw makeException(TypeError, "is not a DataView", options); + } - 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); - }; + if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { + throw makeException(TypeError, "is backed by a SharedArrayBuffer, which is not allowed", options); + } + if (isArrayBufferDetached(value.buffer)) { + throw makeException(TypeError, "is backed by a detached ArrayBuffer", options); + } - Pager.prototype.lastUpdate = function () { - if (!this.updates || !this.updates.length) return null; - var page = this.updates.pop(); - page.updated = false; - return page; - }; + return value; +}; + +// Returns the unforgeable `TypedArray` constructor name or `undefined`, +// if the `this` value isn't a valid `TypedArray` object. +// +// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype-@@tostringtag +const typedArrayNameGetter = Object.getOwnPropertyDescriptor( + Object.getPrototypeOf(Uint8Array).prototype, + Symbol.toStringTag +).get; +[ + Int8Array, + Int16Array, + Int32Array, + Uint8Array, + Uint16Array, + Uint32Array, + Uint8ClampedArray, + Float32Array, + Float64Array +].forEach(func => { + const { name } = func; + const article = /^[AEIOU]/u.test(name) ? "an" : "a"; + exports[name] = (value, options = {}) => { + if (!ArrayBuffer.isView(value) || typedArrayNameGetter.call(value) !== name) { + throw makeException(TypeError, `is not ${article} ${name} object`, options); + } + if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { + throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options); + } + if (isArrayBufferDetached(value.buffer)) { + throw makeException(TypeError, "is a view on a detached ArrayBuffer", options); + } - Pager.prototype._array = function (i, noAllocate) { - if (i >= this.maxPages) { - if (noAllocate) return; - grow(this, i); - } + return value; + }; +}); - factor(i, this.path); +// Common definitions - var arr = this.pages; +exports.ArrayBufferView = (value, options = {}) => { + if (!ArrayBuffer.isView(value)) { + throw makeException(TypeError, "is not a view on an ArrayBuffer or SharedArrayBuffer", options); + } - for (var j = this.level; j > 0; j--) { - var p = this.path[j]; - var next = arr[p]; + if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { + throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options); + } - if (!next) { - if (noAllocate) return; - next = arr[p] = new Array(32768); - } + if (isArrayBufferDetached(value.buffer)) { + throw makeException(TypeError, "is a view on a detached ArrayBuffer", options); + } + return value; +}; - arr = next; - } +exports.BufferSource = (value, options = {}) => { + if (ArrayBuffer.isView(value)) { + if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { + throw makeException(TypeError, "is a view on a SharedArrayBuffer, which is not allowed", options); + } - return arr; - }; + if (isArrayBufferDetached(value.buffer)) { + throw makeException(TypeError, "is a view on a detached ArrayBuffer", options); + } + return value; + } - Pager.prototype.get = function (i, noAllocate) { - var arr = this._array(i, noAllocate); - var first = this.path[0]; - var page = arr && arr[first]; + if (!options.allowShared && !isNonSharedArrayBuffer(value)) { + throw makeException(TypeError, "is not an ArrayBuffer or a view on one", options); + } + if (options.allowShared && !isSharedArrayBuffer(value) && !isNonSharedArrayBuffer(value)) { + throw makeException(TypeError, "is not an ArrayBuffer, SharedArrayBuffer, or a view on one", options); + } + if (isArrayBufferDetached(value)) { + throw makeException(TypeError, "is a detached ArrayBuffer", options); + } - if (!page && !noAllocate) { - page = arr[first] = new Page(i, alloc(this.pageSize)); - if (i >= this.length) this.length = i + 1; - } + return value; +}; - if ( - page && - page.buffer === this.deduplicate && - this.deduplicate && - !noAllocate - ) { - page.buffer = copy(page.buffer); - page.deduplicate = 0; - } +exports.DOMTimeStamp = exports["unsigned long long"]; - 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; +/***/ 9197: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!buf || (this.zeros && buf.equals && buf.equals(this.zeros))) { - arr[first] = undefined; - return; - } +"use strict"; - if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) { - buf = this.deduplicate; - } - var page = arr[first]; - var b = truncate(buf, this.pageSize); +const { URL, URLSearchParams } = __nccwpck_require__(7488); +const urlStateMachine = __nccwpck_require__(8934); +const percentEncoding = __nccwpck_require__(8453); - if (page) page.buffer = b; - else arr[first] = new Page(i, b); - }; +const sharedGlobalObject = { Array, Object, Promise, String, TypeError }; +URL.install(sharedGlobalObject, ["Window"]); +URLSearchParams.install(sharedGlobalObject, ["Window"]); - Pager.prototype.toBuffer = function () { - var list = new Array(this.length); - var empty = alloc(this.pageSize); - var ptr = 0; +exports.URL = sharedGlobalObject.URL; +exports.URLSearchParams = sharedGlobalObject.URLSearchParams; - 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; - } - } +exports.parseURL = urlStateMachine.parseURL; +exports.basicURLParse = urlStateMachine.basicURLParse; +exports.serializeURL = urlStateMachine.serializeURL; +exports.serializePath = urlStateMachine.serializePath; +exports.serializeHost = urlStateMachine.serializeHost; +exports.serializeInteger = urlStateMachine.serializeInteger; +exports.serializeURLOrigin = urlStateMachine.serializeURLOrigin; +exports.setTheUsername = urlStateMachine.setTheUsername; +exports.setThePassword = urlStateMachine.setThePassword; +exports.cannotHaveAUsernamePasswordPort = urlStateMachine.cannotHaveAUsernamePasswordPort; +exports.hasAnOpaquePath = urlStateMachine.hasAnOpaquePath; - return Buffer.concat(list); - }; +exports.percentDecodeString = percentEncoding.percentDecodeString; +exports.percentDecodeBytes = percentEncoding.percentDecodeBytes; - 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; - } +/***/ 1931: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - function copy(buf) { - var cpy = Buffer.allocUnsafe - ? Buffer.allocUnsafe(buf.length) - : new Buffer(buf.length); - buf.copy(cpy); - return cpy; - } +"use strict"; - 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; - } +const conversions = __nccwpck_require__(6362); +const utils = __nccwpck_require__(861); - /***/ - }, +exports.convert = (globalObject, value, { context = "The provided value" } = {}) => { + if (typeof value !== "function") { + throw new globalObject.TypeError(context + " is not a function"); + } - /***/ 5517: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - // Core module - const core = __nccwpck_require__(3994); - const Instrumentation = __nccwpck_require__(2138); - - // Set up the connect function - const connect = __nccwpck_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 = __nccwpck_require__(4239).BulkWriteError; - connect.BulkWriteError = connect.MongoBulkWriteError; - - // Actual driver classes exported - connect.Admin = __nccwpck_require__(3238); - connect.MongoClient = __nccwpck_require__(1545); - connect.Db = __nccwpck_require__(6662); - connect.Collection = __nccwpck_require__(5193); - connect.Server = __nccwpck_require__(8421); - connect.ReplSet = __nccwpck_require__(382); - connect.Mongos = __nccwpck_require__(2048); - connect.ReadPreference = core.ReadPreference; - connect.GridStore = __nccwpck_require__(9406); - connect.Chunk = __nccwpck_require__(3890); - connect.Logger = core.Logger; - connect.AggregationCursor = __nccwpck_require__(7429); - connect.CommandCursor = __nccwpck_require__(538); - connect.Cursor = __nccwpck_require__(7159); - connect.GridFSBucket = __nccwpck_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; - }; + function invokeTheCallbackFunction(...args) { + const thisArg = utils.tryWrapperForImpl(this); + let callResult; - // Set our exports to be the connect function - module.exports = connect; + for (let i = 0; i < args.length; i++) { + args[i] = utils.tryWrapperForImpl(args[i]); + } - /***/ - }, + callResult = Reflect.apply(value, thisArg, args); - /***/ 3238: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const applyWriteConcern = __nccwpck_require__(1371).applyWriteConcern; - - const AddUserOperation = __nccwpck_require__(7057); - const ExecuteDbAdminCommandOperation = __nccwpck_require__(1681); - const RemoveUserOperation = __nccwpck_require__(1969); - const ValidateCollectionOperation = __nccwpck_require__(9263); - const ListDatabasesOperation = __nccwpck_require__(9929); - - const executeOperation = __nccwpck_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); + callResult = conversions["any"](callResult, { context: context, globals: globalObject }); - // Internal state - this.s = { - db: db, - topology: topology, - promiseLibrary: promiseLibrary, - }; - } + return callResult; + } - /** - * 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() : {}; + invokeTheCallbackFunction.construct = (...args) => { + for (let i = 0; i < args.length; i++) { + args[i] = utils.tryWrapperForImpl(args[i]); + } - const commandOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - command, - options - ); + let callResult = Reflect.construct(value, args); - return executeOperation( - this.s.db.s.topology, - commandOperation, - callback - ); - }; + callResult = conversions["any"](callResult, { context: context, globals: globalObject }); - /** - * 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 || {}; + return callResult; + }; - const cmd = { buildinfo: 1 }; + invokeTheCallbackFunction[utils.wrapperSymbol] = value; + invokeTheCallbackFunction.objectReference = value; - const buildInfoOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - cmd, - options - ); + return invokeTheCallbackFunction; +}; - 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 }; +/***/ 5031: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const serverInfoOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - cmd, - options - ); +"use strict"; - return executeOperation( - this.s.db.s.topology, - serverInfoOperation, - callback - ); - }; +const usm = __nccwpck_require__(8934); +const urlencoded = __nccwpck_require__(2934); +const URLSearchParams = __nccwpck_require__(9709); - /** - * 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 || {}; +exports.implementation = class URLImpl { + constructor(globalObject, constructorArgs) { + const url = constructorArgs[0]; + const base = constructorArgs[1]; - const serverStatusOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - { serverStatus: 1 }, - options - ); + let parsedBase = null; + if (base !== undefined) { + parsedBase = usm.basicURLParse(base); + if (parsedBase === null) { + throw new TypeError(`Invalid base URL: ${base}`); + } + } - return executeOperation( - this.s.db.s.topology, - serverStatusOperation, - callback - ); - }; + const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); + if (parsedURL === null) { + throw new TypeError(`Invalid URL: ${url}`); + } - /** - * 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 query = parsedURL.query !== null ? parsedURL.query : ""; - const cmd = { ping: 1 }; + this._url = parsedURL; - const pingOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - cmd, - options - ); + // We cannot invoke the "new URLSearchParams object" algorithm without going through the constructor, which strips + // question mark by default. Therefore the doNotStripQMark hack is used. + this._query = URLSearchParams.createImpl(globalObject, [query], { doNotStripQMark: true }); + this._query._url = this; + } - return executeOperation(this.s.db.s.topology, pingOperation, callback); - }; + get href() { + return usm.serializeURL(this._url); + } - /** - * 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {boolean} [options.fsync=false] **Deprecated** Specify a file sync write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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; + set href(v) { + const parsedURL = usm.basicURLParse(v); + if (parsedURL === null) { + throw new TypeError(`Invalid URL: ${v}`); + } - // Special case where there is no password ($external users) - if ( - typeof username === "string" && - password != null && - typeof password === "object" - ) { - options = password; - password = null; - } + this._url = parsedURL; - 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 - ); + this._query._list.splice(0); + const { query } = parsedURL; + if (query !== null) { + this._query._list = urlencoded.parseUrlencodedString(query); + } + } - return executeOperation( - this.s.db.s.topology, - addUserOperation, - callback - ); - }; + get origin() { + return usm.serializeURLOrigin(this._url); + } - /** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {boolean} [options.fsync=false] **Deprecated** Specify a file sync write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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; + get protocol() { + return `${this._url.scheme}:`; + } - 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 - ); + set protocol(v) { + usm.basicURLParse(`${v}:`, { url: this._url, stateOverride: "scheme start" }); + } - return executeOperation( - this.s.db.s.topology, - removeUserOperation, - callback - ); - }; + get username() { + return this._url.username; + } - /** - * 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 || {}; + set username(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } - const validateCollectionOperation = new ValidateCollectionOperation( - this, - collectionName, - options - ); + usm.setTheUsername(this._url, v); + } - return executeOperation( - this.s.db.s.topology, - validateCollectionOperation, - callback - ); - }; + get password() { + return this._url.password; + } - /** - * 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 || {}; + set password(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } - return executeOperation( - this.s.db.s.topology, - new ListDatabasesOperation(this.s.db, options), - callback - ); - }; + usm.setThePassword(this._url, v); + } - /** - * 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 || {}; + get host() { + const url = this._url; - const replSetGetStatusOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - { replSetGetStatus: 1 }, - options - ); + if (url.host === null) { + return ""; + } - return executeOperation( - this.s.db.s.topology, - replSetGetStatusOperation, - callback - ); - }; + if (url.port === null) { + return usm.serializeHost(url.host); + } - module.exports = Admin; + return `${usm.serializeHost(url.host)}:${usm.serializeInteger(url.port)}`; + } - /***/ - }, + set host(v) { + if (usm.hasAnOpaquePath(this._url)) { + return; + } - /***/ 7429: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const MongoError = __nccwpck_require__(3994).MongoError; - const Cursor = __nccwpck_require__(7159); - const CursorState = __nccwpck_require__(4847).CursorState; - - /** - * @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); - } + usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); + } - /** - * 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, - }); - } + get hostname() { + if (this._url.host === null) { + return ""; + } - if (typeof value !== "number") { - throw MongoError.create({ - message: "batchSize requires an integer", - driver: true, - }); - } + return usm.serializeHost(this._url.host); + } - this.operation.options.batchSize = value; - this.setCursorBatchSize(value); - return this; - } + set hostname(v) { + if (usm.hasAnOpaquePath(this._url)) { + return; + } - /** - * 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; - } + usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); + } - /** - * 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; - } + get port() { + if (this._url.port === null) { + return ""; + } - /** - * 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; - } + return usm.serializeInteger(this._url.port); + } - /** - * 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; - } + set port(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } - /** - * 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; - } + if (v === "") { + this._url.port = null; + } else { + usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); + } + } - /** - * 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; - } + get pathname() { + return usm.serializePath(this._url); + } - /** - * 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; - } + set pathname(v) { + if (usm.hasAnOpaquePath(this._url)) { + return; + } - /** - * 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; - } + this._url.path = []; + usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); + } - /** - * 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; - } + get search() { + if (this._url.query === null || this._url.query === "") { + return ""; + } - /** - * 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; - } + return `?${this._url.query}`; + } - /** - * 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; - } + set search(v) { + const url = this._url; - /** - * Add a unwind stage to the aggregation pipeline - * @method - * @param {(string|object)} field The unwind field name or stage document. - * @return {AggregationCursor} - */ - unwind(field) { - this.operation.addToPipeline({ $unwind: field }); - return this; - } + if (v === "") { + url.query = null; + this._query._list = []; + return; + } - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } - } - - // aliases - AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; - - /** - * 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 - * - * For backwards compatibility, a verbosity of true is interpreted as "allPlansExecution" - * and false as "queryPlanner". Prior to server version 3.6, aggregate() - * ignores the verbosity parameter and executes in "queryPlanner". - * - * @method AggregationCursor.prototype.explain - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [verbosity=true] - An optional mode in which to run the 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; - - /***/ - }, + const input = v[0] === "?" ? v.substring(1) : v; + url.query = ""; + usm.basicURLParse(input, { url, stateOverride: "query" }); + this._query._list = urlencoded.parseUrlencodedString(input); + } - /***/ 2138: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + get searchParams() { + return this._query; + } - const EventEmitter = __nccwpck_require__(8614).EventEmitter; + get hash() { + if (this._url.fragment === null || this._url.fragment === "") { + return ""; + } - class Instrumentation extends EventEmitter { - constructor() { - super(); - } + return `#${this._url.fragment}`; + } - instrument(MongoClient, callback) { - // store a reference to the original functions - this.$MongoClient = MongoClient; - const $prototypeConnect = (this.$prototypeConnect = - MongoClient.prototype.connect); + set hash(v) { + if (v === "") { + this._url.fragment = null; + return; + } - 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); - }; + const input = v[0] === "#" ? v.substring(1) : v; + this._url.fragment = ""; + usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); + } - if (typeof callback === "function") callback(null, this); - } + toJSON() { + return this.href; + } +}; - uninstrument() { - this.$MongoClient.prototype.connect = this.$prototypeConnect; - } - } - module.exports = Instrumentation; +/***/ }), - /***/ - }, +/***/ 1851: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /***/ 1749: /***/ (__unused_webpack_module, exports) => { - "use strict"; +"use strict"; - // async function* asyncIterator() { - // while (true) { - // const value = await this.next(); - // if (!value) { - // await this.close(); - // return; - // } - // yield value; - // } - // } +const conversions = __nccwpck_require__(6362); +const utils = __nccwpck_require__(861); - // TODO: change this to the async generator function above - function asyncIterator() { - const cursor = this; +const implSymbol = utils.implSymbol; +const ctorRegistrySymbol = utils.ctorRegistrySymbol; - return { - next: function () { - return Promise.resolve() - .then(() => cursor.next()) - .then((value) => { - if (!value) { - return cursor.close().then(() => ({ value, done: true })); - } - return { value, done: false }; - }); - }, - }; - } +const interfaceName = "URL"; - exports.asyncIterator = asyncIterator; +exports.is = value => { + return utils.isObject(value) && utils.hasOwn(value, implSymbol) && value[implSymbol] instanceof Impl.implementation; +}; +exports.isImpl = value => { + return utils.isObject(value) && value instanceof Impl.implementation; +}; +exports.convert = (globalObject, value, { context = "The provided value" } = {}) => { + if (exports.is(value)) { + return utils.implForWrapper(value); + } + throw new globalObject.TypeError(`${context} is not of type 'URL'.`); +}; - /***/ - }, +function makeWrapper(globalObject, newTarget) { + let proto; + if (newTarget !== undefined) { + proto = newTarget.prototype; + } - /***/ 4239: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Long = __nccwpck_require__(3994).BSON.Long; - const MongoError = __nccwpck_require__(3994).MongoError; - const ObjectID = __nccwpck_require__(3994).BSON.ObjectID; - const BSON = __nccwpck_require__(3994).BSON; - const MongoWriteConcernError = - __nccwpck_require__(3994).MongoWriteConcernError; - const emitWarningOnce = __nccwpck_require__(1371).emitWarningOnce; - const toError = __nccwpck_require__(1371).toError; - const handleCallback = __nccwpck_require__(1371).handleCallback; - const applyRetryableWrites = - __nccwpck_require__(1371).applyRetryableWrites; - const applyWriteConcern = __nccwpck_require__(1371).applyWriteConcern; - const executeLegacyOperation = - __nccwpck_require__(1371).executeLegacyOperation; - const isPromiseLike = __nccwpck_require__(1371).isPromiseLike; - const hasAtomicOperators = __nccwpck_require__(1371).hasAtomicOperators; - const maxWireVersion = __nccwpck_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; - } - } - - const kUpsertedIds = Symbol("upsertedIds"); - const kInsertedIds = Symbol("insertedIds"); - - /** - * @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; - this[kUpsertedIds] = undefined; - this[kInsertedIds] = undefined; - } - - /** Number of documents inserted. */ - get insertedCount() { - return typeof this.result.nInserted !== "number" - ? 0 - : this.result.nInserted; - } - /** Number of documents matched for update. */ - get matchedCount() { - return typeof this.result.nMatched !== "number" - ? 0 - : this.result.nMatched; - } - /** Number of documents modified. */ - get modifiedCount() { - return typeof this.result.nModified !== "number" - ? 0 - : this.result.nModified; - } - /** Number of documents deleted. */ - get deletedCount() { - return typeof this.result.nRemoved !== "number" - ? 0 - : this.result.nRemoved; - } - /** Number of documents upserted. */ - get upsertedCount() { - return !this.result.upserted ? 0 : this.result.upserted.length; - } - - /** Upserted document generated Id's, hash key is the index of the originating operation */ - get upsertedIds() { - if (this[kUpsertedIds]) { - return this[kUpsertedIds]; - } + if (!utils.isObject(proto)) { + proto = globalObject[ctorRegistrySymbol]["URL"].prototype; + } - this[kUpsertedIds] = {}; - for (const doc of this.result.upserted || []) { - this[kUpsertedIds][doc.index] = doc._id; - } - return this[kUpsertedIds]; - } + return Object.create(proto); +} - /** Inserted document generated Id's, hash key is the index of the originating operation */ - get insertedIds() { - if (this[kInsertedIds]) { - return this[kInsertedIds]; - } +exports.create = (globalObject, constructorArgs, privateData) => { + const wrapper = makeWrapper(globalObject); + return exports.setup(wrapper, globalObject, constructorArgs, privateData); +}; - this[kInsertedIds] = {}; - for (const doc of this.result.insertedIds || []) { - this[kInsertedIds][doc.index] = doc._id; - } - return this[kInsertedIds]; - } +exports.createImpl = (globalObject, constructorArgs, privateData) => { + const wrapper = exports.create(globalObject, constructorArgs, privateData); + return utils.implForWrapper(wrapper); +}; - /** The number of inserted documents @type {number} */ - get n() { - return this.result.insertedCount; - } +exports._internalSetup = (wrapper, globalObject) => {}; - /** - * Evaluates to true if the bulk operation correctly executes - * @type {boolean} - */ - get ok() { - return this.result.ok; - } +exports.setup = (wrapper, globalObject, constructorArgs = [], privateData = {}) => { + privateData.wrapper = wrapper; - /** - * The number of inserted documents - * @type {number} - */ - get nInserted() { - return this.result.nInserted; - } + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: new Impl.implementation(globalObject, constructorArgs, privateData), + configurable: true + }); - /** - * Number of upserted documents - * @type {number} - */ - get nUpserted() { - return this.result.nUpserted; - } + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper; +}; - /** - * Number of matched documents - * @type {number} - */ - get nMatched() { - return this.result.nMatched; - } +exports.new = (globalObject, newTarget) => { + const wrapper = makeWrapper(globalObject, newTarget); - /** - * Number of documents updated physically on disk - * @type {number} - */ - get nModified() { - return this.result.nModified; - } + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: Object.create(Impl.implementation.prototype), + configurable: true + }); - /** - * Number of removed documents - * @type {number} - */ - get nRemoved() { - return this.result.nRemoved; - } + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper[implSymbol]; +}; - /** - * Returns an array of all inserted ids - * - * @return {object[]} - */ - getInsertedIds() { - return this.result.insertedIds; - } +const exposed = new Set(["Window", "Worker"]); - /** - * Returns an array of all upserted ids - * - * @return {object[]} - */ - getUpsertedIds() { - return this.result.upserted; - } +exports.install = (globalObject, globalNames) => { + if (!globalNames.some(globalName => exposed.has(globalName))) { + return; + } - /** - * 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]; + const ctorRegistry = utils.initCtorRegistry(globalObject); + class URL { + constructor(url) { + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to construct 'URL': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to construct 'URL': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + { + let curArg = arguments[1]; + if (curArg !== undefined) { + curArg = conversions["USVString"](curArg, { + context: "Failed to construct 'URL': parameter 2", + globals: globalObject + }); } + args.push(curArg); + } + return exports.setup(Object.create(new.target.prototype), globalObject, args); + } - /** - * Returns raw internal result - * - * @return {object} - */ - getRawResponse() { - return this.result; - } + toJSON() { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'toJSON' called on an object that is not a valid instance of URL."); + } - /** - * Returns true if the bulk operation contains a write error - * - * @return {boolean} - */ - hasWriteErrors() { - return this.result.writeErrors.length > 0; - } + return esValue[implSymbol].toJSON(); + } - /** - * Returns the number of write errors off the bulk operation - * - * @return {number} - */ - getWriteErrorCount() { - return this.result.writeErrors.length; - } + get href() { + const esValue = this !== null && this !== undefined ? this : globalObject; - /** - * 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; - } + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get href' called on an object that is not a valid instance of URL."); + } - /** - * Retrieve all write errors - * - * @return {WriteError[]} - */ - getWriteErrors() { - return this.result.writeErrors; - } + return esValue[implSymbol]["href"]; + } - /** - * Retrieve lastOp if available - * - * @return {object} - */ - getLastOp() { - return this.result.lastOp; - } + set href(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; - /** - * 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; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set href' called on an object that is not a valid instance of URL."); + } - // TODO: Something better - if (i === 0) errmsg = errmsg + " and "; - } + V = conversions["USVString"](V, { + context: "Failed to set the 'href' property on 'URL': The provided value", + globals: globalObject + }); - return new WriteConcernError({ - errmsg: errmsg, - code: WRITE_CONCERN_ERROR, - }); - } - } + esValue[implSymbol]["href"] = V; + } - /** - * @return {object} - */ - toJSON() { - return this.result; - } + toString() { + const esValue = this; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'toString' called on an object that is not a valid instance of URL."); + } - /** - * @return {string} - */ - toString() { - return `BulkWriteResult(${this.toJSON(this.result)})`; - } + return esValue[implSymbol]["href"]; + } - /** - * @return {boolean} - */ - isOk() { - return this.result.ok === 1; - } + get origin() { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get origin' called on an object that is not a valid instance of URL."); } - /** - * @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; - } + return esValue[implSymbol]["origin"]; + } - /** - * Write concern error code. - * @type {number} - */ - get code() { - return this.err.code; - } + get protocol() { + const esValue = this !== null && this !== undefined ? this : globalObject; - /** - * Write concern error message. - * @type {string} - */ - get errmsg() { - return this.err.errmsg; - } + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get protocol' called on an object that is not a valid instance of URL."); + } - /** - * @return {object} - */ - toJSON() { - return { code: this.err.code, errmsg: this.err.errmsg }; - } + return esValue[implSymbol]["protocol"]; + } - /** - * @return {string} - */ - toString() { - return `WriteConcernError(${this.err.errmsg})`; - } + set protocol(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set protocol' called on an object that is not a valid instance of URL."); } - /** - * @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; - } + V = conversions["USVString"](V, { + context: "Failed to set the 'protocol' property on 'URL': The provided value", + globals: globalObject + }); - /** - * WriteError code. - * @type {number} - */ - get code() { - return this.err.code; - } + esValue[implSymbol]["protocol"] = V; + } - /** - * WriteError original bulk operation index. - * @type {number} - */ - get index() { - return this.err.index; - } + get username() { + const esValue = this !== null && this !== undefined ? this : globalObject; - /** - * WriteError message. - * @type {string} - */ - get errmsg() { - return this.err.errmsg; - } + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get username' called on an object that is not a valid instance of URL."); + } - /** - * Returns the underlying operation that caused the error - * @return {object} - */ - getOperation() { - return this.err.op; - } + return esValue[implSymbol]["username"]; + } - /** - * @return {object} - */ - toJSON() { - return { - code: this.err.code, - index: this.err.index, - errmsg: this.err.errmsg, - op: this.err.op, - }; - } + set username(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; - /** - * @return {string} - */ - toString() { - return `WriteError(${JSON.stringify(this.toJSON())})`; - } + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set username' called on an object that is not a valid instance of URL."); } - /** - * 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; - } + V = conversions["USVString"](V, { + context: "Failed to set the 'username' property on 'URL': The provided value", + globals: globalObject + }); - // Do we have a top level error stop processing and return - if (result.ok === 0 && bulkResult.ok === 1) { - bulkResult.ok = 0; + esValue[implSymbol]["username"] = V; + } - const writeError = { - index: 0, - code: result.code || 0, - errmsg: result.message, - op: batch.operations[0], - }; + get password() { + const esValue = this !== null && this !== undefined ? this : globalObject; - bulkResult.writeErrors.push(new WriteError(writeError)); - return; - } else if (result.ok === 0 && bulkResult.ok === 0) { - return; - } + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get password' called on an object that is not a valid instance of URL."); + } - // Deal with opTime if available - if (result.opTime || result.lastOp) { - const opTime = result.lastOp || result.opTime; - let lastOpTS = null; - let lastOpT = null; + return esValue[implSymbol]["password"]; + } - // 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; - } - } - } - } + set password(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; - // If we have an insert Batch type - if (batch.batchType === INSERT && result.n) { - bulkResult.nInserted = bulkResult.nInserted + result.n; - } + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set password' called on an object that is not a valid instance of URL."); + } - // If we have an insert Batch type - if (batch.batchType === REMOVE && result.n) { - bulkResult.nRemoved = bulkResult.nRemoved + result.n; - } + V = conversions["USVString"](V, { + context: "Failed to set the 'password' property on 'URL': The provided value", + globals: globalObject + }); - let nUpserted = 0; + esValue[implSymbol]["password"] = V; + } - // We have an array of upserted values, we need to rewrite the indexes - if (Array.isArray(result.upserted)) { - nUpserted = result.upserted.length; + get host() { + const esValue = this !== null && this !== undefined ? this : globalObject; - 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; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get host' called on an object that is not a valid instance of URL."); + } - bulkResult.upserted.push({ - index: batch.originalZeroIndex, - _id: result.upserted, - }); - } + return esValue[implSymbol]["host"]; + } - // 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); + set host(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; - if (typeof nModified === "number") { - bulkResult.nModified = bulkResult.nModified + nModified; - } else { - bulkResult.nModified = null; - } - } + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set host' called on an object that is not a valid instance of URL."); + } - 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], - }; + V = conversions["USVString"](V, { + context: "Failed to set the 'host' property on 'URL': The provided value", + globals: globalObject + }); - bulkResult.writeErrors.push(new WriteError(writeError)); - } - } + esValue[implSymbol]["host"] = V; + } - if (result.writeConcernError) { - bulkResult.writeConcernErrors.push( - new WriteConcernError(result.writeConcernError) - ); - } - } + get hostname() { + const esValue = this !== null && this !== undefined ? this : globalObject; - function executeCommands(bulkOperation, options, callback) { - if (bulkOperation.s.batches.length === 0) { - return handleCallback( - callback, - null, - new BulkWriteResult(bulkOperation.s.bulkResult) - ); - } + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get hostname' called on an object that is not a valid instance of URL."); + } - const batch = bulkOperation.s.batches.shift(); + return esValue[implSymbol]["hostname"]; + } - 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); - } + set hostname(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; - // If we have and error - if (err) err.ok = 0; - if (err instanceof MongoWriteConcernError) { - return handleMongoWriteConcernError( - batch, - bulkOperation.s.bulkResult, - err, - callback - ); - } + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set hostname' called on an object that is not a valid instance of URL."); + } - // 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); - } + V = conversions["USVString"](V, { + context: "Failed to set the 'hostname' property on 'URL': The provided value", + globals: globalObject + }); - if (bulkOperation.handleWriteError(callback, writeResult)) return; + esValue[implSymbol]["hostname"] = V; + } - // Execute the next command in line - executeCommands(bulkOperation, options, callback); - } + get port() { + const esValue = this !== null && this !== undefined ? this : globalObject; - bulkOperation.finalOptionsHandler( - { options, batch, resultHandler }, - callback - ); + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get port' called on an object that is not a valid instance of URL."); } - /** - * 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 - ); + return esValue[implSymbol]["port"]; + } + + set port(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set port' called on an object that is not a valid instance of URL."); } - /** - * @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); + V = conversions["USVString"](V, { + context: "Failed to set the 'port' property on 'URL': The provided value", + globals: globalObject + }); - Object.assign(this, error); + esValue[implSymbol]["port"] = V; + } - this.name = "BulkWriteError"; - this.result = result; - } + get pathname() { + const esValue = this !== null && this !== undefined ? this : globalObject; - /** Number of documents inserted. */ - get insertedCount() { - return this.result.insertedCount; - } - /** Number of documents matched for update. */ - get matchedCount() { - return this.result.matchedCount; - } - /** Number of documents modified. */ - get modifiedCount() { - return this.result.modifiedCount; - } - /** Number of documents deleted. */ - get deletedCount() { - return this.result.deletedCount; - } - /** Number of documents upserted. */ - get upsertedCount() { - return this.result.upsertedCount; - } - /** Inserted document generated Id's, hash key is the index of the originating operation */ - get insertedIds() { - return this.result.insertedIds; - } - /** Upserted document generated Id's, hash key is the index of the originating operation */ - get upsertedIds() { - return this.result.upsertedIds; - } + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get pathname' called on an object that is not a valid instance of URL."); } - /** - * @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; - } + return esValue[implSymbol]["pathname"]; + } - /** - * 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, - }; + set pathname(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; - if (updateDocument.hint) { - document.hint = updateDocument.hint; - } + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set pathname' called on an object that is not a valid instance of URL."); + } - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } + V = conversions["USVString"](V, { + context: "Failed to set the 'pathname' property on 'URL': The provided value", + globals: globalObject + }); - /** - * 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, - }; + esValue[implSymbol]["pathname"] = V; + } - if (updateDocument.hint) { - document.hint = updateDocument.hint; - } + get search() { + const esValue = this !== null && this !== undefined ? this : globalObject; - if (!hasAtomicOperators(updateDocument)) { - throw new TypeError("Update document requires atomic operators"); - } + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get search' called on an object that is not a valid instance of URL."); + } - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } + return esValue[implSymbol]["search"]; + } - /** - * 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, - }; + set search(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; - if (replacement.hint) { - document.hint = replacement.hint; - } + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set search' called on an object that is not a valid instance of URL."); + } - if (hasAtomicOperators(replacement)) { - throw new TypeError( - "Replacement document must not use atomic operators" - ); - } + V = conversions["USVString"](V, { + context: "Failed to set the 'search' property on 'URL': The provided value", + globals: globalObject + }); - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } + esValue[implSymbol]["search"] = V; + } - /** - * 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; - } + get searchParams() { + const esValue = this !== null && this !== undefined ? this : globalObject; - /** - * 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, - }; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get searchParams' called on an object that is not a valid instance of URL."); + } - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, REMOVE, document); - } + return utils.getSameObject(this, "searchParams", () => { + return utils.tryWrapperForImpl(esValue[implSymbol]["searchParams"]); + }); + } - /** - * 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, - }; + get hash() { + const esValue = this !== null && this !== undefined ? this : globalObject; - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, REMOVE, document); - } + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get hash' called on an object that is not a valid instance of URL."); + } - /** - * backwards compatability for deleteOne - * @deprecated - */ - removeOne() { - emitWarningOnce( - "bulk operation `removeOne` has been deprecated, please use `deleteOne`" - ); - return this.deleteOne(); - } + return esValue[implSymbol]["hash"]; + } - /** - * backwards compatability for delete - * @deprecated - */ - remove() { - emitWarningOnce( - "bulk operation `remove` has been deprecated, please use `delete`" - ); - return this.delete(); - } + set hash(V) { + const esValue = this !== null && this !== undefined ? this : globalObject; + + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set hash' called on an object that is not a valid instance of URL."); } - /** - * @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; + V = conversions["USVString"](V, { + context: "Failed to set the 'hash' property on 'URL': The provided value", + globals: globalObject + }); - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; + esValue[implSymbol]["hash"] = V; + } + } + Object.defineProperties(URL.prototype, { + toJSON: { enumerable: true }, + href: { enumerable: true }, + toString: { enumerable: true }, + origin: { enumerable: true }, + protocol: { enumerable: true }, + username: { enumerable: true }, + password: { enumerable: true }, + host: { enumerable: true }, + hostname: { enumerable: true }, + port: { enumerable: true }, + pathname: { enumerable: true }, + search: { enumerable: true }, + searchParams: { enumerable: true }, + hash: { enumerable: true }, + [Symbol.toStringTag]: { value: "URL", configurable: true } + }); + ctorRegistry[interfaceName] = URL; + + Object.defineProperty(globalObject, interfaceName, { + configurable: true, + writable: true, + value: URL + }); + + if (globalNames.includes("Window")) { + Object.defineProperty(globalObject, "webkitURL", { + configurable: true, + writable: true, + value: URL + }); + } +}; - // Final results - const bulkResult = { - ok: 1, - writeErrors: [], - writeConcernErrors: [], - insertedIds: [], - nInserted: 0, - nUpserted: 0, - nMatched: 0, - nModified: 0, - nRemoved: 0, - upserted: [], - }; +const Impl = __nccwpck_require__(5031); - // 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); - } +/***/ 643: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * 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"); - } +"use strict"; - // Save a current selector - this.s.currentOp = { - selector: selector, - }; +const urlencoded = __nccwpck_require__(2934); + +exports.implementation = class URLSearchParamsImpl { + constructor(globalObject, constructorArgs, { doNotStripQMark = false }) { + let init = constructorArgs[0]; + this._list = []; + this._url = null; + + if (!doNotStripQMark && typeof init === "string" && init[0] === "?") { + init = init.slice(1); + } - return new FindOperators(this); + if (Array.isArray(init)) { + for (const pair of init) { + if (pair.length !== 2) { + throw new TypeError("Failed to construct 'URLSearchParams': parameter 1 sequence's element does not " + + "contain exactly two elements."); } + this._list.push([pair[0], pair[1]]); + } + } else if (typeof init === "object" && Object.getPrototypeOf(init) === null) { + for (const name of Object.keys(init)) { + const value = init[name]; + this._list.push([name, value]); + } + } else { + this._list = urlencoded.parseUrlencodedString(init); + } + } - /** - * 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]); - } + _updateSteps() { + if (this._url !== null) { + let query = urlencoded.serializeUrlencoded(this._list); + if (query === "") { + query = null; + } + this._url._url.query = query; + } + } - // 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, - }; + append(name, value) { + this._list.push([name, value]); + this._updateSteps(); + } - if (op[key].hint) { - operation.hint = op[key].hint; - } + delete(name) { + let i = 0; + while (i < this._list.length) { + if (this._list[i][0] === name) { + this._list.splice(i, 1); + } else { + i++; + } + } + this._updateSteps(); + } - 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: 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+" - ); - } + get(name) { + for (const tuple of this._list) { + if (tuple[0] === name) { + return tuple[1]; + } + } + return null; + } - operation.arrayFilters = op[key].arrayFilters; - } + getAll(name) { + const output = []; + for (const tuple of this._list) { + if (tuple[0] === name) { + output.push(tuple[1]); + } + } + return output; + } - return this.s.options.addToOperationsList(this, UPDATE, operation); - } + has(name) { + for (const tuple of this._list) { + if (tuple[0] === name) { + return true; + } + } + return false; + } - // 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]); - } + set(name, value) { + let found = false; + let i = 0; + while (i < this._list.length) { + if (this._list[i][0] === name) { + if (found) { + this._list.splice(i, 1); + } else { + found = true; + this._list[i][1] = value; + i++; + } + } else { + i++; + } + } + if (!found) { + this._list.push([name, value]); + } + this._updateSteps(); + } - // 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); - } + sort() { + this._list.sort((a, b) => { + if (a[0] < b[0]) { + return -1; + } + if (a[0] > b[0]) { + return 1; + } + return 0; + }); - // 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 - ); - } + this._updateSteps(); + } - if (op.insertMany) { - emitWarningOnce( - "bulk operation `insertMany` has been deprecated; use multiple `insertOne` ops instead" - ); - 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] - ); - } + [Symbol.iterator]() { + return this._list[Symbol.iterator](); + } - return; - } + toString() { + return urlencoded.serializeUrlencoded(this._list); + } +}; - // 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); - } +/***/ 9709: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * 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; - } +"use strict"; - const finalOptions = Object.assign({}, this.s.options, options); - if (typeof _writeConcern === "function") { - callback = _writeConcern; - } else if (_writeConcern && typeof _writeConcern === "object") { - this.s.writeConcern = _writeConcern; - } +const conversions = __nccwpck_require__(6362); +const utils = __nccwpck_require__(861); - if (this.s.executed) { - const executedError = toError("batch cannot be re-executed"); - return this._handleEarlyError(executedError, callback); - } +const Function = __nccwpck_require__(1931); +const newObjectInRealm = utils.newObjectInRealm; +const implSymbol = utils.implSymbol; +const ctorRegistrySymbol = utils.ctorRegistrySymbol; - // 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: finalOptions, callback }; - } +const interfaceName = "URLSearchParams"; - /** - * 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. - */ +exports.is = value => { + return utils.isObject(value) && utils.hasOwn(value, implSymbol) && value[implSymbol] instanceof Impl.implementation; +}; +exports.isImpl = value => { + return utils.isObject(value) && value instanceof Impl.implementation; +}; +exports.convert = (globalObject, value, { context = "The provided value" } = {}) => { + if (exports.is(value)) { + return utils.implForWrapper(value); + } + throw new globalObject.TypeError(`${context} is not of type 'URLSearchParams'.`); +}; + +exports.createDefaultIterator = (globalObject, target, kind) => { + const ctorRegistry = globalObject[ctorRegistrySymbol]; + const iteratorPrototype = ctorRegistry["URLSearchParams Iterator"]; + const iterator = Object.create(iteratorPrototype); + Object.defineProperty(iterator, utils.iterInternalSymbol, { + value: { target, kind, index: 0 }, + configurable: true + }); + return iterator; +}; + +function makeWrapper(globalObject, newTarget) { + let proto; + if (newTarget !== undefined) { + proto = newTarget.prototype; + } - /** - * 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {boolean} [options.fsync=false] **Deprecated** Specify a file sync write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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; - } + if (!utils.isObject(proto)) { + proto = globalObject[ctorRegistrySymbol]["URLSearchParams"].prototype; + } - options = ret.options; - callback = ret.callback; + return Object.create(proto); +} - return executeLegacyOperation(this.s.topology, executeCommands, [ - this, - options, - callback, - ]); - } +exports.create = (globalObject, constructorArgs, privateData) => { + const wrapper = makeWrapper(globalObject); + return exports.setup(wrapper, globalObject, constructorArgs, privateData); +}; - /** - * 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; - } +exports.createImpl = (globalObject, constructorArgs, privateData) => { + const wrapper = exports.create(globalObject, constructorArgs, privateData); + return utils.implForWrapper(wrapper); +}; - if (finalOptions.bypassDocumentValidation !== true) { - delete finalOptions.bypassDocumentValidation; - } +exports._internalSetup = (wrapper, globalObject) => {}; - // Set an operationIf if provided - if (this.operationId) { - config.resultHandler.operationId = this.operationId; - } +exports.setup = (wrapper, globalObject, constructorArgs = [], privateData = {}) => { + privateData.wrapper = wrapper; - // Serialize functions - if (this.s.options.serializeFunctions) { - finalOptions.serializeFunctions = true; - } + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: new Impl.implementation(globalObject, constructorArgs, privateData), + configurable: true + }); - // Ignore undefined - if (this.s.options.ignoreUndefined) { - finalOptions.ignoreUndefined = true; - } + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper; +}; - // Is the bypassDocumentValidation options specific - if (this.s.bypassDocumentValidation === true) { - finalOptions.bypassDocumentValidation = true; - } +exports.new = (globalObject, newTarget) => { + const wrapper = makeWrapper(globalObject, newTarget); - // Is the checkKeys option disabled - if (this.s.checkKeys === false) { - finalOptions.checkKeys = false; - } + exports._internalSetup(wrapper, globalObject); + Object.defineProperty(wrapper, implSymbol, { + value: Object.create(Impl.implementation.prototype), + configurable: true + }); - if (finalOptions.retryWrites) { - if (config.batch.batchType === UPDATE) { - finalOptions.retryWrites = - finalOptions.retryWrites && - !config.batch.operations.some((op) => op.multi); - } + wrapper[implSymbol][utils.wrapperSymbol] = wrapper; + if (Impl.init) { + Impl.init(wrapper[implSymbol]); + } + return wrapper[implSymbol]; +}; - if (config.batch.batchType === REMOVE) { - finalOptions.retryWrites = - finalOptions.retryWrites && - !config.batch.operations.some((op) => op.limit === 0); - } - } +const exposed = new Set(["Window", "Worker"]); - 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) - ); - } - } +exports.install = (globalObject, globalNames) => { + if (!globalNames.some(globalName => exposed.has(globalName))) { + return; + } - /** - * 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; - } + const ctorRegistry = utils.initCtorRegistry(globalObject); + class URLSearchParams { + constructor() { + const args = []; + { + let curArg = arguments[0]; + if (curArg !== undefined) { + if (utils.isObject(curArg)) { + if (curArg[Symbol.iterator] !== undefined) { + if (!utils.isObject(curArg)) { + throw new globalObject.TypeError( + "Failed to construct 'URLSearchParams': parameter 1" + " sequence" + " is not an iterable object." + ); + } else { + const V = []; + const tmp = curArg; + for (let nextItem of tmp) { + if (!utils.isObject(nextItem)) { + throw new globalObject.TypeError( + "Failed to construct 'URLSearchParams': parameter 1" + + " sequence" + + "'s element" + + " is not an iterable object." + ); + } else { + const V = []; + const tmp = nextItem; + for (let nextItem of tmp) { + nextItem = conversions["USVString"](nextItem, { + context: + "Failed to construct 'URLSearchParams': parameter 1" + + " sequence" + + "'s element" + + "'s element", + globals: globalObject + }); - if (writeResult.getWriteConcernError()) { - handleCallback( - callback, - new BulkWriteError( - toError(writeResult.getWriteConcernError()), - writeResult - ), - null - ); - return true; + V.push(nextItem); + } + nextItem = V; + } + + V.push(nextItem); + } + curArg = V; + } + } else { + if (!utils.isObject(curArg)) { + throw new globalObject.TypeError( + "Failed to construct 'URLSearchParams': parameter 1" + " record" + " is not an object." + ); + } else { + const result = Object.create(null); + for (const key of Reflect.ownKeys(curArg)) { + const desc = Object.getOwnPropertyDescriptor(curArg, key); + if (desc && desc.enumerable) { + let typedKey = key; + + typedKey = conversions["USVString"](typedKey, { + context: "Failed to construct 'URLSearchParams': parameter 1" + " record" + "'s key", + globals: globalObject + }); + + let typedValue = curArg[key]; + + typedValue = conversions["USVString"](typedValue, { + context: "Failed to construct 'URLSearchParams': parameter 1" + " record" + "'s value", + globals: globalObject + }); + + result[typedKey] = typedValue; + } + } + curArg = result; + } + } + } else { + curArg = conversions["USVString"](curArg, { + context: "Failed to construct 'URLSearchParams': parameter 1", + globals: globalObject + }); } + } else { + curArg = ""; } + args.push(curArg); } + return exports.setup(Object.create(new.target.prototype), globalObject, args); + } - Object.defineProperty(BulkOperationBase.prototype, "length", { - enumerable: true, - get: function () { - return this.s.currentIndex; - }, - }); + append(name, value) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError( + "'append' called on an object that is not a valid instance of URLSearchParams." + ); + } - // Exports symbols - module.exports = { - Batch, - BulkOperationBase, - bson, - INSERT: INSERT, - UPDATE: UPDATE, - REMOVE: REMOVE, - BulkWriteError, - BulkWriteResult, - }; + if (arguments.length < 2) { + throw new globalObject.TypeError( + `Failed to execute 'append' on 'URLSearchParams': 2 arguments required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'append' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + { + let curArg = arguments[1]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'append' on 'URLSearchParams': parameter 2", + globals: globalObject + }); + args.push(curArg); + } + return utils.tryWrapperForImpl(esValue[implSymbol].append(...args)); + } - /***/ - }, + delete(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError( + "'delete' called on an object that is not a valid instance of URLSearchParams." + ); + } - /***/ 5035: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const common = __nccwpck_require__(4239); - const BulkOperationBase = common.BulkOperationBase; - const Batch = common.Batch; - const bson = common.bson; - const utils = __nccwpck_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, + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to execute 'delete' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'delete' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + return utils.tryWrapperForImpl(esValue[implSymbol].delete(...args)); + } + + get(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'get' called on an object that is not a valid instance of URLSearchParams."); + } - // 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, + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to execute 'get' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'get' on 'URLSearchParams': parameter 1", + globals: globalObject }); + args.push(curArg); + } + return esValue[implSymbol].get(...args); + } - // 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 - ); + getAll(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError( + "'getAll' called on an object that is not a valid instance of URLSearchParams." + ); + } - // 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 - ); + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to execute 'getAll' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'getAll' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + return utils.tryWrapperForImpl(esValue[implSymbol].getAll(...args)); + } - const maxKeySize = bulkOperation.s.maxKeySize; + has(name) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'has' called on an object that is not a valid instance of URLSearchParams."); + } - // 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); + if (arguments.length < 1) { + throw new globalObject.TypeError( + `Failed to execute 'has' on 'URLSearchParams': 1 argument required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'has' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + return esValue[implSymbol].has(...args); + } - // Create a new batch - bulkOperation.s.currentBatch = new Batch( - docType, - bulkOperation.s.currentIndex - ); + set(name, value) { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'set' called on an object that is not a valid instance of URLSearchParams."); + } - // Reset the current size trackers - bulkOperation.s.currentBatchSize = 0; - bulkOperation.s.currentBatchSizeBytes = 0; - } + if (arguments.length < 2) { + throw new globalObject.TypeError( + `Failed to execute 'set' on 'URLSearchParams': 2 arguments required, but only ${arguments.length} present.` + ); + } + const args = []; + { + let curArg = arguments[0]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'set' on 'URLSearchParams': parameter 1", + globals: globalObject + }); + args.push(curArg); + } + { + let curArg = arguments[1]; + curArg = conversions["USVString"](curArg, { + context: "Failed to execute 'set' on 'URLSearchParams': parameter 2", + globals: globalObject + }); + args.push(curArg); + } + return utils.tryWrapperForImpl(esValue[implSymbol].set(...args)); + } - if (docType === common.INSERT) { - bulkOperation.s.bulkResult.insertedIds.push({ - index: bulkOperation.s.currentIndex, - _id: document._id, - }); - } + sort() { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError("'sort' called on an object that is not a valid instance of URLSearchParams."); + } - // We have an array of documents - if (Array.isArray(document)) { - throw toError("operation passed in cannot be an Array"); - } + return utils.tryWrapperForImpl(esValue[implSymbol].sort()); + } - bulkOperation.s.currentBatch.originalIndexes.push( - bulkOperation.s.currentIndex + toString() { + const esValue = this !== null && this !== undefined ? this : globalObject; + if (!exports.is(esValue)) { + throw new globalObject.TypeError( + "'toString' called on an object that is not a valid instance of URLSearchParams." ); - 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 }); + return esValue[implSymbol].toString(); + } - super(topology, collection, options, true); - } + keys() { + if (!exports.is(this)) { + throw new globalObject.TypeError("'keys' called on an object that is not a valid instance of URLSearchParams."); } + return exports.createDefaultIterator(globalObject, this, "key"); + } - /** - * Returns an unordered batch object - * @ignore - */ - function initializeOrderedBulkOp(topology, collection, options) { - return new OrderedBulkOperation(topology, collection, options); + values() { + if (!exports.is(this)) { + throw new globalObject.TypeError( + "'values' called on an object that is not a valid instance of URLSearchParams." + ); } + return exports.createDefaultIterator(globalObject, this, "value"); + } - initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; - module.exports = initializeOrderedBulkOp; - module.exports.Bulk = OrderedBulkOperation; + entries() { + if (!exports.is(this)) { + throw new globalObject.TypeError( + "'entries' called on an object that is not a valid instance of URLSearchParams." + ); + } + return exports.createDefaultIterator(globalObject, this, "key+value"); + } - /***/ - }, + forEach(callback) { + if (!exports.is(this)) { + throw new globalObject.TypeError( + "'forEach' called on an object that is not a valid instance of URLSearchParams." + ); + } + if (arguments.length < 1) { + throw new globalObject.TypeError( + "Failed to execute 'forEach' on 'iterable': 1 argument required, but only 0 present." + ); + } + callback = Function.convert(globalObject, callback, { + context: "Failed to execute 'forEach' on 'iterable': The callback provided as parameter 1" + }); + const thisArg = arguments[1]; + let pairs = Array.from(this[implSymbol]); + let i = 0; + while (i < pairs.length) { + const [key, value] = pairs[i].map(utils.tryWrapperForImpl); + callback.call(thisArg, value, key, this); + pairs = Array.from(this[implSymbol]); + i++; + } + } + } + Object.defineProperties(URLSearchParams.prototype, { + append: { enumerable: true }, + delete: { enumerable: true }, + get: { enumerable: true }, + getAll: { enumerable: true }, + has: { enumerable: true }, + set: { enumerable: true }, + sort: { enumerable: true }, + toString: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true }, + forEach: { enumerable: true }, + [Symbol.toStringTag]: { value: "URLSearchParams", configurable: true }, + [Symbol.iterator]: { value: URLSearchParams.prototype.entries, configurable: true, writable: true } + }); + ctorRegistry[interfaceName] = URLSearchParams; + + ctorRegistry["URLSearchParams Iterator"] = Object.create(ctorRegistry["%IteratorPrototype%"], { + [Symbol.toStringTag]: { + configurable: true, + value: "URLSearchParams Iterator" + } + }); + utils.define(ctorRegistry["URLSearchParams Iterator"], { + next() { + const internal = this && this[utils.iterInternalSymbol]; + if (!internal) { + throw new globalObject.TypeError("next() called on a value that is not a URLSearchParams iterator object"); + } - /***/ 325: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const common = __nccwpck_require__(4239); - const BulkOperationBase = common.BulkOperationBase; - const Batch = common.Batch; - const bson = common.bson; - const utils = __nccwpck_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, + const { target, kind, index } = internal; + const values = Array.from(target[implSymbol]); + const len = values.length; + if (index >= len) { + return newObjectInRealm(globalObject, { value: undefined, done: true }); + } - // 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 pair = values[index]; + internal.index = index + 1; + return newObjectInRealm(globalObject, utils.iteratorResult(pair.map(utils.tryWrapperForImpl), kind)); + } + }); - const maxKeySize = bulkOperation.s.maxKeySize; + Object.defineProperty(globalObject, interfaceName, { + configurable: true, + writable: true, + value: URLSearchParams + }); +}; - // 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 Impl = __nccwpck_require__(643); - // 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"); - } +/***/ 8279: +/***/ ((module) => { - bulkOperation.s.currentBatch.operations.push(document); - bulkOperation.s.currentBatch.originalIndexes.push( - bulkOperation.s.currentIndex - ); - bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1; +"use strict"; - // 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; - } +const utf8Encoder = new TextEncoder(); +const utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true }); - // Update current batch size - bulkOperation.s.currentBatch.size += 1; - bulkOperation.s.currentBatch.sizeBytes += maxKeySize + bsonSize; +function utf8Encode(string) { + return utf8Encoder.encode(string); +} - // Return bulkOperation - return bulkOperation; - } +function utf8DecodeWithoutBOM(bytes) { + return utf8Decoder.decode(bytes); +} - /** - * 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 }); +module.exports = { + utf8Encode, + utf8DecodeWithoutBOM +}; - super(topology, collection, options, false); - } - handleWriteError(callback, writeResult) { - if (this.s.batches.length) { - return false; - } +/***/ }), - return super.handleWriteError(callback, writeResult); - } - } +/***/ 5143: +/***/ ((module) => { - /** - * Returns an unordered batch object - * @ignore - */ - function initializeUnorderedBulkOp(topology, collection, options) { - return new UnorderedBulkOperation(topology, collection, options); - } +"use strict"; - initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; - module.exports = initializeUnorderedBulkOp; - module.exports.Bulk = UnorderedBulkOperation; - /***/ - }, +// Note that we take code points as JS numbers, not JS strings. - /***/ 1117: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Denque = __nccwpck_require__(2342); - const EventEmitter = __nccwpck_require__(8614); - const isResumableError = __nccwpck_require__(9386).isResumableError; - const MongoError = __nccwpck_require__(3994).MongoError; - const Cursor = __nccwpck_require__(7159); - const relayEvents = __nccwpck_require__(1178).relayEvents; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const maybePromise = __nccwpck_require__(1371).maybePromise; - const now = __nccwpck_require__(1371).now; - const calculateDurationInMs = - __nccwpck_require__(1371).calculateDurationInMs; - const AggregateOperation = __nccwpck_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"), - }; +function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; +} - /** - * @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 = __nccwpck_require__(5193); - const Db = __nccwpck_require__(6662); - const MongoClient = __nccwpck_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" - ); - } +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} - this.promiseLibrary = parent.s.promiseLibrary; - if (!this.options.readPreference && parent.s.readPreference) { - this.options.readPreference = parent.s.readPreference; - } +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} - this[kResumeQueue] = new Denque(); +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} - // Create contained Change Stream cursor - this.cursor = createChangeStreamCursor(this, options); +module.exports = { + isASCIIDigit, + isASCIIAlpha, + isASCIIAlphanumeric, + isASCIIHex +}; - 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"); - } - }); - } +/***/ 8453: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * @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; - } +"use strict"; - /** - * 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); - }); - }); - } +const { isASCIIHex } = __nccwpck_require__(5143); +const { utf8Encode } = __nccwpck_require__(8279); - /** - * 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); - }); - }); - }); - } +function p(char) { + return char.codePointAt(0); +} - /** - * Is the change stream closed - * @method ChangeStream.prototype.isClosed - * @return {boolean} - */ - isClosed() { - return this.closed || (this.cursor && this.cursor.isClosed()); - } +// https://url.spec.whatwg.org/#percent-encode +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = `0${hex}`; + } - /** - * 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(); + return `%${hex}`; +} + +// https://url.spec.whatwg.org/#percent-decode +function percentDecodeBytes(input) { + const output = new Uint8Array(input.byteLength); + let outputIndex = 0; + for (let i = 0; i < input.byteLength; ++i) { + const byte = input[i]; + if (byte !== 0x25) { + output[outputIndex++] = byte; + } else if (byte === 0x25 && (!isASCIIHex(input[i + 1]) || !isASCIIHex(input[i + 2]))) { + output[outputIndex++] = byte; + } else { + const bytePoint = parseInt(String.fromCodePoint(input[i + 1], input[i + 2]), 16); + output[outputIndex++] = bytePoint; + i += 2; + } + } - // flag the change stream as explicitly closed - this.closed = true; + return output.slice(0, outputIndex); +} + +// https://url.spec.whatwg.org/#string-percent-decode +function percentDecodeString(input) { + const bytes = utf8Encode(input); + return percentDecodeBytes(bytes); +} + +// https://url.spec.whatwg.org/#c0-control-percent-encode-set +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +// https://url.spec.whatwg.org/#fragment-percent-encode-set +const extraFragmentPercentEncodeSet = new Set([p(" "), p("\""), p("<"), p(">"), p("`")]); +function isFragmentPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraFragmentPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#query-percent-encode-set +const extraQueryPercentEncodeSet = new Set([p(" "), p("\""), p("#"), p("<"), p(">")]); +function isQueryPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraQueryPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#special-query-percent-encode-set +function isSpecialQueryPercentEncode(c) { + return isQueryPercentEncode(c) || c === p("'"); +} + +// https://url.spec.whatwg.org/#path-percent-encode-set +const extraPathPercentEncodeSet = new Set([p("?"), p("`"), p("{"), p("}")]); +function isPathPercentEncode(c) { + return isQueryPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#userinfo-percent-encode-set +const extraUserinfoPercentEncodeSet = + new Set([p("/"), p(":"), p(";"), p("="), p("@"), p("["), p("\\"), p("]"), p("^"), p("|")]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#component-percent-encode-set +const extraComponentPercentEncodeSet = new Set([p("$"), p("%"), p("&"), p("+"), p(",")]); +function isComponentPercentEncode(c) { + return isUserinfoPercentEncode(c) || extraComponentPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#application-x-www-form-urlencoded-percent-encode-set +const extraURLEncodedPercentEncodeSet = new Set([p("!"), p("'"), p("("), p(")"), p("~")]); +function isURLEncodedPercentEncode(c) { + return isComponentPercentEncode(c) || extraURLEncodedPercentEncodeSet.has(c); +} + +// https://url.spec.whatwg.org/#code-point-percent-encode-after-encoding +// https://url.spec.whatwg.org/#utf-8-percent-encode +// Assuming encoding is always utf-8 allows us to trim one of the logic branches. TODO: support encoding. +// The "-Internal" variant here has code points as JS strings. The external version used by other files has code points +// as JS numbers, like the rest of the codebase. +function utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate) { + const bytes = utf8Encode(codePoint); + let output = ""; + for (const byte of bytes) { + // Our percentEncodePredicate operates on bytes, not code points, so this is slightly different from the spec. + if (!percentEncodePredicate(byte)) { + output += String.fromCharCode(byte); + } else { + output += percentEncode(byte); + } + } - if (!this.cursor) return cb(); + return output; +} + +function utf8PercentEncodeCodePoint(codePoint, percentEncodePredicate) { + return utf8PercentEncodeCodePointInternal(String.fromCodePoint(codePoint), percentEncodePredicate); +} + +// https://url.spec.whatwg.org/#string-percent-encode-after-encoding +// https://url.spec.whatwg.org/#string-utf-8-percent-encode +function utf8PercentEncodeString(input, percentEncodePredicate, spaceAsPlus = false) { + let output = ""; + for (const codePoint of input) { + if (spaceAsPlus && codePoint === " ") { + output += "+"; + } else { + output += utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate); + } + } + return output; +} + +module.exports = { + isC0ControlPercentEncode, + isFragmentPercentEncode, + isQueryPercentEncode, + isSpecialQueryPercentEncode, + isPathPercentEncode, + isUserinfoPercentEncode, + isURLEncodedPercentEncode, + percentDecodeString, + percentDecodeBytes, + utf8PercentEncodeString, + utf8PercentEncodeCodePoint +}; + + +/***/ }), + +/***/ 8934: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const tr46 = __nccwpck_require__(1504); + +const infra = __nccwpck_require__(5143); +const { utf8DecodeWithoutBOM } = __nccwpck_require__(8279); +const { percentDecodeString, utf8PercentEncodeCodePoint, utf8PercentEncodeString, isC0ControlPercentEncode, + isFragmentPercentEncode, isQueryPercentEncode, isSpecialQueryPercentEncode, isPathPercentEncode, + isUserinfoPercentEncode } = __nccwpck_require__(8453); + +function p(char) { + return char.codePointAt(0); +} + +const specialSchemes = { + ftp: 21, + file: null, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +const failure = Symbol("failure"); + +function countSymbols(str) { + return [...str].length; +} + +function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return infra.isASCIIAlpha(cp1) && (cp2 === p(":") || cp2 === p("|")); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && infra.isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u) !== -1; +} + +function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function isNotSpecial(url) { + return !isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function parseIPv4Number(input) { + if (input === "") { + return failure; + } - // Tidy up the existing cursor - const cursor = this.cursor; + let R = 10; - return cursor.close((err) => { - ["data", "close", "end", "error"].forEach((event) => - cursor.removeAllListeners(event) - ); - this.cursor = undefined; + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } - return cb(err); - }); - }); - } + if (input === "") { + return 0; + } - /** - * 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); - } + let regex = /[^0-7]/u; + if (R === 10) { + regex = /[^0-9]/u; + } + if (R === 16) { + regex = /[^0-9A-Fa-f]/u; + } - /** - * 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); - } + if (regex.test(input)) { + return failure; + } - /** - * 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); - } + return parseInt(input, R); +} - /** - * 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(); - } +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } - /** - * This method will cause the readable stream to resume emitting data events. - * @return {null} - */ - resume() { - return this.cursor.resume(); - } + if (parts.length > 4) { + return failure; + } + + const numbers = []; + for (const part of parts) { + const n = parseIPv4Number(part); + if (n === failure) { + return failure; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= 256 ** (5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * 256 ** (3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = `.${output}`; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = Array.from(input, c => c.codePointAt(0)); + + if (input[pointer] === p(":")) { + if (input[pointer + 1] !== p(":")) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === p(":")) { + if (compress !== null) { + return failure; } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } - class ChangeStreamCursor extends Cursor { - constructor(topology, operation, options) { - super(topology, operation, options); + let value = 0; + let length = 0; - options = options || {}; - this._resumeToken = null; - this.startAtOperationTime = options.startAtOperationTime; + while (length < 4 && infra.isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } - if (options.startAfter) { - this.resumeToken = options.startAfter; - } else if (options.resumeAfter) { - this.resumeToken = options.resumeAfter; - } - } + if (input[pointer] === p(".")) { + if (length === 0) { + return failure; + } - set resumeToken(token) { - this._resumeToken = token; - this.emit("resumeTokenChanged", token); - } + pointer -= length; - get resumeToken() { - return this._resumeToken; - } + if (pieceIndex > 6) { + return failure; + } - get resumeOptions() { - const result = {}; - for (const optionName of CURSOR_OPTIONS) { - if (this.options[optionName]) - result[optionName] = this.options[optionName]; - } + let numbersSeen = 0; - if (this.resumeToken || this.startAtOperationTime) { - ["resumeAfter", "startAfter", "startAtOperationTime"].forEach( - (key) => delete result[key] - ); + while (input[pointer] !== undefined) { + let ipv4Piece = null; - 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; - } + if (numbersSeen > 0) { + if (input[pointer] === p(".") && numbersSeen < 4) { + ++pointer; + } else { + return failure; } + } - return result; + if (!infra.isASCIIDigit(input[pointer])) { + return failure; } - cacheResumeToken(resumeToken) { - if ( - this.bufferedCount() === 0 && - this.cursorState.postBatchResumeToken - ) { - this.resumeToken = this.cursorState.postBatchResumeToken; + while (infra.isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; } else { - this.resumeToken = resumeToken; + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; } - this.hasReceived = true; + ++pointer; } - _processBatch(batchName, response) { - const cursor = response.cursor; - if (cursor.postBatchResumeToken) { - this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken; + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; - if (cursor[batchName].length === 0) { - this.resumeToken = cursor.postBatchResumeToken; - } - } + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; } + } - _initializeCursor(callback) { - super._initializeCursor((err, result) => { - if (err || result == null) { - callback(err, result); - return; - } + if (numbersSeen !== 4) { + return failure; + } - const response = result.documents[0]; + break; + } else if (input[pointer] === p(":")) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } - if ( - this.startAtOperationTime == null && - this.resumeAfter == null && - this.startAfter == null && - maxWireVersion(this.server) >= 7 - ) { - this.startAtOperationTime = response.operationTime; - } + address[pieceIndex] = value; + ++pieceIndex; + } - this._processBatch("firstBatch", response); + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } - this.emit("init", result); - this.emit("response"); - callback(err, result); - }); - } + return address; +} - _getMore(callback) { - super._getMore((err, response) => { - if (err) { - callback(err); - return; - } +function serializeIPv6(address) { + let output = ""; + const compress = findLongestZeroSequence(address); + let ignore0 = false; - this._processBatch("nextBatch", response); + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } - this.emit("more", response); - this.emit("response"); - callback(err, response); - }); - } - } + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } - /** - * @event ChangeStreamCursor#response - * internal event DO NOT USE - * @ignore - */ + output += address[pieceIndex].toString(16); - // 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; - } + if (pieceIndex !== 7) { + output += ":"; + } + } - const pipeline = [{ $changeStream: changeStreamStageOptions }].concat( - self.pipeline - ); - const cursorOptions = applyKnownOptions({}, options, CURSOR_OPTIONS); + return output; +} - const changeStreamCursor = new ChangeStreamCursor( - self.topology, - new AggregateOperation(self.parent, pipeline, options), - cursorOptions - ); +function parseHost(input, isNotSpecialArg = false) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } - relayEvents(changeStreamCursor, self, [ - "resumeTokenChanged", - "end", - "close", - ]); + return parseIPv6(input.substring(1, input.length - 1)); + } - /** - * 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); - }); - } + if (isNotSpecialArg) { + return parseOpaqueHost(input); + } - /** - * Change stream close event - * - * @event ChangeStream#close - * @type {null} - */ + const domain = utf8DecodeWithoutBOM(percentDecodeString(input)); + const asciiDomain = domainToASCII(domain); + if (asciiDomain === failure) { + return failure; + } - /** - * Change stream end event - * - * @event ChangeStream#end - * @type {null} - */ + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } - /** - * Emitted each time the change stream stores a new resume token. - * - * @event ChangeStream#resumeTokenChanged - * @type {ResumeToken} - */ + if (endsInANumber(asciiDomain)) { + return parseIPv4(asciiDomain); + } - /** - * Fired when the stream encounters an error. - * - * @event ChangeStream#error - * @type {Error} - */ - changeStreamCursor.on("error", function (error) { - processError(self, error); - }); + return asciiDomain; +} - if (self.pipeDestinations) { - const cursorStream = changeStreamCursor.stream(self.streamOptions); - for (let pipeDestination of self.pipeDestinations) { - cursorStream.pipe(pipeDestination); - } - } +function endsInANumber(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length === 1) { + return false; + } + parts.pop(); + } - return changeStreamCursor; - } + const last = parts[parts.length - 1]; + if (parseIPv4Number(last) !== failure) { + return true; + } - function applyKnownOptions(target, source, optionNames) { - optionNames.forEach((name) => { - if (source[name]) { - target[name] = source[name]; - } - }); + if (/^[0-9]+$/u.test(last)) { + return true; + } - return target; - } + return false; +} - // 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(); - } +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } - const start = options.start || now(); - const timeout = options.timeout || SELECTION_TIMEOUT; - const readPreference = options.readPreference; - if (topology.isConnected({ readPreference })) { - return callback(); - } + return utf8PercentEncodeString(input, isC0ControlPercentEncode); +} - if (calculateDurationInMs(start) > timeout) { - return callback(new MongoError("Timed out waiting for connection")); - } +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; - waitForTopologyConnected(topology, options, callback); - }, 500); // this is an arbitrary wait time to allow SDAM to transition + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; } - function processNewChange(changeStream, change, callback) { - const cursor = changeStream.cursor; + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } - // a null change means the cursor has been notified, implicitly closing the change stream - if (change == null) { - changeStream.closed = true; - } + // if trailing zeros + if (currLen > maxLen) { + return currStart; + } - if (changeStream.closed) { - if (callback) callback(new MongoError("ChangeStream is closed")); - return; - } + return maxIdx; +} - if (change && !change._id) { - const noResumeTokenError = new Error( - "A change stream document has been received that lacks a resume token (_id)." - ); +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } - if (!callback) return changeStream.emit("error", noResumeTokenError); - return callback(noResumeTokenError); - } + // IPv6 serializer + if (host instanceof Array) { + return `[${serializeIPv6(host)}]`; + } - // cache the resume token - cursor.cacheResumeToken(change._id); + return host; +} + +function domainToASCII(domain, beStrict = false) { + const result = tr46.toASCII(domain, { + checkBidi: true, + checkHyphens: false, + checkJoiners: true, + useSTD3ASCIIRules: beStrict, + verifyDNSLength: beStrict + }); + if (result === null || result === "") { + return failure; + } + return result; +} - // 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; +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/ug, ""); +} - // Return the change - if (!callback) return changeStream.emit("change", change); - return callback(undefined, change); - } +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/ug, ""); +} - function processError(changeStream, error, callback) { - const topology = changeStream.topology; - const cursor = changeStream.cursor; +function shortenPath(url) { + const { path } = url; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } - // If the change stream has been closed explictly, do not process error. - if (changeStream.closed) { - if (callback) callback(new MongoError("ChangeStream is closed")); - return; - } + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || hasAnOpaquePath(url) || url.scheme === "file"; +} + +function hasAnOpaquePath(url) { + return typeof url.path === "string"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/u.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null + }; - // if the resume succeeds, continue with the new cursor - function resumeWithCursor(newCursor) { - changeStream.cursor = newCursor; - processResumeQueue(changeStream); - } + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } - // 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; - } + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; - if (cursor && isResumableError(error, maxWireVersion(cursor.server))) { - changeStream.cursor = undefined; + this.state = stateOverride || "scheme start"; - // stop listening to all events from old cursor - ["data", "close", "end", "error"].forEach((event) => - cursor.removeAllListeners(event) - ); + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; - // close internal cursor, ignore errors - cursor.close(); + this.input = Array.from(this.input, c => c.codePointAt(0)); - 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 - ); + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); - // attempt to continue in emitter mode - if (!callback) return resumeWithCursor(newCursor); + // exec state machine + const ret = this[`parse ${this.state}`](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (infra.isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } - // 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; - } + return true; +}; - if (!callback) return changeStream.emit("error", error); - return callback(error); +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (infra.isASCIIAlphanumeric(c) || c === p("+") || c === p("-") || c === p(".")) { + this.buffer += cStr.toLowerCase(); + } else if (c === p(":")) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; } - /** - * 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; - } + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } - // no cursor, queue callback until topology reconnects - changeStream[kResumeQueue].push(callback); + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; } - /** - * 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); - } + if (this.url.scheme === "file" && this.url.host === "") { + return false; + } + } + this.url.scheme = this.buffer; + if (this.stateOverride) { + if (this.url.port === defaultPort(this.url.scheme)) { + this.url.port = null; } + return false; + } + this.buffer = ""; + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== p("/") || this.input[this.pointer + 2] !== p("/")) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === p("/")) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.path = ""; + this.state = "opaque path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } - /** - * 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. - */ + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (hasAnOpaquePath(this.base) && c !== p("#"))) { + return failure; + } else if (hasAnOpaquePath(this.base) && c === p("#")) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path; + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } - module.exports = ChangeStream; + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === p("/") && this.input[this.pointer + 1] === p("/")) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } - /***/ - }, + return true; +}; - /***/ 9820: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const EventEmitter = __nccwpck_require__(8614); - const MessageStream = __nccwpck_require__(2425); - const MongoError = __nccwpck_require__(3111).MongoError; - const MongoNetworkError = __nccwpck_require__(3111).MongoNetworkError; - const MongoNetworkTimeoutError = - __nccwpck_require__(3111).MongoNetworkTimeoutError; - const MongoWriteConcernError = - __nccwpck_require__(3111).MongoWriteConcernError; - const CommandResult = __nccwpck_require__(2337); - const StreamDescription = __nccwpck_require__(6292).StreamDescription; - const wp = __nccwpck_require__(9206); - const apm = __nccwpck_require__(9815); - const updateSessionFromResponse = - __nccwpck_require__(5474).updateSessionFromResponse; - const uuidV4 = __nccwpck_require__(1178).uuidV4; - const now = __nccwpck_require__(1371).now; - const calculateDurationInMs = - __nccwpck_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 - : 0; - 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; - } +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === p("/")) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } - // 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 */ - }); + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (c === p("/")) { + this.state = "relative slash"; + } else if (isSpecial(this.url) && c === p("\\")) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + if (c === p("?")) { + this.url.query = ""; + this.state = "query"; + } else if (c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (!isNaN(c)) { + this.url.query = null; + this.url.path.pop(); + this.state = "path"; + --this.pointer; + } + } - this[kMessageStream].on("error", (error) => - this.handleIssue({ destroy: error }) - ); - stream.on("close", () => this.handleIssue({ isClose: true })); - stream.on("timeout", () => - this.handleIssue({ isTimeout: true, destroy: true }) - ); + return true; +}; - // hook the message stream up to the passed in stream - stream.pipe(this[kMessageStream]); - this[kMessageStream].pipe(stream); - } +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === p("/") || c === p("\\"))) { + if (c === p("\\")) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === p("/")) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } - get description() { - return this[kDescription]; - } + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === p("/") && this.input[this.pointer + 1] === p("/")) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } - get ismaster() { - return this[kIsMaster]; - } + return true; +}; - // the `connect` method stores the result of the handshake ismaster on the connection - set ismaster(response) { - this[kDescription].receiveResponse(response); +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== p("/") && c !== p("\\")) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } - // TODO: remove this, and only use the `StreamDescription` in the future - this[kIsMaster] = response; - } + return true; +}; - get generation() { - return this[kGeneration] || 0; - } +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === p("@")) { + this.parseError = true; + if (this.atFlag) { + this.buffer = `%40${this.buffer}`; + } + this.atFlag = true; - get idleTime() { - return calculateDurationInMs(this[kLastUseTime]); - } + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); - get clusterTime() { - return this[kClusterTime]; - } + if (codePoint === p(":") && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = utf8PercentEncodeCodePoint(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || + (isSpecial(this.url) && c === p("\\"))) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } - get stream() { - return this[kStream]; - } + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === p(":") && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } - markAvailable() { - this[kLastUseTime] = now(); - } + if (this.stateOverride === "hostname") { + return false; + } - /** - * @param {{ isTimeout?: boolean; isClose?: boolean; destroy?: boolean | Error }} issue - */ - handleIssue(issue) { - if (this.closed) { - return; - } + const host = parseHost(this.buffer, isNotSpecial(this.url)); + if (host === failure) { + return failure; + } - if (issue.destroy) { - this[kStream].destroy( - typeof issue.destroy === "boolean" ? undefined : issue.destroy - ); - } + this.url.host = host; + this.buffer = ""; + this.state = "port"; + } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || + (isSpecial(this.url) && c === p("\\"))) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } - this.closed = true; + const host = parseHost(this.buffer, isNotSpecial(this.url)); + if (host === failure) { + return failure; + } - for (const idAndOp of this[kQueue]) { - const op = idAndOp[1]; - if (issue.isTimeout) { - op.cb( - new MongoNetworkTimeoutError( - `connection ${this.id} to ${this.address} timed out`, - { - beforeHandshake: this.ismaster == null, - } - ) - ); - } else if (issue.isClose) { - op.cb( - new MongoNetworkError( - `connection ${this.id} to ${this.address} closed` - ) - ); - } else { - op.cb( - typeof issue.destroy === "boolean" ? undefined : issue.destroy - ); - } - } + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === p("[")) { + this.arrFlag = true; + } else if (c === p("]")) { + this.arrFlag = false; + } + this.buffer += cStr; + } - this[kQueue].clear(); - this.emit("close"); - } + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (infra.isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === p("/") || c === p("?") || c === p("#") || + (isSpecial(this.url) && c === p("\\")) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > 2 ** 16 - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } - destroy(options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } + return true; +}; - options = Object.assign({ force: false }, options); - if (this[kStream] == null || this.destroyed) { - this.destroyed = true; - if (typeof callback === "function") { - callback(); - } +const fileOtherwiseCodePoints = new Set([p("/"), p("\\"), p("?"), p("#")]); - return; - } +function startsWithWindowsDriveLetter(input, pointer) { + const length = input.length - pointer; + return length >= 2 && + isWindowsDriveLetterCodePoints(input[pointer], input[pointer + 1]) && + (length === 2 || fileOtherwiseCodePoints.has(input[pointer + 2])); +} - if (options.force) { - this[kStream].destroy(); - this.destroyed = true; - if (typeof callback === "function") { - callback(); - } +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + this.url.host = ""; - return; - } + if (c === p("/") || c === p("\\")) { + if (c === p("\\")) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + if (c === p("?")) { + this.url.query = ""; + this.state = "query"; + } else if (c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (!isNaN(c)) { + this.url.query = null; + if (!startsWithWindowsDriveLetter(this.input, this.pointer)) { + shortenPath(this.url); + } else { + this.parseError = true; + this.url.path = []; + } - this[kStream].end((err) => { - this.destroyed = true; - if (typeof callback === "function") { - callback(err); - } - }); - } + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } - // Wire protocol methods - command(ns, cmd, options, callback) { - wp.command(makeServerTrampoline(this), ns, cmd, options, callback); - } + return true; +}; - query(ns, cmd, cursorState, options, callback) { - wp.query( - makeServerTrampoline(this), - ns, - cmd, - cursorState, - options, - callback - ); - } +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === p("/") || c === p("\\")) { + if (c === p("\\")) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (!startsWithWindowsDriveLetter(this.input, this.pointer) && + isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } + this.url.host = this.base.host; + } + this.state = "path"; + --this.pointer; + } - getMore(ns, cursorState, batchSize, options, callback) { - wp.getMore( - makeServerTrampoline(this), - ns, - cursorState, - batchSize, - options, - callback - ); - } + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === p("/") || c === p("\\") || c === p("?") || c === p("#")) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isNotSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; - killCursors(ns, cursorState, callback) { - wp.killCursors(makeServerTrampoline(this), ns, cursorState, callback); - } + if (this.stateOverride) { + return false; + } - insert(ns, ops, options, callback) { - wp.insert(makeServerTrampoline(this), ns, ops, options, callback); - } + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } - update(ns, ops, options, callback) { - wp.update(makeServerTrampoline(this), ns, ops, options, callback); - } + return true; +}; - remove(ns, ops, options, callback) { - wp.remove(makeServerTrampoline(this), ns, ops, options, callback); - } - } +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === p("\\")) { + this.parseError = true; + } + this.state = "path"; - /// 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 (c !== p("/") && c !== p("\\")) { + --this.pointer; + } + } else if (!this.stateOverride && c === p("?")) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== p("/")) { + --this.pointer; + } + } else if (this.stateOverride && this.url.host === null) { + this.url.path.push(""); + } - if (connection[kAutoEncrypter]) { - server.autoEncrypter = connection[kAutoEncrypter]; - } + return true; +}; - return server; +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === p("/") || (isSpecial(this.url) && c === p("\\")) || + (!this.stateOverride && (c === p("?") || c === p("#")))) { + if (isSpecial(this.url) && c === p("\\")) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== p("/") && !(isSpecial(this.url) && c === p("\\"))) { + this.url.path.push(""); } + } else if (isSingleDot(this.buffer) && c !== p("/") && + !(isSpecial(this.url) && c === p("\\"))) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + this.buffer = `${this.buffer[0]}:`; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (c === p("?")) { + this.url.query = ""; + this.state = "query"; + } + if (c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. - 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; - } + if (c === p("%") && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } - const operationDescription = conn[kQueue].get(message.responseTo); - const callback = operationDescription.cb; + this.buffer += utf8PercentEncodeCodePoint(c, isPathPercentEncode); + } - // 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); - } + return true; +}; + +URLStateMachine.prototype["parse opaque path"] = function parseOpaquePath(c) { + if (c === p("?")) { + this.url.query = ""; + this.state = "query"; + } else if (c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== p("%")) { + this.parseError = true; + } - try { - // Pass in the entire description because it has BSON parsing options - message.parse(operationDescription); - } catch (err) { - callback(new MongoError(err)); - return; - } + if (c === p("%") && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } - if (message.documents[0]) { - const document = message.documents[0]; - const session = operationDescription.session; - if (session) { - updateSessionFromResponse(session, document); - } + if (!isNaN(c)) { + this.url.path += utf8PercentEncodeCodePoint(c, isC0ControlPercentEncode); + } + } - if (document.$clusterTime) { - conn[kClusterTime] = document.$clusterTime; - conn.emit("clusterTimeReceived", document.$clusterTime); - } + return true; +}; - if (operationDescription.command) { - if (document.writeConcernError) { - callback( - new MongoWriteConcernError( - document.writeConcernError, - document - ) - ); - return; - } +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } - if ( - document.ok === 0 || - document.$err || - document.errmsg || - document.code - ) { - callback(new MongoError(document)); - return; - } - } - } + if ((!this.stateOverride && c === p("#")) || isNaN(c)) { + const queryPercentEncodePredicate = isSpecial(this.url) ? isSpecialQueryPercentEncode : isQueryPercentEncode; + this.url.query += utf8PercentEncodeString(this.buffer, queryPercentEncodePredicate); - // NODE-2382: reenable in our glorious non-leaky abstraction future - // callback(null, operationDescription.fullResult ? message : message.documents[0]); + this.buffer = ""; - callback( - undefined, - new CommandResult( - operationDescription.fullResult ? message : message.documents[0], - conn, - message - ) - ); - }; - } + if (c === p("#")) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else if (!isNaN(c)) { + // TODO: If c is not a URL code point and not "%", parse error. - function streamIdentifier(stream) { - if (typeof stream.address === "function") { - return `${stream.remoteAddress}:${stream.remotePort}`; - } + if (c === p("%") && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } - return uuidV4().toString("hex"); - } + this.buffer += cStr; + } - // 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; - } + return true; +}; - 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, - bsonRegExp: - typeof options.bsonRegExp === "boolean" - ? options.bsonRegExp - : false, - raw: typeof options.raw === "boolean" ? options.raw : false, - }; +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (!isNaN(c)) { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === p("%") && + (!infra.isASCIIHex(this.input[this.pointer + 1]) || + !infra.isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } - if (this[kDescription] && this[kDescription].compressor) { - operationDescription.agreedCompressor = this[kDescription].compressor; + this.url.fragment += utf8PercentEncodeCodePoint(c, isFragmentPercentEncode); + } - if (this[kDescription].zlibCompressionLevel) { - operationDescription.zlibCompressionLevel = - this[kDescription].zlibCompressionLevel; - } - } + return true; +}; - if (typeof options.socketTimeout === "number") { - operationDescription.socketTimeoutOverride = true; - this[kStream].setTimeout(options.socketTimeout); - } +function serializeURL(url, excludeFragment) { + let output = `${url.scheme}:`; + if (url.host !== null) { + output += "//"; - // if command monitoring is enabled we need to modify the callback here - if (this.monitorCommands) { - this.emit( - "commandStarted", - new apm.CommandStartedEvent(this, command) - ); + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += `:${url.password}`; + } + output += "@"; + } - 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 - ) - ); - } - } + output += serializeHost(url.host); - if (typeof callback === "function") { - callback(err, reply); - } - }; - } + if (url.port !== null) { + output += `:${url.port}`; + } + } - if (!operationDescription.noResponse) { - this[kQueue].set( - operationDescription.requestId, - operationDescription - ); - } + if (url.host === null && !hasAnOpaquePath(url) && url.path.length > 1 && url.path[0] === "") { + output += "/."; + } + output += serializePath(url); - try { - this[kMessageStream].writeCommand(command, operationDescription); - } catch (e) { - if (!operationDescription.noResponse) { - this[kQueue].delete(operationDescription.requestId); - operationDescription.cb(e); - return; - } - } + if (url.query !== null) { + output += `?${url.query}`; + } - if (operationDescription.noResponse) { - operationDescription.cb(); - } - } + if (!excludeFragment && url.fragment !== null) { + output += `#${url.fragment}`; + } - module.exports = { - Connection, - }; + return output; +} - /***/ - }, +function serializeOrigin(tuple) { + let result = `${tuple.scheme}://`; + result += serializeHost(tuple.host); - /***/ 2529: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Denque = __nccwpck_require__(2342); - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const Logger = __nccwpck_require__(104); - const makeCounter = __nccwpck_require__(1371).makeCounter; - const MongoError = __nccwpck_require__(3111).MongoError; - const Connection = __nccwpck_require__(9820).Connection; - const eachAsync = __nccwpck_require__(1178).eachAsync; - const connect = __nccwpck_require__(6573); - const relayEvents = __nccwpck_require__(1178).relayEvents; - - const errors = __nccwpck_require__(2926); - const PoolClosedError = errors.PoolClosedError; - const WaitQueueTimeoutError = errors.WaitQueueTimeoutError; - - const events = __nccwpck_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 (Object.prototype.hasOwnProperty.call(options, key)) { - obj[key] = options[key]; - } + if (tuple.port !== null) { + result += `:${tuple.port}`; + } - 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, - }); + return result; +} - if (options.minSize > options.maxSize) { - throw new TypeError( - "Connection pool minimum size must not be greater than maxiumum pool size" - ); - } +function serializePath(url) { + if (hasAnOpaquePath(url)) { + return url.path; + } - 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); - }); - } + let output = ""; + for (const segment of url.path) { + output += `/${segment}`; + } + return output; +} - get address() { - return `${this.options.host}:${this.options.port}`; - } +module.exports.serializeURL = serializeURL; - get generation() { - return this[kGeneration]; - } +module.exports.serializePath = serializePath; - get totalConnectionCount() { - return ( - this[kConnections].length + - (this.options.maxPoolSize - this[kPermits]) - ); - } +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(serializePath(url))); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // The spec says: + // > Unfortunate as it is, this is left as an exercise to the reader. When in doubt, return a new opaque origin. + // Browsers tested so far: + // - Chrome says "file://", but treats file: URLs as cross-origin for most (all?) purposes; see e.g. + // https://bugs.chromium.org/p/chromium/issues/detail?id=37586 + // - Firefox says "null", but treats file: URLs as same-origin sometimes based on directory stuff; see + // https://developer.mozilla.org/en-US/docs/Archive/Misc_top_level/Same-origin_policy_for_file:_URIs + return "null"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; - get availableConnectionCount() { - return this[kConnections].length; - } +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } - get waitQueueSize() { - return this[kWaitQueue].length; - } + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return null; + } - /** - * 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) - ); + return usm.url; +}; - if (this.closed) { - this.emit( - "connectionCheckOutFailed", - new ConnectionCheckOutFailedEvent(this, "poolClosed") - ); - callback(new PoolClosedError(this)); - return; - } +module.exports.setTheUsername = function (url, username) { + url.username = utf8PercentEncodeString(username, isUserinfoPercentEncode); +}; - const waitQueueMember = { callback }; +module.exports.setThePassword = function (url, password) { + url.password = utf8PercentEncodeString(password, isUserinfoPercentEncode); +}; - const pool = this; - const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS; - if (waitQueueTimeoutMS) { - waitQueueMember.timer = setTimeout(() => { - waitQueueMember[kCancelled] = true; - waitQueueMember.timer = undefined; +module.exports.serializeHost = serializeHost; - pool.emit( - "connectionCheckOutFailed", - new ConnectionCheckOutFailedEvent(pool, "timeout") - ); - waitQueueMember.callback(new WaitQueueTimeoutError(pool)); - }, waitQueueTimeoutMS); - } +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; - this[kWaitQueue].push(waitQueueMember); - process.nextTick(() => processWaitQueue(this)); - } +module.exports.hasAnOpaquePath = hasAnOpaquePath; - /** - * 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); +module.exports.serializeInteger = function (integer) { + return String(integer); +}; - if (!willDestroy) { - connection.markAvailable(); - this[kConnections].push(connection); - } +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } - this.emit( - "connectionCheckedIn", - new ConnectionCheckedInEvent(this, connection) - ); + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; - if (willDestroy) { - const reason = connection.closed - ? "error" - : poolClosed - ? "poolClosed" - : "stale"; - destroyConnection(this, connection, reason); - } - process.nextTick(() => 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) - ); - } +/***/ 2934: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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; - } +"use strict"; - options = Object.assign({ force: false }, options); - if (this.closed) { - return callback(); - } +const { utf8Encode, utf8DecodeWithoutBOM } = __nccwpck_require__(8279); +const { percentDecodeBytes, utf8PercentEncodeString, isURLEncodedPercentEncode } = __nccwpck_require__(8453); - // immediately cancel any in-flight connections - this[kCancellationToken].emit("cancel"); +function p(char) { + return char.codePointAt(0); +} - // 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") - ); - } - } +// https://url.spec.whatwg.org/#concept-urlencoded-parser +function parseUrlencoded(input) { + const sequences = strictlySplitByteSequence(input, p("&")); + const output = []; + for (const bytes of sequences) { + if (bytes.length === 0) { + continue; + } - // clear the min pool size timer - if (this[kMinPoolSizeTimer]) { - clearTimeout(this[kMinPoolSizeTimer]); - } + let name, value; + const indexOfEqual = bytes.indexOf(p("=")); - // end the connection counter - if (typeof this[kConnectionCounter].return === "function") { - this[kConnectionCounter].return(); - } + if (indexOfEqual >= 0) { + name = bytes.slice(0, indexOfEqual); + value = bytes.slice(indexOfEqual + 1); + } else { + name = bytes; + value = new Uint8Array(0); + } - // mark the pool as closed immediately - this.closed = true; + name = replaceByteInByteSequence(name, 0x2B, 0x20); + value = replaceByteInByteSequence(value, 0x2B, 0x20); - 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); - } - ); - } + const nameString = utf8DecodeWithoutBOM(percentDecodeBytes(name)); + const valueString = utf8DecodeWithoutBOM(percentDecodeBytes(value)); - /** - * 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` + output.push([nameString, valueString]); + } + return output; +} + +// https://url.spec.whatwg.org/#concept-urlencoded-string-parser +function parseUrlencodedString(input) { + return parseUrlencoded(utf8Encode(input)); +} + +// https://url.spec.whatwg.org/#concept-urlencoded-serializer +function serializeUrlencoded(tuples, encodingOverride = undefined) { + let encoding = "utf-8"; + if (encodingOverride !== undefined) { + // TODO "get the output encoding", i.e. handle encoding labels vs. names. + encoding = encodingOverride; + } - fn(err, conn, (fnErr, result) => { - if (typeof callback === "function") { - if (fnErr) { - callback(fnErr); - } else { - callback(undefined, result); - } - } + let output = ""; + for (const [i, tuple] of tuples.entries()) { + // TODO: handle encoding override - if (conn) { - this.checkIn(conn); - } - }); - }); - } + const name = utf8PercentEncodeString(tuple[0], isURLEncodedPercentEncode, true); + + let value = tuple[1]; + if (tuple.length > 2 && tuple[2] !== undefined) { + if (tuple[2] === "hidden" && name === "_charset_") { + value = encoding; + } else if (tuple[2] === "file") { + // value is a File object + value = value.name; } + } - function ensureMinPoolSize(pool) { - if (pool.closed || pool.options.minPoolSize === 0) { - return; - } + value = utf8PercentEncodeString(value, isURLEncodedPercentEncode, true); - const minPoolSize = pool.options.minPoolSize; - for (let i = pool.totalConnectionCount; i < minPoolSize; ++i) { - createConnection(pool); - } + if (i !== 0) { + output += "&"; + } + output += `${name}=${value}`; + } + return output; +} + +function strictlySplitByteSequence(buf, cp) { + const list = []; + let last = 0; + let i = buf.indexOf(cp); + while (i >= 0) { + list.push(buf.slice(last, i)); + last = i + 1; + i = buf.indexOf(cp, last); + } + if (last !== buf.length) { + list.push(buf.slice(last)); + } + return list; +} + +function replaceByteInByteSequence(buf, from, to) { + let i = buf.indexOf(from); + while (i >= 0) { + buf[i] = to; + i = buf.indexOf(from, i + 1); + } + return buf; +} - pool[kMinPoolSizeTimer] = setTimeout(() => ensureMinPoolSize(pool), 10); - } +module.exports = { + parseUrlencodedString, + serializeUrlencoded +}; - 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 - ); +/***/ 861: +/***/ ((module, exports) => { - 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); - } +"use strict"; - return; - } - // The pool might have closed since we started trying to create a connection - if (pool.closed) { - connection.destroy({ force: true }); - return; - } +// Returns "Type(value) is Object" in ES terminology. +function isObject(value) { + return (typeof value === "object" && value !== null) || typeof value === "function"; +} - // forward all events from the connection to the pool - relayEvents(connection, pool, [ - "commandStarted", - "commandFailed", - "commandSucceeded", - "clusterTimeReceived", - ]); - - pool.emit( - "connectionCreated", - new ConnectionCreatedEvent(pool, connection) - ); +const hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty); - connection.markAvailable(); - pool.emit( - "connectionReady", - new ConnectionReadyEvent(pool, connection) - ); +// Like `Object.assign`, but using `[[GetOwnProperty]]` and `[[DefineOwnProperty]]` +// instead of `[[Get]]` and `[[Set]]` and only allowing objects +function define(target, source) { + for (const key of Reflect.ownKeys(source)) { + const descriptor = Reflect.getOwnPropertyDescriptor(source, key); + if (descriptor && !Reflect.defineProperty(target, key, descriptor)) { + throw new TypeError(`Cannot redefine property: ${String(key)}`); + } + } +} + +function newObjectInRealm(globalObject, object) { + const ctorRegistry = initCtorRegistry(globalObject); + return Object.defineProperties( + Object.create(ctorRegistry["%Object.prototype%"]), + Object.getOwnPropertyDescriptors(object) + ); +} + +const wrapperSymbol = Symbol("wrapper"); +const implSymbol = Symbol("impl"); +const sameObjectCaches = Symbol("SameObject caches"); +const ctorRegistrySymbol = Symbol.for("[webidl2js] constructor registry"); + +const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype); + +function initCtorRegistry(globalObject) { + if (hasOwn(globalObject, ctorRegistrySymbol)) { + return globalObject[ctorRegistrySymbol]; + } - // if a callback has been provided, check out the connection immediately - if (typeof callback === "function") { - callback(undefined, connection); - return; - } + const ctorRegistry = Object.create(null); - // otherwise add it to the pool for later acquisition, and try to process the wait queue - pool[kConnections].push(connection); - process.nextTick(() => 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 - process.nextTick(() => 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; - } + // In addition to registering all the WebIDL2JS-generated types in the constructor registry, + // we also register a few intrinsics that we make use of in generated code, since they are not + // easy to grab from the globalObject variable. + ctorRegistry["%Object.prototype%"] = globalObject.Object.prototype; + ctorRegistry["%IteratorPrototype%"] = Object.getPrototypeOf( + Object.getPrototypeOf(new globalObject.Array()[Symbol.iterator]()) + ); - 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; - } + try { + ctorRegistry["%AsyncIteratorPrototype%"] = Object.getPrototypeOf( + Object.getPrototypeOf( + globalObject.eval("(async function* () {})").prototype + ) + ); + } catch { + ctorRegistry["%AsyncIteratorPrototype%"] = AsyncIteratorPrototype; + } - const reason = connection.closed - ? "error" - : isStale - ? "stale" - : "idle"; - destroyConnection(pool, connection, reason); - } + globalObject[ctorRegistrySymbol] = ctorRegistry; + return ctorRegistry; +} - 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 || waitQueueMember[kCancelled]) { - if (err == null) { - pool[kConnections].push(connection); - } +function getSameObject(wrapper, prop, creator) { + if (!wrapper[sameObjectCaches]) { + wrapper[sameObjectCaches] = Object.create(null); + } - return; - } + if (prop in wrapper[sameObjectCaches]) { + return wrapper[sameObjectCaches][prop]; + } - if (err) { - pool.emit( - "connectionCheckOutFailed", - new ConnectionCheckOutFailedEvent(pool, err) - ); - } else { - pool.emit( - "connectionCheckedOut", - new ConnectionCheckedOutEvent(pool, connection) - ); - } + wrapper[sameObjectCaches][prop] = creator(); + return wrapper[sameObjectCaches][prop]; +} - clearTimeout(waitQueueMember.timer); - waitQueueMember.callback(err, connection); - }); +function wrapperForImpl(impl) { + return impl ? impl[wrapperSymbol] : null; +} - return; - } - } +function implForWrapper(wrapper) { + return wrapper ? wrapper[implSymbol] : null; +} - /** - * 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, - }; +function tryWrapperForImpl(impl) { + const wrapper = wrapperForImpl(impl); + return wrapper ? wrapper : impl; +} - /***/ - }, +function tryImplForWrapper(wrapper) { + const impl = implForWrapper(wrapper); + return impl ? impl : wrapper; +} - /***/ 2926: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const MongoError = __nccwpck_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; - } - } +const iterInternalSymbol = Symbol("internal"); - /** - * 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; +function isArrayIndexPropName(P) { + if (typeof P !== "string") { + return false; + } + const i = P >>> 0; + if (i === 2 ** 32 - 1) { + return false; + } + const s = `${i}`; + if (P !== s) { + return false; + } + return true; +} + +const byteLengthGetter = + Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; +function isArrayBuffer(value) { + try { + byteLengthGetter.call(value); + return true; + } catch (e) { + return false; + } +} + +function iteratorResult([key, value], kind) { + let result; + switch (kind) { + case "key": + result = key; + break; + case "value": + result = value; + break; + case "key+value": + result = [key, value]; + break; + } + return { value: result, done: false }; +} + +const supportsPropertyIndex = Symbol("supports property index"); +const supportedPropertyIndices = Symbol("supported property indices"); +const supportsPropertyName = Symbol("supports property name"); +const supportedPropertyNames = Symbol("supported property names"); +const indexedGet = Symbol("indexed property get"); +const indexedSetNew = Symbol("indexed property set new"); +const indexedSetExisting = Symbol("indexed property set existing"); +const namedGet = Symbol("named property get"); +const namedSetNew = Symbol("named property set new"); +const namedSetExisting = Symbol("named property set existing"); +const namedDelete = Symbol("named property delete"); + +const asyncIteratorNext = Symbol("async iterator get the next iteration result"); +const asyncIteratorReturn = Symbol("async iterator return steps"); +const asyncIteratorInit = Symbol("async iterator initialization steps"); +const asyncIteratorEOI = Symbol("async iterator end of iteration"); + +module.exports = exports = { + isObject, + hasOwn, + define, + newObjectInRealm, + wrapperSymbol, + implSymbol, + getSameObject, + ctorRegistrySymbol, + initCtorRegistry, + wrapperForImpl, + implForWrapper, + tryWrapperForImpl, + tryImplForWrapper, + iterInternalSymbol, + isArrayBuffer, + isArrayIndexPropName, + supportsPropertyIndex, + supportedPropertyIndices, + supportsPropertyName, + supportedPropertyNames, + indexedGet, + indexedSetNew, + indexedSetExisting, + namedGet, + namedSetNew, + namedSetExisting, + namedDelete, + asyncIteratorNext, + asyncIteratorReturn, + asyncIteratorInit, + asyncIteratorEOI, + iteratorResult +}; + + +/***/ }), + +/***/ 7488: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const URL = __nccwpck_require__(1851); +const URLSearchParams = __nccwpck_require__(9709); + +exports.URL = URL; +exports.URLSearchParams = URLSearchParams; + + +/***/ }), + +/***/ 3238: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Admin = void 0; +const add_user_1 = __nccwpck_require__(7057); +const remove_user_1 = __nccwpck_require__(1969); +const validate_collection_1 = __nccwpck_require__(9263); +const list_databases_1 = __nccwpck_require__(9929); +const execute_operation_1 = __nccwpck_require__(2548); +const run_command_1 = __nccwpck_require__(1363); +const utils_1 = __nccwpck_require__(1371); +/** + * The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @public + * + * @example + * ```js + * 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) { + * expect(err).to.not.exist; + * test.ok(dbs.databases.length > 0); + * client.close(); + * }); + * }); + * ``` + */ +class Admin { + /** + * Create a new Admin instance + * @internal + */ + constructor(db) { + this.s = { db }; + } + command(command, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = Object.assign({ dbName: 'admin' }, options); + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this.s.db), new run_command_1.RunCommandOperation(this.s.db, command, options), callback); + } + buildInfo(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.command({ buildinfo: 1 }, options, callback); + } + serverInfo(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.command({ buildinfo: 1 }, options, callback); + } + serverStatus(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.command({ serverStatus: 1 }, options, callback); + } + ping(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.command({ ping: 1 }, options, callback); + } + addUser(username, password, options, callback) { + if (typeof password === 'function') { + (callback = password), (password = undefined), (options = {}); } - } - - 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; + else if (typeof password !== 'string') { + if (typeof options === 'function') { + (callback = options), (options = password), (password = undefined); + } + else { + (options = password), (callback = undefined), (password = undefined); + } } - } - - /** - * 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; + else { + if (typeof options === 'function') + (callback = options), (options = {}); } - } - - /** - * An event published when a connection pool is closed - */ - class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool) { - super(pool); + options = Object.assign({ dbName: 'admin' }, options); + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this.s.db), new add_user_1.AddUserOperation(this.s.db, username, password, options), callback); + } + removeUser(username, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = Object.assign({ dbName: 'admin' }, options); + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this.s.db), new remove_user_1.RemoveUserOperation(this.s.db, username, options), callback); + } + validateCollection(collectionName, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this.s.db), new validate_collection_1.ValidateCollectionOperation(this, collectionName, options), callback); + } + listDatabases(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this.s.db), new list_databases_1.ListDatabasesOperation(this.s.db, options), callback); + } + replSetGetStatus(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.command({ replSetGetStatus: 1 }, options, callback); + } +} +exports.Admin = Admin; +//# sourceMappingURL=admin.js.map + +/***/ }), + +/***/ 5578: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveBSONOptions = exports.pluckBSONSerializeOptions = exports.Map = exports.BSONSymbol = exports.BSONRegExp = exports.DBRef = exports.Double = exports.Int32 = exports.Decimal128 = exports.MaxKey = exports.MinKey = exports.Code = exports.Timestamp = exports.ObjectId = exports.Binary = exports.Long = exports.calculateObjectSize = exports.serialize = exports.deserialize = void 0; +// eslint-disable-next-line @typescript-eslint/no-var-requires +let BSON = __nccwpck_require__(1960); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + BSON = __nccwpck_require__(9845); +} +catch { } // eslint-disable-line +/** @internal */ +exports.deserialize = BSON.deserialize; +/** @internal */ +exports.serialize = BSON.serialize; +/** @internal */ +exports.calculateObjectSize = BSON.calculateObjectSize; +var bson_1 = __nccwpck_require__(1960); +Object.defineProperty(exports, "Long", ({ enumerable: true, get: function () { return bson_1.Long; } })); +Object.defineProperty(exports, "Binary", ({ enumerable: true, get: function () { return bson_1.Binary; } })); +Object.defineProperty(exports, "ObjectId", ({ enumerable: true, get: function () { return bson_1.ObjectId; } })); +Object.defineProperty(exports, "Timestamp", ({ enumerable: true, get: function () { return bson_1.Timestamp; } })); +Object.defineProperty(exports, "Code", ({ enumerable: true, get: function () { return bson_1.Code; } })); +Object.defineProperty(exports, "MinKey", ({ enumerable: true, get: function () { return bson_1.MinKey; } })); +Object.defineProperty(exports, "MaxKey", ({ enumerable: true, get: function () { return bson_1.MaxKey; } })); +Object.defineProperty(exports, "Decimal128", ({ enumerable: true, get: function () { return bson_1.Decimal128; } })); +Object.defineProperty(exports, "Int32", ({ enumerable: true, get: function () { return bson_1.Int32; } })); +Object.defineProperty(exports, "Double", ({ enumerable: true, get: function () { return bson_1.Double; } })); +Object.defineProperty(exports, "DBRef", ({ enumerable: true, get: function () { return bson_1.DBRef; } })); +Object.defineProperty(exports, "BSONRegExp", ({ enumerable: true, get: function () { return bson_1.BSONRegExp; } })); +Object.defineProperty(exports, "BSONSymbol", ({ enumerable: true, get: function () { return bson_1.BSONSymbol; } })); +Object.defineProperty(exports, "Map", ({ enumerable: true, get: function () { return bson_1.Map; } })); +function pluckBSONSerializeOptions(options) { + const { fieldsAsRaw, promoteValues, promoteBuffers, promoteLongs, serializeFunctions, ignoreUndefined, bsonRegExp, raw } = options; + return { + fieldsAsRaw, + promoteValues, + promoteBuffers, + promoteLongs, + serializeFunctions, + ignoreUndefined, + bsonRegExp, + raw + }; +} +exports.pluckBSONSerializeOptions = pluckBSONSerializeOptions; +/** + * Merge the given BSONSerializeOptions, preferring options over the parent's options, and + * substituting defaults for values not set. + * + * @internal + */ +function resolveBSONOptions(options, parent) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; + const parentOptions = parent === null || parent === void 0 ? void 0 : parent.bsonOptions; + return { + raw: (_b = (_a = options === null || options === void 0 ? void 0 : options.raw) !== null && _a !== void 0 ? _a : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.raw) !== null && _b !== void 0 ? _b : false, + promoteLongs: (_d = (_c = options === null || options === void 0 ? void 0 : options.promoteLongs) !== null && _c !== void 0 ? _c : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.promoteLongs) !== null && _d !== void 0 ? _d : true, + promoteValues: (_f = (_e = options === null || options === void 0 ? void 0 : options.promoteValues) !== null && _e !== void 0 ? _e : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.promoteValues) !== null && _f !== void 0 ? _f : true, + promoteBuffers: (_h = (_g = options === null || options === void 0 ? void 0 : options.promoteBuffers) !== null && _g !== void 0 ? _g : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.promoteBuffers) !== null && _h !== void 0 ? _h : false, + ignoreUndefined: (_k = (_j = options === null || options === void 0 ? void 0 : options.ignoreUndefined) !== null && _j !== void 0 ? _j : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.ignoreUndefined) !== null && _k !== void 0 ? _k : false, + bsonRegExp: (_m = (_l = options === null || options === void 0 ? void 0 : options.bsonRegExp) !== null && _l !== void 0 ? _l : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.bsonRegExp) !== null && _m !== void 0 ? _m : false, + serializeFunctions: (_p = (_o = options === null || options === void 0 ? void 0 : options.serializeFunctions) !== null && _o !== void 0 ? _o : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.serializeFunctions) !== null && _p !== void 0 ? _p : false, + fieldsAsRaw: (_r = (_q = options === null || options === void 0 ? void 0 : options.fieldsAsRaw) !== null && _q !== void 0 ? _q : parentOptions === null || parentOptions === void 0 ? void 0 : parentOptions.fieldsAsRaw) !== null && _r !== void 0 ? _r : {} + }; +} +exports.resolveBSONOptions = resolveBSONOptions; +//# sourceMappingURL=bson.js.map + +/***/ }), + +/***/ 4239: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BulkOperationBase = exports.FindOperators = exports.MongoBulkWriteError = exports.mergeBatchResults = exports.WriteError = exports.WriteConcernError = exports.BulkWriteResult = exports.Batch = exports.BatchType = void 0; +const promise_provider_1 = __nccwpck_require__(2725); +const bson_1 = __nccwpck_require__(5578); +const error_1 = __nccwpck_require__(9386); +const utils_1 = __nccwpck_require__(1371); +const execute_operation_1 = __nccwpck_require__(2548); +const insert_1 = __nccwpck_require__(4179); +const update_1 = __nccwpck_require__(1134); +const delete_1 = __nccwpck_require__(5831); +const write_concern_1 = __nccwpck_require__(2481); +/** @internal */ +const kServerError = Symbol('serverError'); +/** @public */ +exports.BatchType = Object.freeze({ + INSERT: 1, + UPDATE: 2, + DELETE: 3 +}); +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * + * @public + */ +class Batch { + constructor(batchType, originalZeroIndex) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; + } +} +exports.Batch = Batch; +/** + * @public + * The result of a bulk write. + */ +class BulkWriteResult { + /** + * Create a new BulkWriteResult instance + * @internal + */ + constructor(bulkResult) { + this.result = bulkResult; + } + /** Number of documents inserted. */ + get insertedCount() { + var _a; + return (_a = this.result.nInserted) !== null && _a !== void 0 ? _a : 0; + } + /** Number of documents matched for update. */ + get matchedCount() { + var _a; + return (_a = this.result.nMatched) !== null && _a !== void 0 ? _a : 0; + } + /** Number of documents modified. */ + get modifiedCount() { + var _a; + return (_a = this.result.nModified) !== null && _a !== void 0 ? _a : 0; + } + /** Number of documents deleted. */ + get deletedCount() { + var _a; + return (_a = this.result.nRemoved) !== null && _a !== void 0 ? _a : 0; + } + /** Number of documents upserted. */ + get upsertedCount() { + var _a; + return (_a = this.result.upserted.length) !== null && _a !== void 0 ? _a : 0; + } + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds() { + var _a; + const upserted = {}; + for (const doc of (_a = this.result.upserted) !== null && _a !== void 0 ? _a : []) { + upserted[doc.index] = doc._id; + } + return upserted; + } + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds() { + var _a; + const inserted = {}; + for (const doc of (_a = this.result.insertedIds) !== null && _a !== void 0 ? _a : []) { + inserted[doc.index] = doc._id; + } + return inserted; + } + /** Evaluates to true if the bulk operation correctly executes */ + get ok() { + return this.result.ok; + } + /** The number of inserted documents */ + get nInserted() { + return this.result.nInserted; + } + /** Number of upserted documents */ + get nUpserted() { + return this.result.nUpserted; + } + /** Number of matched documents */ + get nMatched() { + return this.result.nMatched; + } + /** Number of documents updated physically on disk */ + get nModified() { + return this.result.nModified; + } + /** Number of removed documents */ + get nRemoved() { + return this.result.nRemoved; + } + /** Returns an array of all inserted ids */ + getInsertedIds() { + return this.result.insertedIds; + } + /** Returns an array of all upserted ids */ + getUpsertedIds() { + return this.result.upserted; + } + /** Returns the upserted id at the given index */ + getUpsertedIdAt(index) { + return this.result.upserted[index]; + } + /** Returns raw internal result */ + getRawResponse() { + return this.result; + } + /** Returns true if the bulk operation contains a write error */ + hasWriteErrors() { + return this.result.writeErrors.length > 0; + } + /** Returns the number of write errors off the bulk operation */ + getWriteErrorCount() { + return this.result.writeErrors.length; + } + /** Returns a specific write error object */ + getWriteErrorAt(index) { + if (index < this.result.writeErrors.length) { + return this.result.writeErrors[index]; } - } - - /** - * 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; + } + /** Retrieve all write errors */ + getWriteErrors() { + return this.result.writeErrors; + } + /** Retrieve lastOp if available */ + getLastOp() { + return this.result.opTime; + } + /** Retrieve the write concern error if one exists */ + getWriteConcernError() { + if (this.result.writeConcernErrors.length === 0) { + return; } - } - - /** - * 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; + else if (this.result.writeConcernErrors.length === 1) { + // Return the error + return this.result.writeConcernErrors[0]; } - } - - /** - * 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"; + 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: Something better + if (i === 0) + errmsg = errmsg + ' and '; + } + return new WriteConcernError({ errmsg, code: error_1.MONGODB_ERROR_CODES.WriteConcernFailed }); } - } - - /** - * An event published when a request to check a connection out begins - */ - class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool) { - super(pool); + } + toJSON() { + return this.result; + } + toString() { + return `BulkWriteResult(${this.toJSON()})`; + } + isOk() { + return this.result.ok === 1; + } +} +exports.BulkWriteResult = BulkWriteResult; +/** + * An error representing a failure by the server to apply the requested write concern to the bulk operation. + * @public + * @category Error + */ +class WriteConcernError { + constructor(error) { + this[kServerError] = error; + } + /** Write concern error code. */ + get code() { + return this[kServerError].code; + } + /** Write concern error message. */ + get errmsg() { + return this[kServerError].errmsg; + } + /** Write concern error info. */ + get errInfo() { + return this[kServerError].errInfo; + } + /** @deprecated The `err` prop that contained a MongoServerError has been deprecated. */ + get err() { + return this[kServerError]; + } + toJSON() { + return this[kServerError]; + } + toString() { + return `WriteConcernError(${this.errmsg})`; + } +} +exports.WriteConcernError = WriteConcernError; +/** + * An error that occurred during a BulkWrite on the server. + * @public + * @category Error + */ +class WriteError { + constructor(err) { + this.err = err; + } + /** WriteError code. */ + get code() { + return this.err.code; + } + /** WriteError original bulk operation index. */ + get index() { + return this.err.index; + } + /** WriteError message. */ + get errmsg() { + return this.err.errmsg; + } + /** WriteError details. */ + get errInfo() { + return this.err.errInfo; + } + /** Returns the underlying operation that caused the error */ + getOperation() { + return this.err.op; + } + toJSON() { + return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; + } + toString() { + return `WriteError(${JSON.stringify(this.toJSON())})`; + } +} +exports.WriteError = WriteError; +/** Converts the number to a Long or returns it. */ +function longOrConvert(value) { + return typeof value === 'number' ? bson_1.Long.fromNumber(value) : value; +} +/** Merges results into shared data structure */ +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; + } + 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, + errInfo: result.errInfo, + op: batch.operations[0] + }; + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } + else if (result.ok === 0 && bulkResult.ok === 0) { + return; + } + // The server write command specification states that lastOp is an optional + // mongod only field that has a type of timestamp. Across various scarce specs + // where opTime is mentioned, it is an "opaque" object that can have a "ts" and + // "t" field with Timestamp and Long as their types respectively. + // The "lastOp" field of the bulk write result is never mentioned in the driver + // specifications or the bulk write spec, so we should probably just keep its + // value consistent since it seems to vary. + // See: https://github.com/mongodb/specifications/blob/master/source/driver-bulk-update.rst#results-object + if (result.opTime || result.lastOp) { + let opTime = result.lastOp || result.opTime; + // If the opTime is a Timestamp, convert it to a consistent format to be + // able to compare easily. Converting to the object from a timestamp is + // much more straightforward than the other direction. + if (opTime._bsontype === 'Timestamp') { + opTime = { ts: opTime, t: bson_1.Long.ZERO }; + } + // If there's no lastOp, just set it. + if (!bulkResult.opTime) { + bulkResult.opTime = opTime; } - } - - /** - * 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; + else { + // First compare the ts values and set if the opTimeTS value is greater. + const lastOpTS = longOrConvert(bulkResult.opTime.ts); + const opTimeTS = longOrConvert(opTime.ts); + if (opTimeTS.greaterThan(lastOpTS)) { + bulkResult.opTime = opTime; + } + else if (opTimeTS.equals(lastOpTS)) { + // If the ts values are equal, then compare using the t values. + const lastOpT = longOrConvert(bulkResult.opTime.t); + const opTimeT = longOrConvert(opTime.t); + if (opTimeT.greaterThan(lastOpT)) { + bulkResult.opTime = opTime; + } + } } - } - - /** - * 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; + } + // If we have an insert Batch type + if (isInsertBatch(batch) && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + // If we have an insert Batch type + if (isDeleteBatch(batch) && 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 + }); } - } - - /** - * 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; + } + else if (result.upserted) { + nUpserted = 1; + bulkResult.upserted.push({ + index: batch.originalZeroIndex, + _id: result.upserted + }); + } + // If we have an update Batch type + if (isUpdateBatch(batch) && 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; } - } - - /** - * An event published when a connection pool is cleared - */ - class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool) { - super(pool); + else { + bulkResult.nModified = 0; } - } - - 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, - __nccwpck_require__ - ) => { - "use strict"; - - const Duplex = __nccwpck_require__(2413).Duplex; - const BufferList = __nccwpck_require__(336); - const MongoParseError = __nccwpck_require__(3111).MongoParseError; - const decompress = __nccwpck_require__(7793).decompress; - const Response = __nccwpck_require__(9814).Response; - const BinMsg = __nccwpck_require__(8988).BinMsg; - const MongoError = __nccwpck_require__(3111).MongoError; - const OP_COMPRESSED = __nccwpck_require__(7272).opcodes.OP_COMPRESSED; - const OP_MSG = __nccwpck_require__(7272).opcodes.OP_MSG; - const MESSAGE_HEADER_SIZE = __nccwpck_require__(7272).MESSAGE_HEADER_SIZE; - const COMPRESSION_DETAILS_SIZE = - __nccwpck_require__(7272).COMPRESSION_DETAILS_SIZE; - const opcodes = __nccwpck_require__(7272).opcodes; - const compress = __nccwpck_require__(7793).compress; - const compressorIDs = __nccwpck_require__(7793).compressorIDs; - const uncompressibleCommands = - __nccwpck_require__(7793).uncompressibleCommands; - const Msg = __nccwpck_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; + } + 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, + errInfo: result.writeErrors[i].errInfo, + op: batch.operations[result.writeErrors[i].index] + }; + bulkResult.writeErrors.push(new WriteError(writeError)); } - - writeCommand(command, operationDescription) { - // TODO: 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); + } + if (result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} +exports.mergeBatchResults = mergeBatchResults; +function executeCommands(bulkOperation, options, callback) { + if (bulkOperation.s.batches.length === 0) { + return callback(undefined, 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, return early + if (err && 'message' in err && !(err instanceof error_1.MongoWriteConcernError)) { + return callback(new MongoBulkWriteError(err, new BulkWriteResult(bulkOperation.s.bulkResult))); + } + if (err instanceof error_1.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 callback(undefined, writeResult); + } + if (bulkOperation.handleWriteError(callback, writeResult)) 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, - ]) - ); - } - ); + // Execute the next command in line + executeCommands(bulkOperation, options, callback); + } + const finalOptions = (0, utils_1.resolveOptions)(bulkOperation, { + ...options, + ordered: bulkOperation.isOrdered + }); + if (finalOptions.bypassDocumentValidation !== true) { + delete finalOptions.bypassDocumentValidation; + } + // Set an operationIf if provided + if (bulkOperation.operationId) { + resultHandler.operationId = bulkOperation.operationId; + } + // Is the bypassDocumentValidation options specific + if (bulkOperation.s.bypassDocumentValidation === true) { + finalOptions.bypassDocumentValidation = true; + } + // Is the checkKeys option disabled + if (bulkOperation.s.checkKeys === false) { + finalOptions.checkKeys = false; + } + if (finalOptions.retryWrites) { + if (isUpdateBatch(batch)) { + finalOptions.retryWrites = finalOptions.retryWrites && !batch.operations.some(op => op.multi); } - } - - // 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; + if (isDeleteBatch(batch)) { + finalOptions.retryWrites = + finalOptions.retryWrites && !batch.operations.some(op => op.limit === 0); } - - const sizeOfMessage = buffer.readInt32LE(0); - if (sizeOfMessage < 0) { - callback( - new MongoParseError(`Invalid message size: ${sizeOfMessage}`) - ); - return; + } + try { + if (isInsertBatch(batch)) { + (0, execute_operation_1.executeOperation)(bulkOperation.s.topology, new insert_1.InsertOperation(bulkOperation.s.namespace, batch.operations, finalOptions), resultHandler); } - - if (sizeOfMessage > stream.maxBsonMessageSize) { - callback( - new MongoParseError( - `Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}` - ) - ); - return; + else if (isUpdateBatch(batch)) { + (0, execute_operation_1.executeOperation)(bulkOperation.s.topology, new update_1.UpdateOperation(bulkOperation.s.namespace, batch.operations, finalOptions), resultHandler); } - - if (sizeOfMessage > buffer.length) { - callback(); - return; + else if (isDeleteBatch(batch)) { + (0, execute_operation_1.executeOperation)(bulkOperation.s.topology, new delete_1.DeleteOperation(bulkOperation.s.namespace, batch.operations, finalOptions), resultHandler); } - - 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; + } + catch (err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + mergeBatchResults(batch, bulkOperation.s.bulkResult, err, undefined); + callback(); + } +} +function handleMongoWriteConcernError(batch, bulkResult, err, callback) { + var _a, _b; + mergeBatchResults(batch, bulkResult, undefined, err.result); + callback(new MongoBulkWriteError({ + message: (_a = err.result) === null || _a === void 0 ? void 0 : _a.writeConcernError.errmsg, + code: (_b = err.result) === null || _b === void 0 ? void 0 : _b.writeConcernError.result + }, new BulkWriteResult(bulkResult))); +} +/** + * An error indicating an unsuccessful Bulk Write + * @public + * @category Error + */ +class MongoBulkWriteError extends error_1.MongoServerError { + /** Creates a new MongoBulkWriteError */ + constructor(error, result) { + var _a; + super(error); + this.writeErrors = []; + if (error instanceof WriteConcernError) + this.err = error; + else if (!(error instanceof Error)) { + this.message = error.message; + this.code = error.code; + this.writeErrors = (_a = error.writeErrors) !== null && _a !== void 0 ? _a : []; } - - 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, - __nccwpck_require__ - ) => { - "use strict"; - - const parseServerType = __nccwpck_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]; - } + this.result = result; + Object.assign(this, error); + } + get name() { + return 'MongoBulkWriteError'; + } + /** Number of documents inserted. */ + get insertedCount() { + return this.result.insertedCount; + } + /** Number of documents matched for update. */ + get matchedCount() { + return this.result.matchedCount; + } + /** Number of documents modified. */ + get modifiedCount() { + return this.result.modifiedCount; + } + /** Number of documents deleted. */ + get deletedCount() { + return this.result.deletedCount; + } + /** Number of documents upserted. */ + get upsertedCount() { + return this.result.upsertedCount; + } + /** Inserted document generated Id's, hash key is the index of the originating operation */ + get insertedIds() { + return this.result.insertedIds; + } + /** Upserted document generated Id's, hash key is the index of the originating operation */ + get upsertedIds() { + return this.result.upsertedIds; + } +} +exports.MongoBulkWriteError = MongoBulkWriteError; +/** + * A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. + * + * @public + */ +class FindOperators { + /** + * Creates a new FindOperators object. + * @internal + */ + constructor(bulkOperation) { + this.bulkOperation = bulkOperation; + } + /** Add a multiple update operation to the bulk operation */ + update(updateDocument) { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, { + ...currentOp, + multi: true + })); + } + /** Add a single update operation to the bulk operation */ + updateOne(updateDocument) { + if (!(0, utils_1.hasAtomicOperators)(updateDocument)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); } - } - - module.exports = { - StreamDescription, - }; - - /***/ - }, - - /***/ 5193: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const deprecate = __nccwpck_require__(1669).deprecate; - const deprecateOptions = __nccwpck_require__(1371).deprecateOptions; - const emitWarningOnce = __nccwpck_require__(1371).emitWarningOnce; - const checkCollectionName = __nccwpck_require__(1371).checkCollectionName; - const ObjectID = __nccwpck_require__(3994).BSON.ObjectID; - const MongoError = __nccwpck_require__(3994).MongoError; - const normalizeHintField = __nccwpck_require__(1371).normalizeHintField; - const decorateCommand = __nccwpck_require__(1371).decorateCommand; - const decorateWithCollation = - __nccwpck_require__(1371).decorateWithCollation; - const decorateWithReadConcern = - __nccwpck_require__(1371).decorateWithReadConcern; - const formattedOrderClause = - __nccwpck_require__(1371).formattedOrderClause; - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const unordered = __nccwpck_require__(325); - const ordered = __nccwpck_require__(5035); - const ChangeStream = __nccwpck_require__(1117); - const executeLegacyOperation = - __nccwpck_require__(1371).executeLegacyOperation; - const WriteConcern = __nccwpck_require__(2481); - const ReadConcern = __nccwpck_require__(7289); - const MongoDBNamespace = __nccwpck_require__(1371).MongoDBNamespace; - const AggregationCursor = __nccwpck_require__(7429); - const CommandCursor = __nccwpck_require__(538); - - // Operations - const ensureIndex = __nccwpck_require__(6716).ensureIndex; - const group = __nccwpck_require__(6716).group; - const parallelCollectionScan = - __nccwpck_require__(6716).parallelCollectionScan; - const removeDocuments = __nccwpck_require__(2296).removeDocuments; - const save = __nccwpck_require__(6716).save; - const updateDocuments = __nccwpck_require__(2296).updateDocuments; - - const AggregateOperation = __nccwpck_require__(1554); - const BulkWriteOperation = __nccwpck_require__(6976); - const CountDocumentsOperation = __nccwpck_require__(5131); - const CreateIndexesOperation = __nccwpck_require__(6394); - const DeleteManyOperation = __nccwpck_require__(323); - const DeleteOneOperation = __nccwpck_require__(6352); - const DistinctOperation = __nccwpck_require__(6469); - const DropCollectionOperation = - __nccwpck_require__(2360).DropCollectionOperation; - const DropIndexOperation = __nccwpck_require__(3560); - const DropIndexesOperation = __nccwpck_require__(5328); - const EstimatedDocumentCountOperation = __nccwpck_require__(4451); - const FindOperation = __nccwpck_require__(9961); - const FindOneOperation = __nccwpck_require__(4497); - const FindAndModifyOperation = __nccwpck_require__(711); - const FindOneAndDeleteOperation = __nccwpck_require__(5841); - const FindOneAndReplaceOperation = __nccwpck_require__(4316); - const FindOneAndUpdateOperation = __nccwpck_require__(1925); - const GeoHaystackSearchOperation = __nccwpck_require__(8169); - const IndexesOperation = __nccwpck_require__(4218); - const IndexExistsOperation = __nccwpck_require__(7809); - const IndexInformationOperation = __nccwpck_require__(4245); - const InsertManyOperation = __nccwpck_require__(3592); - const InsertOneOperation = __nccwpck_require__(9915); - const IsCappedOperation = __nccwpck_require__(4956); - const ListIndexesOperation = __nccwpck_require__(28); - const MapReduceOperation = __nccwpck_require__(2779); - const OptionsOperation = __nccwpck_require__(43); - const RenameOperation = __nccwpck_require__(2808); - const ReIndexOperation = __nccwpck_require__(6331); - const ReplaceOneOperation = __nccwpck_require__(2508); - const StatsOperation = __nccwpck_require__(968); - const UpdateManyOperation = __nccwpck_require__(9350); - const UpdateOneOperation = __nccwpck_require__(9068); - - const executeOperation = __nccwpck_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 bsonRegExp = - options == null || options.bsonRegExp == null - ? db.s.options.bsonRegExp - : options.bsonRegExp; - 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; - + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, { ...currentOp, multi: false })); + } + /** Add a replace one operation to the bulk operation */ + replaceOne(replacement) { + if ((0, utils_1.hasAtomicOperators)(replacement)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not use atomic operators'); + } + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, replacement, { ...currentOp, multi: false })); + } + /** Add a delete one operation to the bulk operation */ + deleteOne() { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 1 })); + } + /** Add a delete many operation to the bulk operation */ + delete() { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 0 })); + } + /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */ + upsert() { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.upsert = true; + return this; + } + /** Specifies the collation for the query condition. */ + collation(collation) { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.collation = collation; + return this; + } + /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */ + arrayFilters(arrayFilters) { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.arrayFilters = arrayFilters; + return this; + } +} +exports.FindOperators = FindOperators; +/** @public */ +class BulkOperationBase { + /** + * Create a new OrderedBulkOperation or UnorderedBulkOperation instance + * @internal + */ + constructor(collection, options, isOrdered) { + // determine whether bulkOperation is ordered or unordered + this.isOrdered = isOrdered; + const topology = (0, utils_1.getTopology)(collection); + 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 = undefined; + // 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 + let finalOptions = Object.assign({}, options); + finalOptions = (0, utils_1.applyRetryableWrites)(finalOptions, collection.s.db); + // Final results + const bulkResult = { + ok: 1, + writeErrors: [], + writeConcernErrors: [], + insertedIds: [], + nInserted: 0, + nUpserted: 0, + nMatched: 0, + nModified: 0, + nRemoved: 0, + upserted: [] + }; // 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, - // bsonRegExp - bsonRegExp: bsonRegExp, - // internalHint - internalHint: internalHint, - // collectionHint - collectionHint: collectionHint, - // Promise library - promiseLibrary: promiseLibrary, - // Read Concern - readConcern: ReadConcern.fromOptions(options), - // Write Concern - writeConcern: WriteConcern.fromOptions(options), + // Final result + bulkResult, + // Current batch state + currentBatch: undefined, + currentIndex: 0, + // ordered specific + currentBatchSize: 0, + currentBatchSizeBytes: 0, + // unordered specific + currentInsertBatch: undefined, + currentUpdateBatch: undefined, + currentRemoveBatch: undefined, + batches: [], + // Write concern + writeConcern: write_concern_1.WriteConcern.fromOptions(options), + // Max batch size options + maxBsonObjectSize, + maxBatchSizeBytes, + maxWriteBatchSize, + maxKeySize, + // Namespace + namespace, + // Topology + topology, + // Options + options: finalOptions, + // BSON options + bsonOptions: (0, bson_1.resolveBSONOptions)(options), + // Current operation + currentOp, + // Executed + executed, + // Collection + collection, + // Fundamental error + err: undefined, + // check keys + checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : false }; - } - - /** - * 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.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 {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @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 {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @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 - emitWarningOnce( - "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; + // bypass Validation + if (options.bypassDocumentValidation === true) { + this.s.bypassDocumentValidation = true; + } + } + /** + * Add a single insert document to the bulk operation + * + * @example + * ```js + * 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 (document._id == null && !shouldForceServerObjectId(this)) { + document._id = new bson_1.ObjectId(); + } + return this.addToOperationsList(exports.BatchType.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. + * + * @example + * ```js + * 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({writeConcern: { 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 new error_1.MongoInvalidArgumentError('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. */ + raw(op) { + if ('insertOne' in op) { + const forceServerObjectId = shouldForceServerObjectId(this); + if (op.insertOne && op.insertOne.document == null) { + // NOTE: provided for legacy support, but this is a malformed operation + if (forceServerObjectId !== true && op.insertOne._id == null) { + op.insertOne._id = new bson_1.ObjectId(); + } + return this.addToOperationsList(exports.BatchType.INSERT, op.insertOne); } - } - - // 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; + if (forceServerObjectId !== true && op.insertOne.document._id == null) { + op.insertOne.document._id = new bson_1.ObjectId(); } - } - - // 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]; + return this.addToOperationsList(exports.BatchType.INSERT, op.insertOne.document); + } + if ('replaceOne' in op || 'updateOne' in op || 'updateMany' in op) { + if ('replaceOne' in op) { + if ('q' in op.replaceOne) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = (0, update_1.makeUpdateStatement)(op.replaceOne.filter, op.replaceOne.replacement, { ...op.replaceOne, multi: false }); + if ((0, utils_1.hasAtomicOperators)(updateStatement.u)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not use atomic operators'); + } + return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); + } + if ('updateOne' in op) { + if ('q' in op.updateOne) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = (0, update_1.makeUpdateStatement)(op.updateOne.filter, op.updateOne.update, { + ...op.updateOne, + multi: false + }); + if (!(0, utils_1.hasAtomicOperators)(updateStatement.u)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); + } + if ('updateMany' in op) { + if ('q' in op.updateMany) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + const updateStatement = (0, update_1.makeUpdateStatement)(op.updateMany.filter, op.updateMany.update, { + ...op.updateMany, + multi: true + }); + if (!(0, utils_1.hasAtomicOperators)(updateStatement.u)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); } - } - - // 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; - if ( - newOptions.bsonRegExp == null && - typeof this.s.bsonRegExp === "boolean" - ) - newOptions.bsonRegExp = this.s.bsonRegExp; - - // 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: 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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; + if ('deleteOne' in op) { + if ('q' in op.deleteOne) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + return this.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteOne.filter, { ...op.deleteOne, limit: 1 })); } - - 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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, - }); + if ('deleteMany' in op) { + if ('q' in op.deleteMany) { + throw new error_1.MongoInvalidArgumentError('Raw operations are not allowed'); + } + return this.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteMany.filter, { ...op.deleteMany, limit: 0 })); } - - 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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; + // otherwise an unknown operation was provided + throw new error_1.MongoInvalidArgumentError('bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany'); + } + get bsonOptions() { + return this.s.bsonOptions; + } + get writeConcern() { + return this.s.writeConcern; + } + get batches() { + const batches = [...this.s.batches]; + if (this.isOrdered) { + if (this.s.currentBatch) + batches.push(this.s.currentBatch); } - - 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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 {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @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; + else { + if (this.s.currentInsertBatch) + batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) + batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) + batches.push(this.s.currentRemoveBatch); } - - 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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 batches; + } + execute(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + if (this.s.executed) { + return handleEarlyError(new error_1.MongoBatchReExecutionError(), callback); } - - 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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 {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @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; + const writeConcern = write_concern_1.WriteConcern.fromOptions(options); + if (writeConcern) { + this.s.writeConcern = writeConcern; } - - 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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; + // If we have current batch + if (this.isOrdered) { + if (this.s.currentBatch) + this.s.batches.push(this.s.currentBatch); } - - 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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 {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @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; + 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); } - - 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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 {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @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; + // If we have no operations in the bulk raise an error + if (this.s.batches.length === 0) { + const emptyBatchError = new error_1.MongoInvalidArgumentError('Invalid BulkOperation, Batch cannot be empty'); + return handleEarlyError(emptyBatchError, callback); } - - 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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; + this.s.executed = true; + const finalOptions = { ...this.s.options, ...options }; + return (0, utils_1.executeLegacyOperation)(this.s.topology, executeCommands, [this, finalOptions, callback]); + } + /** + * Handles the write error before executing commands + * @internal + */ + 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'; + callback(new MongoBulkWriteError({ + message: msg, + code: this.s.bulkResult.writeErrors[0].code, + writeErrors: this.s.bulkResult.writeErrors + }, writeResult)); + return true; } - - 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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; + const writeConcernError = writeResult.getWriteConcernError(); + if (writeConcernError) { + callback(new MongoBulkWriteError(writeConcernError, writeResult)); + return true; } - - 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.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 {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @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 {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @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 - emitWarningOnce( - "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); + } +} +exports.BulkOperationBase = BulkOperationBase; +Object.defineProperty(BulkOperationBase.prototype, 'length', { + enumerable: true, + get() { + return this.s.currentIndex; + } +}); +/** helper function to assist with promiseOrCallback behavior */ +function handleEarlyError(err, callback) { + const Promise = promise_provider_1.PromiseProvider.get(); + if (typeof callback === 'function') { + callback(err); + return; + } + return Promise.reject(err); +} +function shouldForceServerObjectId(bulkOperation) { + var _a, _b; + if (typeof bulkOperation.s.options.forceServerObjectId === 'boolean') { + return bulkOperation.s.options.forceServerObjectId; + } + if (typeof ((_a = bulkOperation.s.collection.s.db.options) === null || _a === void 0 ? void 0 : _a.forceServerObjectId) === 'boolean') { + return (_b = bulkOperation.s.collection.s.db.options) === null || _b === void 0 ? void 0 : _b.forceServerObjectId; + } + return false; +} +function isInsertBatch(batch) { + return batch.batchType === exports.BatchType.INSERT; +} +function isUpdateBatch(batch) { + return batch.batchType === exports.BatchType.UPDATE; +} +function isDeleteBatch(batch) { + return batch.batchType === exports.BatchType.DELETE; +} +function buildCurrentOp(bulkOp) { + let { currentOp } = bulkOp.s; + bulkOp.s.currentOp = undefined; + if (!currentOp) + currentOp = {}; + return currentOp; +} +//# sourceMappingURL=common.js.map + +/***/ }), + +/***/ 5035: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.OrderedBulkOperation = void 0; +const BSON = __nccwpck_require__(5578); +const common_1 = __nccwpck_require__(4239); +const error_1 = __nccwpck_require__(9386); +/** @public */ +class OrderedBulkOperation extends common_1.BulkOperationBase { + constructor(collection, options) { + super(collection, options, true); + } + addToOperationsList(batchType, 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 >= this.s.maxBsonObjectSize) + // TODO(NODE-3483): Change this to MongoBSONError + throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`); + // Create a new batch object if we don't have a current one + if (this.s.currentBatch == null) { + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); } - ); - - /** - * 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 maxKeySize = this.s.maxKeySize; + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + this.s.currentBatchSize + 1 >= this.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 + (this.s.currentBatchSize > 0 && + this.s.currentBatchSizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + this.s.currentBatch.batchType !== batchType) { + // Save the batch to the execution stack + this.s.batches.push(this.s.currentBatch); + // Create a new batch + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + // Reset the current size trackers + this.s.currentBatchSize = 0; + this.s.currentBatchSizeBytes = 0; + } + if (batchType === common_1.BatchType.INSERT) { + this.s.bulkResult.insertedIds.push({ + index: this.s.currentIndex, + _id: document._id + }); + } + // We have an array of documents + if (Array.isArray(document)) { + throw new error_1.MongoInvalidArgumentError('Operation passed in cannot be an Array'); + } + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentBatch.operations.push(document); + this.s.currentBatchSize += 1; + this.s.currentBatchSizeBytes += maxKeySize + bsonSize; + this.s.currentIndex += 1; + return this; + } +} +exports.OrderedBulkOperation = OrderedBulkOperation; +//# sourceMappingURL=ordered.js.map + +/***/ }), + +/***/ 325: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.UnorderedBulkOperation = void 0; +const BSON = __nccwpck_require__(5578); +const common_1 = __nccwpck_require__(4239); +const error_1 = __nccwpck_require__(9386); +/** @public */ +class UnorderedBulkOperation extends common_1.BulkOperationBase { + constructor(collection, options) { + super(collection, options, false); + } + handleWriteError(callback, writeResult) { + if (this.s.batches.length) { + return false; + } + return super.handleWriteError(callback, writeResult); + } + addToOperationsList(batchType, 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 >= this.s.maxBsonObjectSize) { + // TODO(NODE-3483): Change this to MongoBSONError + throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`); + } + // Holds the current batch + this.s.currentBatch = undefined; + // Get the right type of batch + if (batchType === common_1.BatchType.INSERT) { + this.s.currentBatch = this.s.currentInsertBatch; + } + else if (batchType === common_1.BatchType.UPDATE) { + this.s.currentBatch = this.s.currentUpdateBatch; + } + else if (batchType === common_1.BatchType.DELETE) { + this.s.currentBatch = this.s.currentRemoveBatch; + } + const maxKeySize = this.s.maxKeySize; + // Create a new batch object if we don't have a current one + if (this.s.currentBatch == null) { + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + } + // Check if we need to create a new batch + if ( + // New batch if we exceed the max batch op size + this.s.currentBatch.size + 1 >= this.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 + (this.s.currentBatch.size > 0 && + this.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes) || + // New batch if the new op does not have the same op type as the current batch + this.s.currentBatch.batchType !== batchType) { + // Save the batch to the execution stack + this.s.batches.push(this.s.currentBatch); + // Create a new batch + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + } + // We have an array of documents + if (Array.isArray(document)) { + throw new error_1.MongoInvalidArgumentError('Operation passed in cannot be an Array'); + } + this.s.currentBatch.operations.push(document); + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentIndex = this.s.currentIndex + 1; + // Save back the current Batch to the right type + if (batchType === common_1.BatchType.INSERT) { + this.s.currentInsertBatch = this.s.currentBatch; + this.s.bulkResult.insertedIds.push({ + index: this.s.bulkResult.insertedIds.length, + _id: document._id + }); + } + else if (batchType === common_1.BatchType.UPDATE) { + this.s.currentUpdateBatch = this.s.currentBatch; + } + else if (batchType === common_1.BatchType.DELETE) { + this.s.currentRemoveBatch = this.s.currentBatch; + } + // Update current batch size + this.s.currentBatch.size += 1; + this.s.currentBatch.sizeBytes += maxKeySize + bsonSize; + return this; + } +} +exports.UnorderedBulkOperation = UnorderedBulkOperation; +//# sourceMappingURL=unordered.js.map + +/***/ }), + +/***/ 1117: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChangeStreamCursor = exports.ChangeStream = void 0; +const Denque = __nccwpck_require__(2342); +const error_1 = __nccwpck_require__(9386); +const aggregate_1 = __nccwpck_require__(1554); +const utils_1 = __nccwpck_require__(1371); +const mongo_client_1 = __nccwpck_require__(1545); +const db_1 = __nccwpck_require__(6662); +const collection_1 = __nccwpck_require__(5193); +const abstract_cursor_1 = __nccwpck_require__(7349); +const execute_operation_1 = __nccwpck_require__(2548); +const mongo_types_1 = __nccwpck_require__(696); +/** @internal */ +const kResumeQueue = Symbol('resumeQueue'); +/** @internal */ +const kCursorStream = Symbol('cursorStream'); +/** @internal */ +const kClosed = Symbol('closed'); +/** @internal */ +const kMode = Symbol('mode'); +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') +}; +const NO_RESUME_TOKEN_ERROR = 'A change stream document has been received that lacks a resume token (_id).'; +const NO_CURSOR_ERROR = 'ChangeStream has no cursor'; +const CHANGESTREAM_CLOSED_ERROR = 'ChangeStream is closed'; +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @public + */ +class ChangeStream extends mongo_types_1.TypedEventEmitter { + /** + * @internal + * + * @param parent - The parent object that created this change stream + * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents + */ + constructor(parent, pipeline = [], options = {}) { + super(); + this.pipeline = pipeline; + this.options = options; + if (parent instanceof collection_1.Collection) { + this.type = CHANGE_DOMAIN_TYPES.COLLECTION; + } + else if (parent instanceof db_1.Db) { + this.type = CHANGE_DOMAIN_TYPES.DATABASE; + } + else if (parent instanceof mongo_client_1.MongoClient) { + this.type = CHANGE_DOMAIN_TYPES.CLUSTER; + } + else { + throw new error_1.MongoChangeStreamError('Parent provided to ChangeStream constructor must be an instance of Collection, Db, or MongoClient'); + } + this.parent = parent; + this.namespace = parent.s.namespace; + if (!this.options.readPreference && parent.readPreference) { + this.options.readPreference = parent.readPreference; + } + this[kResumeQueue] = new Denque(); + // Create contained Change Stream cursor + this.cursor = createChangeStreamCursor(this, options); + this[kClosed] = false; + this[kMode] = false; + // Listen for any `change` listeners being added to ChangeStream + this.on('newListener', eventName => { + if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { + streamEvents(this, this.cursor); + } + }); + this.on('removeListener', eventName => { + var _a; + if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { + (_a = this[kCursorStream]) === null || _a === void 0 ? void 0 : _a.removeAllListeners('data'); + } + }); + } + /** @internal */ + get cursorStream() { + return this[kCursorStream]; + } + /** The cached resume token that is used to resume after the most recently returned change. */ + get resumeToken() { + var _a; + return (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.resumeToken; + } + hasNext(callback) { + setIsIterator(this); + return (0, utils_1.maybePromise)(callback, cb => { + getCursor(this, (err, cursor) => { + if (err || !cursor) + return cb(err); // failed to resume, raise an error + cursor.hasNext(cb); + }); + }); + } + next(callback) { + setIsIterator(this); + return (0, utils_1.maybePromise)(callback, cb => { + getCursor(this, (err, cursor) => { + if (err || !cursor) + 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 cursor closed */ + get closed() { + var _a, _b; + return this[kClosed] || ((_b = (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.closed) !== null && _b !== void 0 ? _b : false); + } + /** Close the Change Stream */ + close(callback) { + this[kClosed] = true; + return (0, utils_1.maybePromise)(callback, cb => { + if (!this.cursor) { + return cb(); + } + const cursor = this.cursor; + return cursor.close(err => { + endStream(this); + this.cursor = undefined; + return cb(err); + }); + }); + } + /** + * Return a modified Readable stream including a possible transform method. + * @throws MongoDriverError if this.cursor is undefined + */ + stream(options) { + this.streamOptions = options; + if (!this.cursor) + throw new error_1.MongoChangeStreamError(NO_CURSOR_ERROR); + return this.cursor.stream(options); + } + tryNext(callback) { + setIsIterator(this); + return (0, utils_1.maybePromise)(callback, cb => { + getCursor(this, (err, cursor) => { + if (err || !cursor) + return cb(err); // failed to resume, raise an error + return cursor.tryNext(cb); + }); + }); + } +} +exports.ChangeStream = ChangeStream; +/** @event */ +ChangeStream.RESPONSE = 'response'; +/** @event */ +ChangeStream.MORE = 'more'; +/** @event */ +ChangeStream.INIT = 'init'; +/** @event */ +ChangeStream.CLOSE = '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 = 'change'; +/** @event */ +ChangeStream.END = 'end'; +/** @event */ +ChangeStream.ERROR = 'error'; +/** + * Emitted each time the change stream stores a new resume token. + * @event + */ +ChangeStream.RESUME_TOKEN_CHANGED = 'resumeTokenChanged'; +/** @internal */ +class ChangeStreamCursor extends abstract_cursor_1.AbstractCursor { + constructor(topology, namespace, pipeline = [], options = {}) { + super(topology, namespace, options); + this.pipeline = pipeline; + this.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(ChangeStream.RESUME_TOKEN_CHANGED, token); + } + get resumeToken() { + return this._resumeToken; + } + get resumeOptions() { + const result = {}; + for (const optionName of CURSOR_OPTIONS) { + if (Reflect.has(this.options, optionName)) { + Reflect.set(result, optionName, Reflect.get(this.options, optionName)); + } + } + if (this.resumeToken || this.startAtOperationTime) { + ['resumeAfter', 'startAfter', 'startAtOperationTime'].forEach(key => Reflect.deleteProperty(result, key)); + if (this.resumeToken) { + const resumeKey = this.options.startAfter && !this.hasReceived ? 'startAfter' : 'resumeAfter'; + Reflect.set(result, resumeKey, this.resumeToken); + } + else if (this.startAtOperationTime && (0, utils_1.maxWireVersion)(this.server) >= 7) { + result.startAtOperationTime = this.startAtOperationTime; + } + } + return result; + } + cacheResumeToken(resumeToken) { + if (this.bufferedCount() === 0 && this.postBatchResumeToken) { + this.resumeToken = this.postBatchResumeToken; + } + else { + this.resumeToken = resumeToken; + } + this.hasReceived = true; + } + _processBatch(batchName, response) { + const cursor = (response === null || response === void 0 ? void 0 : response.cursor) || {}; + if (cursor.postBatchResumeToken) { + this.postBatchResumeToken = cursor.postBatchResumeToken; + if (cursor[batchName].length === 0) { + this.resumeToken = cursor.postBatchResumeToken; + } + } + } + clone() { + return new ChangeStreamCursor(this.topology, this.namespace, this.pipeline, { + ...this.cursorOptions + }); + } + _initialize(session, callback) { + const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this.pipeline, { + ...this.cursorOptions, + ...this.options, + session + }); + (0, execute_operation_1.executeOperation)(this.topology, aggregateOperation, (err, response) => { + if (err || response == null) { + return callback(err); + } + const server = aggregateOperation.server; + if (this.startAtOperationTime == null && + this.resumeAfter == null && + this.startAfter == null && + (0, utils_1.maxWireVersion)(server) >= 7) { + this.startAtOperationTime = response.operationTime; + } + this._processBatch('firstBatch', response); + this.emit(ChangeStream.INIT, response); + this.emit(ChangeStream.RESPONSE); + // TODO: NODE-2882 + callback(undefined, { server, session, response }); + }); + } + _getMore(batchSize, callback) { + super._getMore(batchSize, (err, response) => { + if (err) { + return callback(err); + } + this._processBatch('nextBatch', response); + this.emit(ChangeStream.MORE, response); + this.emit(ChangeStream.RESPONSE); + callback(err, response); + }); + } +} +exports.ChangeStreamCursor = ChangeStreamCursor; +const CHANGE_STREAM_EVENTS = [ + ChangeStream.RESUME_TOKEN_CHANGED, + ChangeStream.END, + ChangeStream.CLOSE +]; +function setIsEmitter(changeStream) { + if (changeStream[kMode] === 'iterator') { + // TODO(NODE-3485): Replace with MongoChangeStreamModeError + throw new error_1.MongoAPIError('ChangeStream cannot be used as an EventEmitter after being used as an iterator'); + } + changeStream[kMode] = 'emitter'; +} +function setIsIterator(changeStream) { + if (changeStream[kMode] === 'emitter') { + // TODO(NODE-3485): Replace with MongoChangeStreamModeError + throw new error_1.MongoAPIError('ChangeStream cannot be used as an iterator after being used as an EventEmitter'); + } + changeStream[kMode] = 'iterator'; +} +/** + * Create a new change stream cursor based on self's configuration + * @internal + */ +function createChangeStreamCursor(changeStream, options) { + const changeStreamStageOptions = { fullDocument: options.fullDocument || 'default' }; + applyKnownOptions(changeStreamStageOptions, options, CHANGE_STREAM_OPTIONS); + if (changeStream.type === CHANGE_DOMAIN_TYPES.CLUSTER) { + changeStreamStageOptions.allChangesForCluster = true; + } + const pipeline = [{ $changeStream: changeStreamStageOptions }].concat(changeStream.pipeline); + const cursorOptions = applyKnownOptions({}, options, CURSOR_OPTIONS); + const changeStreamCursor = new ChangeStreamCursor((0, utils_1.getTopology)(changeStream.parent), changeStream.namespace, pipeline, cursorOptions); + for (const event of CHANGE_STREAM_EVENTS) { + changeStreamCursor.on(event, e => changeStream.emit(event, e)); + } + if (changeStream.listenerCount(ChangeStream.CHANGE) > 0) { + streamEvents(changeStream, changeStreamCursor); + } + 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 = (0, utils_1.now)(); + } + const start = options.start || (0, utils_1.now)(); + const timeout = options.timeout || SELECTION_TIMEOUT; + if (topology.isConnected()) { + return callback(); + } + if ((0, utils_1.calculateDurationInMs)(start) > timeout) { + // TODO(NODE-3497): Replace with MongoNetworkTimeoutError + return callback(new error_1.MongoRuntimeError('Timed out waiting for connection')); + } + waitForTopologyConnected(topology, options, callback); + }, 500); // this is an arbitrary wait time to allow SDAM to transition +} +function closeWithError(changeStream, error, callback) { + if (!callback) { + changeStream.emit(ChangeStream.ERROR, error); + } + changeStream.close(() => callback && callback(error)); +} +function streamEvents(changeStream, cursor) { + setIsEmitter(changeStream); + const stream = changeStream[kCursorStream] || cursor.stream(); + changeStream[kCursorStream] = stream; + stream.on('data', change => processNewChange(changeStream, change)); + stream.on('error', error => processError(changeStream, error)); +} +function endStream(changeStream) { + const cursorStream = changeStream[kCursorStream]; + if (cursorStream) { + ['data', 'close', 'end', 'error'].forEach(event => cursorStream.removeAllListeners(event)); + cursorStream.destroy(); + } + changeStream[kCursorStream] = undefined; +} +function processNewChange(changeStream, change, callback) { + var _a; + if (changeStream[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + if (callback) + callback(new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR)); + return; + } + // a null change means the cursor has been notified, implicitly closing the change stream + if (change == null) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + return closeWithError(changeStream, new error_1.MongoRuntimeError(CHANGESTREAM_CLOSED_ERROR), callback); + } + if (change && !change._id) { + return closeWithError(changeStream, new error_1.MongoChangeStreamError(NO_RESUME_TOKEN_ERROR), callback); + } + // cache the resume token + (_a = changeStream.cursor) === null || _a === void 0 ? void 0 : _a.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(ChangeStream.CHANGE, change); + return callback(undefined, change); +} +function processError(changeStream, error, callback) { + const cursor = changeStream.cursor; + // If the change stream has been closed explicitly, do not process error. + if (changeStream[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + if (callback) + callback(new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR)); + 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(ChangeStream.ERROR, err); + } + changeStream.close(() => processResumeQueue(changeStream, err)); + } + if (cursor && (0, error_1.isResumableError)(error, (0, utils_1.maxWireVersion)(cursor.server))) { + changeStream.cursor = undefined; + // stop listening to all events from old cursor + endStream(changeStream); + // close internal cursor, ignore errors + cursor.close(); + const topology = (0, utils_1.getTopology)(changeStream.parent); + waitForTopologyConnected(topology, { readPreference: cursor.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 initial error wasn't resumable, raise an error and close the change stream + return closeWithError(changeStream, error, callback); +} +/** + * Safely provides a cursor across resume attempts + * + * @param changeStream - the parent ChangeStream + */ +function getCursor(changeStream, callback) { + if (changeStream[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + callback(new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR)); + 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 - the parent ChangeStream + * @param err - error getting a new cursor + */ +function processResumeQueue(changeStream, err) { + while (changeStream[kResumeQueue].length) { + const request = changeStream[kResumeQueue].pop(); + if (!request) + break; // Should never occur but TS can't use the length check in the while condition + if (!err) { + if (changeStream[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + request(new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR)); + return; + } + if (!changeStream.cursor) { + request(new error_1.MongoChangeStreamError(NO_CURSOR_ERROR)); + return; + } + } + request(err, changeStream.cursor); + } +} +//# sourceMappingURL=change_stream.js.map - 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 {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern 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.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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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 || {}; +/***/ 4802: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const createIndexesOperation = new CreateIndexesOperation( - this, - this.collectionName, - fieldOrSpec, - options - ); +"use strict"; - 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern 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.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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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 {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @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 even if a document was upserted unless `returnDocument` is specified as `'after'`, in which case the upserted document will be returned. - * @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 {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @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 || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - 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 {'before'|'after'} [options.returnDocument='before'] When set to `'after'`, returns the updated document rather than the original. The default is `'before'`. - * @param {boolean} [options.returnOriginal=true] **Deprecated** Use `options.returnDocument` instead. - * @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 {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @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 = deprecateOptions( - { - name: "collection.findOneAndReplace", - deprecatedOptions: ["returnOriginal"], - optionsIndex: 2, - }, - function (filter, replacement, 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 executeOperation( - this.s.topology, - new FindOneAndReplaceOperation(this, filter, replacement, options), - callback - ); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AuthProvider = exports.AuthContext = void 0; +const error_1 = __nccwpck_require__(9386); +/** Context used during authentication */ +class AuthContext { + constructor(connection, credentials, options) { + this.connection = connection; + this.credentials = credentials; + this.options = options; + } +} +exports.AuthContext = AuthContext; +class AuthProvider { + /** + * Prepare the handshake document before the initial handshake. + * + * @param handshakeDoc - The document used for the initial handshake on a connection + * @param authContext - Context for authentication flow + */ + prepare(handshakeDoc, authContext, callback) { + callback(undefined, handshakeDoc); + } + /** + * Authenticate + * + * @param context - A shared context for authentication flow + * @param callback - The callback to return the result from the authentication + */ + auth(context, callback) { + // TODO(NODE-3483): Replace this with MongoMethodOverrideError + callback(new error_1.MongoRuntimeError('`auth` method must be overridden by subclass')); + } +} +exports.AuthProvider = AuthProvider; +//# sourceMappingURL=auth_provider.js.map + +/***/ }), + +/***/ 7162: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AUTH_PROVIDERS = exports.AuthMechanism = void 0; +const mongocr_1 = __nccwpck_require__(9916); +const x509_1 = __nccwpck_require__(817); +const plain_1 = __nccwpck_require__(613); +const gssapi_1 = __nccwpck_require__(4816); +const scram_1 = __nccwpck_require__(9121); +const mongodb_aws_1 = __nccwpck_require__(9394); +/** @public */ +exports.AuthMechanism = Object.freeze({ + MONGODB_AWS: 'MONGODB-AWS', + MONGODB_CR: 'MONGODB-CR', + MONGODB_DEFAULT: 'DEFAULT', + MONGODB_GSSAPI: 'GSSAPI', + MONGODB_PLAIN: 'PLAIN', + MONGODB_SCRAM_SHA1: 'SCRAM-SHA-1', + MONGODB_SCRAM_SHA256: 'SCRAM-SHA-256', + MONGODB_X509: 'MONGODB-X509' +}); +exports.AUTH_PROVIDERS = new Map([ + [exports.AuthMechanism.MONGODB_AWS, new mongodb_aws_1.MongoDBAWS()], + [exports.AuthMechanism.MONGODB_CR, new mongocr_1.MongoCR()], + [exports.AuthMechanism.MONGODB_GSSAPI, new gssapi_1.GSSAPI()], + [exports.AuthMechanism.MONGODB_PLAIN, new plain_1.Plain()], + [exports.AuthMechanism.MONGODB_SCRAM_SHA1, new scram_1.ScramSHA1()], + [exports.AuthMechanism.MONGODB_SCRAM_SHA256, new scram_1.ScramSHA256()], + [exports.AuthMechanism.MONGODB_X509, new x509_1.X509()] +]); +//# sourceMappingURL=defaultAuthProviders.js.map + +/***/ }), + +/***/ 4816: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GSSAPI = void 0; +const auth_provider_1 = __nccwpck_require__(4802); +const error_1 = __nccwpck_require__(9386); +const deps_1 = __nccwpck_require__(6763); +const utils_1 = __nccwpck_require__(1371); +const dns = __nccwpck_require__(881); +class GSSAPI extends auth_provider_1.AuthProvider { + auth(authContext, callback) { + const { connection, credentials } = authContext; + if (credentials == null) + return callback(new error_1.MongoMissingCredentialsError('Credentials required for GSSAPI authentication')); + const { username } = credentials; + function externalCommand(command, cb) { + return connection.command((0, utils_1.ns)('$external.$cmd'), command, undefined, cb); + } + makeKerberosClient(authContext, (err, client) => { + if (err) + return callback(err); + if (client == null) + return callback(new error_1.MongoMissingDependencyError('GSSAPI client missing')); + client.step('', (err, payload) => { + if (err) + return callback(err); + externalCommand(saslStart(payload), (err, result) => { + if (err) + return callback(err); + if (result == null) + return callback(); + negotiate(client, 10, result.payload, (err, payload) => { + if (err) + return callback(err); + externalCommand(saslContinue(payload, result.conversationId), (err, result) => { + if (err) + return callback(err); + if (result == null) + return callback(); + 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); + }); + }); + }); + }); + }); + }); + }); + } +} +exports.GSSAPI = GSSAPI; +function makeKerberosClient(authContext, callback) { + var _a; + const { hostAddress } = authContext.options; + const { credentials } = authContext; + if (!hostAddress || typeof hostAddress.host !== 'string' || !credentials) { + return callback(new error_1.MongoInvalidArgumentError('Connection must have host and port and credentials defined.')); + } + if ('kModuleError' in deps_1.Kerberos) { + return callback(deps_1.Kerberos['kModuleError']); + } + const { initializeClient } = deps_1.Kerberos; + const { username, password } = credentials; + const mechanismProperties = credentials.mechanismProperties; + const serviceName = (_a = mechanismProperties.SERVICE_NAME) !== null && _a !== void 0 ? _a : 'mongodb'; + performGssapiCanonicalizeHostName(hostAddress.host, mechanismProperties, (err, host) => { + if (err) + return callback(err); + const initOptions = {}; + if (password != null) { + Object.assign(initOptions, { user: username, password: password }); + } + let spn = `${serviceName}${process.platform === 'win32' ? '/' : '@'}${host}`; + if ('SERVICE_REALM' in mechanismProperties) { + spn = `${spn}@${mechanismProperties.SERVICE_REALM}`; + } + initializeClient(spn, initOptions, (err, client) => { + // TODO(NODE-3483) + if (err) + return callback(new error_1.MongoRuntimeError(err)); + callback(undefined, client); + }); + }); +} +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) { + if (!mechanismProperties.gssapiCanonicalizeHostName) + 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]); } - ); - - /** - * 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 {'before'|'after'} [options.returnDocument='before'] When set to `'after'`, returns the updated document rather than the original. The default is `'before'`. - * @param {boolean} [options.returnOriginal=true] **Deprecated** Use `options.returnDocument` instead. - * @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 {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @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 = deprecateOptions( - { - name: "collection.findOneAndUpdate", - deprecatedOptions: ["returnOriginal"], - optionsIndex: 2, - }, - function (filter, 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 executeOperation( - this.s.topology, - new FindOneAndUpdateOperation(this, filter, update, options), - callback - ); + callback(undefined, host); + }); +} +//# sourceMappingURL=gssapi.js.map + +/***/ }), + +/***/ 4418: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +// Resolves the default auth mechanism according to +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MongoCredentials = void 0; +const error_1 = __nccwpck_require__(9386); +const defaultAuthProviders_1 = __nccwpck_require__(7162); +// 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.includes(defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA256) + ? defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA256 + : defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA1; + } + // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 + if (ismaster.maxWireVersion >= 3) { + return defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA1; } - ); - - /** - * 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern 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 - * @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.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 {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @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 {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @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: remove this when NODE-2074 is resolved - if (typeof callback === "function") { - callback(null, cursor); - return; + } + // Default for wireprotocol < 3 + return defaultAuthProviders_1.AuthMechanism.MONGODB_CR; +} +/** + * A representation of the credentials used by MongoDB + * @public + */ +class MongoCredentials { + constructor(options) { + this.username = options.username; + this.password = options.password; + this.source = options.source; + if (!this.source && options.db) { + this.source = options.db; + } + this.mechanism = options.mechanism || defaultAuthProviders_1.AuthMechanism.MONGODB_DEFAULT; + this.mechanismProperties = options.mechanismProperties || {}; + if (this.mechanism.match(/MONGODB-AWS/i)) { + if (!this.username && process.env.AWS_ACCESS_KEY_ID) { + this.username = process.env.AWS_ACCESS_KEY_ID; + } + if (!this.password && 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 != null) { + this.mechanismProperties = { + ...this.mechanismProperties, + AWS_SESSION_TOKEN: process.env.AWS_SESSION_TOKEN + }; + } } - - 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 = []; + Object.freeze(this.mechanismProperties); + Object.freeze(this); + } + /** Determines if two MongoCredentials objects are equivalent */ + 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 ismaster - An ismaster response from the server + */ + 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 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 this; + } + validate() { + if ((this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_GSSAPI || + this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_CR || + this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_PLAIN || + this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA1 || + this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA256) && + !this.username) { + throw new error_1.MongoMissingCredentialsError(`Username required for mechanism '${this.mechanism}'`); + } + if (this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_GSSAPI || + this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_AWS || + this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_X509) { + if (this.source != null && this.source !== '$external') { + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new error_1.MongoAPIError(`Invalid source '${this.source}' for mechanism '${this.mechanism}' specified.`); + } + } + if (this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_PLAIN && this.source == null) { + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new error_1.MongoAPIError('PLAIN Authentication Mechanism needs an auth source'); + } + if (this.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_X509 && this.password != null) { + if (this.password === '') { + Reflect.set(this, 'password', undefined); + return; + } + // TODO(NODE-3485): Replace this with a MongoAuthValidationError + throw new error_1.MongoAPIError(`Password not allowed for mechanism MONGODB-X509`); } + } + static merge(creds, options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + return new MongoCredentials({ + username: (_b = (_a = options.username) !== null && _a !== void 0 ? _a : creds === null || creds === void 0 ? void 0 : creds.username) !== null && _b !== void 0 ? _b : '', + password: (_d = (_c = options.password) !== null && _c !== void 0 ? _c : creds === null || creds === void 0 ? void 0 : creds.password) !== null && _d !== void 0 ? _d : '', + mechanism: (_f = (_e = options.mechanism) !== null && _e !== void 0 ? _e : creds === null || creds === void 0 ? void 0 : creds.mechanism) !== null && _f !== void 0 ? _f : defaultAuthProviders_1.AuthMechanism.MONGODB_DEFAULT, + mechanismProperties: (_h = (_g = options.mechanismProperties) !== null && _g !== void 0 ? _g : creds === null || creds === void 0 ? void 0 : creds.mechanismProperties) !== null && _h !== void 0 ? _h : {}, + source: (_l = (_k = (_j = options.source) !== null && _j !== void 0 ? _j : options.db) !== null && _k !== void 0 ? _k : creds === null || creds === void 0 ? void 0 : creds.source) !== null && _l !== void 0 ? _l : 'admin' + }); + } +} +exports.MongoCredentials = MongoCredentials; +//# sourceMappingURL=mongo_credentials.js.map - 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); - } +/***/ 9916: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (typeof reduce === "function") { - reduce = reduce.toString(); - } +"use strict"; - if (typeof finalize === "function") { - finalize = finalize.toString(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MongoCR = void 0; +const crypto = __nccwpck_require__(6417); +const auth_provider_1 = __nccwpck_require__(4802); +const utils_1 = __nccwpck_require__(1371); +const error_1 = __nccwpck_require__(9386); +class MongoCR extends auth_provider_1.AuthProvider { + auth(authContext, callback) { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); } - - // 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 {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @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" - ); + const username = credentials.username; + const password = credentials.password; + const source = credentials.source; + connection.command((0, utils_1.ns)(`${source}.$cmd`), { getnonce: 1 }, undefined, (err, r) => { + let nonce = null; + let key = null; + // Get nonce + if (err == null) { + 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((0, utils_1.ns)(`${source}.$cmd`), authenticateCommand, undefined, callback); + }); + } +} +exports.MongoCR = MongoCR; +//# sourceMappingURL=mongocr.js.map + +/***/ }), + +/***/ 9394: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MongoDBAWS = void 0; +const http = __nccwpck_require__(8605); +const crypto = __nccwpck_require__(6417); +const url = __nccwpck_require__(8835); +const BSON = __nccwpck_require__(5578); +const auth_provider_1 = __nccwpck_require__(4802); +const mongo_credentials_1 = __nccwpck_require__(4418); +const error_1 = __nccwpck_require__(9386); +const utils_1 = __nccwpck_require__(1371); +const deps_1 = __nccwpck_require__(6763); +const defaultAuthProviders_1 = __nccwpck_require__(7162); +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'; +const bsonOptions = { + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false +}; +class MongoDBAWS extends auth_provider_1.AuthProvider { + auth(authContext, callback) { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if ('kModuleError' in deps_1.aws4) { + return callback(deps_1.aws4['kModuleError']); + } + const { sign } = deps_1.aws4; + if ((0, utils_1.maxWireVersion)(connection) < 9) { + callback(new error_1.MongoCompatibilityError('MONGODB-AWS authentication requires MongoDB version 4.4 or later')); + return; } - - if ("function" === typeof map) { - map = map.toString(); + if (!credentials.username) { + makeTempCredentials(credentials, (err, tempCredentials) => { + if (err || !tempCredentials) + return callback(err); + authContext.credentials = tempCredentials; + this.auth(authContext, callback); + }); + return; } - - if ("function" === typeof reduce) { - reduce = reduce.toString(); - } - - if ("function" === typeof options.finalize) { - options.finalize = options.finalize.toString(); + const accessKeyId = credentials.username; + const secretAccessKey = credentials.password; + const sessionToken = credentials.mechanismProperties.AWS_SESSION_TOKEN; + // If all three defined, include sessionToken, else include username and pass, else no credentials + const awsCredentials = accessKeyId && secretAccessKey && sessionToken + ? { accessKeyId, secretAccessKey, sessionToken } + : accessKeyId && secretAccessKey + ? { accessKeyId, secretAccessKey } + : undefined; + const db = credentials.source; + 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 }, bsonOptions) + }; + connection.command((0, utils_1.ns)(`${db}.$cmd`), saslStart, undefined, (err, res) => { + if (err) + return callback(err); + const serverResponse = BSON.deserialize(res.payload.buffer, bsonOptions); + const host = serverResponse.h; + const serverNonce = serverResponse.s.buffer; + if (serverNonce.length !== 64) { + callback( + // TODO(NODE-3483) + new error_1.MongoRuntimeError(`Invalid server nonce length ${serverNonce.length}, expected 64`)); + return; + } + if (serverNonce.compare(nonce, 0, nonce.length, 0, nonce.length) !== 0) { + // TODO(NODE-3483) + callback(new error_1.MongoRuntimeError('Server nonce does not begin with client nonce')); + return; + } + if (host.length < 1 || host.length > 255 || host.indexOf('..') !== -1) { + // TODO(NODE-3483) + callback(new error_1.MongoRuntimeError(`Server returned an invalid host: "${host}"`)); + return; + } + const body = 'Action=GetCallerIdentity&Version=2011-06-15'; + const options = 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 + }, awsCredentials); + const payload = { + a: options.headers.Authorization, + d: options.headers['X-Amz-Date'] + }; + if (sessionToken) { + payload.t = sessionToken; + } + const saslContinue = { + saslContinue: 1, + conversationId: 1, + payload: BSON.serialize(payload, bsonOptions) + }; + connection.command((0, utils_1.ns)(`${db}.$cmd`), saslContinue, undefined, callback); + }); + }); + } +} +exports.MongoDBAWS = MongoDBAWS; +function makeTempCredentials(credentials, callback) { + function done(creds) { + if (!creds.AccessKeyId || !creds.SecretAccessKey || !creds.Token) { + callback(new error_1.MongoMissingCredentialsError('Could not obtain temporary MONGODB-AWS credentials')); + return; } - 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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; + callback(undefined, new mongo_credentials_1.MongoCredentials({ + username: creds.AccessKeyId, + password: creds.SecretAccessKey, + source: credentials.source, + mechanism: defaultAuthProviders_1.AuthMechanism.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}`, undefined, (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) { + const 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) { + // TODO(NODE-3483) + callback(new error_1.MongoRuntimeError(`Invalid JSON response: "${data}"`)); + } + }); + }); + req.on('error', err => callback(err)); + req.end(); +} +//# sourceMappingURL=mongodb_aws.js.map + +/***/ }), + +/***/ 613: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Plain = void 0; +const bson_1 = __nccwpck_require__(5578); +const auth_provider_1 = __nccwpck_require__(4802); +const error_1 = __nccwpck_require__(9386); +const utils_1 = __nccwpck_require__(1371); +class Plain extends auth_provider_1.AuthProvider { + auth(authContext, callback) { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); } - - 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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. - * @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; + const username = credentials.username; + const password = credentials.password; + const payload = new bson_1.Binary(Buffer.from(`\x00${username}\x00${password}`)); + const command = { + saslStart: 1, + mechanism: 'PLAIN', + payload: payload, + autoAuthorize: 1 + }; + connection.command((0, utils_1.ns)('$external.$cmd'), command, undefined, callback); + } +} +exports.Plain = Plain; +//# sourceMappingURL=plain.js.map + +/***/ }), + +/***/ 9121: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ScramSHA256 = exports.ScramSHA1 = void 0; +const crypto = __nccwpck_require__(6417); +const bson_1 = __nccwpck_require__(5578); +const error_1 = __nccwpck_require__(9386); +const auth_provider_1 = __nccwpck_require__(4802); +const utils_1 = __nccwpck_require__(1371); +const deps_1 = __nccwpck_require__(6763); +const defaultAuthProviders_1 = __nccwpck_require__(7162); +class ScramSHA extends auth_provider_1.AuthProvider { + constructor(cryptoMethod) { + super(); + this.cryptoMethod = cryptoMethod || 'sha1'; + } + prepare(handshakeDoc, authContext, callback) { + const cryptoMethod = this.cryptoMethod; + const credentials = authContext.credentials; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); } - 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, - __nccwpck_require__ - ) => { - "use strict"; - - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const MongoError = __nccwpck_require__(3994).MongoError; - const Cursor = __nccwpck_require__(7159); - const CursorState = __nccwpck_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); + if (cryptoMethod === 'sha256' && deps_1.saslprep == null) { + (0, utils_1.emitWarning)('Warning: no saslprep library specified. Passwords will not be sanitized'); } - - /** - * 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, + crypto.randomBytes(24, (err, nonce) => { + if (err) { + return callback(err); + } + // store the nonce for later use + Object.assign(authContext, { nonce }); + const request = Object.assign({}, handshakeDoc, { + speculativeAuthenticate: Object.assign(makeFirstMessage(cryptoMethod, credentials, nonce), { + db: credentials.source + }) }); - } - - 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; + callback(undefined, request); + }); + } + auth(authContext, callback) { + const response = authContext.response; + if (response && response.speculativeAuthenticate) { + continueScramConversation(this.cryptoMethod, response.speculativeAuthenticate, authContext, callback); + return; } - - /** - * 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; + 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' ? defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA1 : defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA256; + // 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 bson_1.Binary(Buffer.concat([Buffer.from('n,,', 'utf8'), clientFirstMessageBare(username, nonce)])), + autoAuthorize: 1, + options: { skipEmptyExchange: true } + }; +} +function executeScram(cryptoMethod, authContext, callback) { + const { connection, credentials } = authContext; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if (!authContext.nonce) { + return callback(new error_1.MongoInvalidArgumentError('AuthContext must contain a valid nonce property')); + } + const nonce = authContext.nonce; + const db = credentials.source; + const saslStartCmd = makeFirstMessage(cryptoMethod, credentials, nonce); + connection.command((0, utils_1.ns)(`${db}.$cmd`), saslStartCmd, undefined, (_err, result) => { + const err = resolveError(_err, result); + if (err) { + return callback(err); } - - /** - * 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; + continueScramConversation(cryptoMethod, result, authContext, callback); + }); +} +function continueScramConversation(cryptoMethod, response, authContext, callback) { + const connection = authContext.connection; + const credentials = authContext.credentials; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + if (!authContext.nonce) { + return callback(new error_1.MongoInvalidArgumentError('Unable to continue SCRAM without valid nonce')); + } + const nonce = authContext.nonce; + const db = credentials.source; + const username = cleanUsername(credentials.username); + const password = credentials.password; + let processedPassword; + if (cryptoMethod === 'sha256') { + processedPassword = 'kModuleError' in deps_1.saslprep ? password : (0, deps_1.saslprep)(password); + } + else { + try { + processedPassword = passwordDigest(username, password); } + catch (e) { + return callback(e); + } + } + const payload = Buffer.isBuffer(response.payload) + ? new bson_1.Binary(response.payload) + : response.payload; + const dict = parsePayload(payload.value()); + const iterations = parseInt(dict.i, 10); + if (iterations && iterations < 4096) { + callback( + // TODO(NODE-3483) + new error_1.MongoRuntimeError(`Server returned an invalid iteration count ${iterations}`), false); + return; + } + const salt = dict.s; + const rnonce = dict.r; + if (rnonce.startsWith('nonce')) { + // TODO(NODE-3483) + callback(new error_1.MongoRuntimeError(`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(), 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 bson_1.Binary(Buffer.from(clientFinal)) + }; + connection.command((0, utils_1.ns)(`${db}.$cmd`), saslContinueCmd, undefined, (_err, r) => { + const err = resolveError(_err, r); + if (err) { + return callback(err); + } + const parsedResponse = parsePayload(r.payload.value()); + if (!compareDigest(Buffer.from(parsedResponse.v, 'base64'), serverSignature)) { + callback(new error_1.MongoRuntimeError('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((0, utils_1.ns)(`${db}.$cmd`), retrySaslContinueCmd, undefined, 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 error_1.MongoInvalidArgumentError('Username must be a string'); + } + if (typeof password !== 'string') { + throw new error_1.MongoInvalidArgumentError('Password must be a string'); + } + if (password.length === 0) { + throw new error_1.MongoInvalidArgumentError('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] != null) { + 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; + if (result) { + if (result.$err || result.errmsg) + return new error_1.MongoServerError(result); + } +} +class ScramSHA1 extends ScramSHA { + constructor() { + super('sha1'); + } +} +exports.ScramSHA1 = ScramSHA1; +class ScramSHA256 extends ScramSHA { + constructor() { + super('sha256'); + } +} +exports.ScramSHA256 = ScramSHA256; +//# sourceMappingURL=scram.js.map + +/***/ }), + +/***/ 817: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.X509 = void 0; +const auth_provider_1 = __nccwpck_require__(4802); +const error_1 = __nccwpck_require__(9386); +const utils_1 = __nccwpck_require__(1371); +class X509 extends auth_provider_1.AuthProvider { + prepare(handshakeDoc, authContext, callback) { + const { credentials } = authContext; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + Object.assign(handshakeDoc, { + speculativeAuthenticate: x509AuthenticateCommand(credentials) + }); + callback(undefined, handshakeDoc); + } + auth(authContext, callback) { + const connection = authContext.connection; + const credentials = authContext.credentials; + if (!credentials) { + return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.')); + } + const response = authContext.response; + if (response && response.speculativeAuthenticate) { + return callback(); + } + connection.command((0, utils_1.ns)('$external.$cmd'), x509AuthenticateCommand(credentials), undefined, callback); + } +} +exports.X509 = X509; +function x509AuthenticateCommand(credentials) { + const command = { authenticate: 1, mechanism: 'MONGODB-X509' }; + if (credentials.username) { + command.user = credentials.username; + } + return command; +} +//# sourceMappingURL=x509.js.map - /** - * 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; - - /***/ - }, - - /***/ 7703: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Msg = __nccwpck_require__(8988).Msg; - const KillCursor = __nccwpck_require__(9814).KillCursor; - const GetMore = __nccwpck_require__(9814).GetMore; - const deepCopy = __nccwpck_require__(1371).deepCopy; - - /** 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", - ]); - - const HELLO_COMMANDS = new Set(["hello", "ismaster", "isMaster"]); - - 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", - }; +/***/ 5975: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const OP_QUERY_KEYS = [ - "tailable", - "oplogReplay", - "noCursorTimeout", - "awaitData", - "partial", - "exhaust", - ]; +"use strict"; - const collectionName = (command) => command.ns.split(".")[1]; - - const shouldRedactCommand = (commandName, cmd) => - SENSITIVE_COMMANDS.has(commandName) || - (HELLO_COMMANDS.has(commandName) && !!cmd.speculativeAuthenticate); - - /** - * Extract the actual command from the query, possibly upconverting if it's a legacy - * format - * - * @param {Object} command the command - */ - const extractCommand = (command) => { - let extractedCommand; - if (command instanceof GetMore) { - extractedCommand = { - getMore: deepCopy(command.cursorId), +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CommandFailedEvent = exports.CommandSucceededEvent = exports.CommandStartedEvent = void 0; +const commands_1 = __nccwpck_require__(3726); +const utils_1 = __nccwpck_require__(1371); +/** + * An event indicating the start of a given + * @public + * @category Event + */ +class CommandStartedEvent { + /** + * Create a started event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + */ + constructor(connection, command) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + // TODO: remove in major revision, this is not spec behavior + if (SENSITIVE_COMMANDS.has(commandName)) { + this.commandObj = {}; + this.commandObj[commandName] = true; + } + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.databaseName = databaseName(command); + this.commandName = commandName; + this.command = maybeRedact(commandName, cmd, cmd); + } + /* @internal */ + get hasServiceId() { + return !!this.serviceId; + } +} +exports.CommandStartedEvent = CommandStartedEvent; +/** + * An event indicating the success of a given command + * @public + * @category Event + */ +class CommandSucceededEvent { + /** + * Create a succeeded event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + * @param reply - the reply for this command from the server + * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(connection, command, reply, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.commandName = commandName; + this.duration = (0, utils_1.calculateDurationInMs)(started); + this.reply = maybeRedact(commandName, cmd, extractReply(command, reply)); + } + /* @internal */ + get hasServiceId() { + return !!this.serviceId; + } +} +exports.CommandSucceededEvent = CommandSucceededEvent; +/** + * An event indicating the failure of a given command + * @public + * @category Event + */ +class CommandFailedEvent { + /** + * Create a failure event + * + * @internal + * @param pool - the pool that originated the command + * @param command - the command + * @param error - the generated error or a server error response + * @param started - a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(connection, command, error, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + const { address, connectionId, serviceId } = extractConnectionDetails(connection); + this.address = address; + this.connectionId = connectionId; + this.serviceId = serviceId; + this.requestId = command.requestId; + this.commandName = commandName; + this.duration = (0, utils_1.calculateDurationInMs)(started); + this.failure = maybeRedact(commandName, cmd, error); + } + /* @internal */ + get hasServiceId() { + return !!this.serviceId; + } +} +exports.CommandFailedEvent = CommandFailedEvent; +/** 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' +]); +const HELLO_COMMANDS = new Set(['hello', 'ismaster', 'isMaster']); +// 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 maybeRedact = (commandName, commandDoc, result) => SENSITIVE_COMMANDS.has(commandName) || + (HELLO_COMMANDS.has(commandName) && commandDoc.speculativeAuthenticate) + ? {} + : result; +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', + returnFieldSelector: 'projection' +}; +const OP_QUERY_KEYS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'partial', + 'exhaust' +]; +/** Extract the actual command from the query, possibly up-converting if it's a legacy format */ +function extractCommand(command) { + var _a; + if (command instanceof commands_1.GetMore) { + return { + getMore: (0, utils_1.deepCopy)(command.cursorId), collection: collectionName(command), - batchSize: command.numberToReturn, - }; - } else if (command instanceof KillCursor) { - extractedCommand = { + batchSize: command.numberToReturn + }; + } + if (command instanceof commands_1.KillCursor) { + return { killCursors: collectionName(command), - cursors: deepCopy(command.cursorIds), - }; - } else if (command instanceof Msg) { - extractedCommand = deepCopy(command.command); - } else if (command.query && command.query.$query) { - let result; - if (command.ns === "admin.$cmd") { - // upconvert legacy command + cursors: (0, utils_1.deepCopy)(command.cursorIds) + }; + } + if (command instanceof commands_1.Msg) { + return (0, utils_1.deepCopy)(command.command); + } + if ((_a = command.query) === null || _a === void 0 ? void 0 : _a.$query) { + let result; + if (command.ns === 'admin.$cmd') { + // up-convert legacy command result = Object.assign({}, command.query.$query); - } else { - // upconvert legacy find command + } + else { + // up-convert 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]] = deepCopy( - command.query[key] - ); + Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { + if (command.query[key] != null) { + result[LEGACY_FIND_QUERY_MAP[key]] = (0, utils_1.deepCopy)(command.query[key]); + } }); - } - - Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach((key) => { - if (typeof command[key] !== "undefined") - result[LEGACY_FIND_OPTIONS_MAP[key]] = deepCopy(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) { - extractedCommand = { explain: result }; - } else { - extractedCommand = result; - } - } else { - extractedCommand = deepCopy(command.query || command); - } - - const commandName = Object.keys(extractedCommand)[0]; - return { - cmd: extractedCommand, - name: commandName, - shouldRedact: shouldRedactCommand(commandName, extractedCommand), - }; - }; - - module.exports = { - extractCommand, - }; - - /***/ - }, - - /***/ 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; + Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { + const legacyKey = key; + if (command[legacyKey] != null) { + result[LEGACY_FIND_OPTIONS_MAP[legacyKey]] = (0, utils_1.deepCopy)(command[legacyKey]); + } + }); + OP_QUERY_KEYS.forEach(key => { + const opKey = key; + if (command[opKey]) { + result[opKey] = command[opKey]; + } + }); + if (command.pre32Limit != null) { + result.limit = command.pre32Limit; } - - /** - * 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); + if (command.query.$explain) { + return { explain: result }; } - - /** - * 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") - ); + return result; + } + const clonedQuery = {}; + const clonedCommand = {}; + if (command.query) { + for (const k in command.query) { + clonedQuery[k] = (0, utils_1.deepCopy)(command.query[k]); } - } - - /** - * 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, - __nccwpck_require__ - ) => { - "use strict"; - - const MongoCR = __nccwpck_require__(4228); - const X509 = __nccwpck_require__(7324); - const Plain = __nccwpck_require__(8728); - const GSSAPI = __nccwpck_require__(2640); - const ScramSHA1 = __nccwpck_require__(864).ScramSHA1; - const ScramSHA256 = __nccwpck_require__(864).ScramSHA256; - const MongoDBAWS = __nccwpck_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) { + clonedCommand.query = clonedQuery; + } + for (const k in command) { + if (k === 'query') + continue; + clonedCommand[k] = (0, utils_1.deepCopy)(command[k]); + } + return command.query ? clonedQuery : clonedCommand; +} +function extractReply(command, reply) { + if (command instanceof commands_1.KillCursor) { 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), + ok: 1, + cursorsUnknown: command.cursorIds }; - } - - module.exports = { defaultAuthProviders }; - - /***/ - }, - - /***/ 2640: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const dns = __nccwpck_require__(881); - - const AuthProvider = __nccwpck_require__(557).AuthProvider; - const retrieveKerberos = __nccwpck_require__(1178).retrieveKerberos; - const MongoError = __nccwpck_require__(3111).MongoError; - - let kerberos; - - class GSSAPI extends AuthProvider { - auth(authContext, callback) { - const connection = authContext.connection; - const credentials = authContext.credentials; - if (credentials == null) - return callback(new MongoError("credentials required")); - const username = credentials.username; - function externalCommand(command, cb) { - return connection.command("$external.$cmd", command, cb); - } - makeKerberosClient(authContext, (err, client) => { - if (err) return callback(err); - if (client == null) - return callback(new MongoError("gssapi client missing")); - client.step("", (err, payload) => { - if (err) return callback(err); - externalCommand(saslStart(payload), (err, response) => { - if (err) return callback(err); - const result = response.result; - negotiate(client, 10, result.payload, (err, payload) => { - if (err) return callback(err); - externalCommand( - saslContinue(payload, result.conversationId), - (err, response) => { - if (err) return callback(err); - const result = response.result; - 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 makeKerberosClient(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)); - callback(null, client); - } - ); - } - ); - } - - function saslStart(payload) { + } + if (!reply) { + return reply; + } + if (command instanceof commands_1.GetMore) { return { - saslStart: 1, - mechanism: "GSSAPI", - payload, - autoAuthorize: 1, + ok: 1, + cursor: { + id: (0, utils_1.deepCopy)(reply.cursorId), + ns: namespace(command), + nextBatch: (0, utils_1.deepCopy)(reply.documents) + } }; - } - function saslContinue(payload, conversationId) { + } + if (command instanceof commands_1.Msg) { + return (0, utils_1.deepCopy)(reply.result ? reply.result : reply); + } + // is this a legacy find command? + if (command.query && command.query.$query != null) { 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 (/MONGODB-AWS/i.test(this.mechanism)) { - if (!this.username && process.env.AWS_ACCESS_KEY_ID) { - this.username = process.env.AWS_ACCESS_KEY_ID; - } - - if (!this.password && process.env.AWS_SECRET_ACCESS_KEY) { - this.password = process.env.AWS_SECRET_ACCESS_KEY; - } - - if ( - !this.mechanismProperties.AWS_SESSION_TOKEN && - process.env.AWS_SESSION_TOKEN - ) { - this.mechanismProperties.AWS_SESSION_TOKEN = - process.env.AWS_SESSION_TOKEN; + ok: 1, + cursor: { + id: (0, utils_1.deepCopy)(reply.cursorId), + ns: namespace(command), + firstBatch: (0, utils_1.deepCopy)(reply.documents) } - } - - 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 - ); + }; + } + return (0, utils_1.deepCopy)(reply.result ? reply.result : reply); +} +function extractConnectionDetails(connection) { + let connectionId; + if ('id' in connection) { + connectionId = connection.id; + } + return { + address: connection.address, + serviceId: connection.serviceId, + connectionId + }; +} +//# sourceMappingURL=command_monitoring_events.js.map + +/***/ }), + +/***/ 3726: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BinMsg = exports.Msg = exports.Response = exports.KillCursor = exports.GetMore = exports.Query = void 0; +const read_preference_1 = __nccwpck_require__(9802); +const BSON = __nccwpck_require__(5578); +const utils_1 = __nccwpck_require__(1371); +const constants_1 = __nccwpck_require__(6042); +const error_1 = __nccwpck_require__(9386); +// Incrementing request id +let _requestId = 0; +// Query flags +const OPTS_TAILABLE_CURSOR = 2; +const OPTS_SLAVE = 4; +const OPTS_OPLOG_REPLAY = 8; +const OPTS_NO_CURSOR_TIMEOUT = 16; +const OPTS_AWAIT_DATA = 32; +const OPTS_EXHAUST = 64; +const OPTS_PARTIAL = 128; +// Response flags +const CURSOR_NOT_FOUND = 1; +const QUERY_FAILURE = 2; +const SHARD_CONFIG_STALE = 4; +const AWAIT_CAPABLE = 8; +/************************************************************** + * QUERY + **************************************************************/ +/** @internal */ +class Query { + constructor(ns, query, options) { + // Basic options needed to be passed in + // TODO(NODE-3483): Replace with MongoCommandError + if (ns == null) + throw new error_1.MongoRuntimeError('Namespace must be specified for query'); + // TODO(NODE-3483): Replace with MongoCommandError + if (query == null) + throw new error_1.MongoRuntimeError('A query document must be specified for query'); + // Validate that we are not passing 0x00 in the collection name + if (ns.indexOf('\x00') !== -1) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new error_1.MongoRuntimeError('Namespace cannot contain a null character'); } - - /** - * 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 (/DEFAULT/i.test(this.mechanism)) { - return new MongoCredentials({ - username: this.username, - password: this.password, - source: this.source, - mechanism: getDefaultAuthMechanism(ismaster), - mechanismProperties: this.mechanismProperties, - }); - } - - return this; + // Basic options + this.ns = ns; + this.query = query; + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || undefined; + 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 : false; + this.batchSize = this.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 next request Id. */ + incRequestId() { + this.requestId = _requestId++; + } + /** Peek next request Id. */ + nextRequestId() { + return _requestId + 1; + } + /** Increment then return next request Id. */ + static getRequestId() { + return ++_requestId; + } + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin() { + const buffers = []; + let projection = null; + // Set up the flags + let flags = 0; + if (this.tailable) { + flags |= OPTS_TAILABLE_CURSOR; } - } - - module.exports = { MongoCredentials }; - - /***/ - }, - - /***/ 4228: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const crypto = __nccwpck_require__(6417); - const AuthProvider = __nccwpck_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 - ); - } - ); + if (this.slaveOk) { + flags |= OPTS_SLAVE; } - } - - module.exports = MongoCR; - - /***/ - }, - - /***/ 8857: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const AuthProvider = __nccwpck_require__(557).AuthProvider; - const MongoCredentials = __nccwpck_require__(2222).MongoCredentials; - const MongoError = __nccwpck_require__(3111).MongoError; - const crypto = __nccwpck_require__(6417); - const http = __nccwpck_require__(8605); - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const url = __nccwpck_require__(8835); - - let aws4; - try { - // Ensure you always wrap an optional require in the try block NODE-3199 - aws4 = __nccwpck_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(); - }); - }); - }); + if (this.oplogReplay) { + flags |= OPTS_OPLOG_REPLAY; } - } - - 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 (this.noCursorTimeout) { + flags |= OPTS_NO_CURSOR_TIMEOUT; } - - // 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; + if (this.awaitData) { + flags |= OPTS_AWAIT_DATA; } - - // 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"; + if (this.exhaust) { + flags |= OPTS_EXHAUST; } - - return parts[1]; - } - - function request(uri, options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; + if (this.partial) { + flags |= OPTS_PARTIAL; } - - options = Object.assign( - { - method: "GET", - timeout: 10000, - json: true, - }, - url.parse(uri), - options + // If batchSize is different to this.numberToReturn + if (this.batchSize !== this.numberToReturn) + this.numberToReturn = this.batchSize; + // Allocate write protocol header buffer + const header = Buffer.alloc(4 * 4 + // Header + 4 + // Flags + Buffer.byteLength(this.ns) + + 1 + // namespace + 4 + // numberToSkip + 4 // numberToReturn ); - - 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}"`)); - } - }); + // Add header to buffers + buffers.push(header); + // Serialize the query + const query = BSON.serialize(this.query, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined }); - - req.on("error", (err) => callback(err)); - req.end(); - } - - module.exports = MongoDBAWS; - - /***/ - }, - - /***/ 8728: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const retrieveBSON = __nccwpck_require__(7746).retrieveBSON; - const AuthProvider = __nccwpck_require__(557).AuthProvider; - - // TODO: 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, - __nccwpck_require__ - ) => { - "use strict"; - - const crypto = __nccwpck_require__(6417); - const Buffer = __nccwpck_require__(1867).Buffer; - const retrieveBSON = __nccwpck_require__(7746).retrieveBSON; - const MongoError = __nccwpck_require__(3111).MongoError; - const AuthProvider = __nccwpck_require__(557).AuthProvider; - const emitWarningOnce = __nccwpck_require__(1371).emitWarning; - - const BSON = retrieveBSON(); - const Binary = BSON.Binary; - - let saslprep; - try { - // Ensure you always wrap an optional require in the try block NODE-3199 - saslprep = __nccwpck_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) { - emitWarningOnce( - "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, - } - ), + // Add query document + buffers.push(query); + if (this.returnFieldSelector && Object.keys(this.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = BSON.serialize(this.returnFieldSelector, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined }); - - 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, - __nccwpck_require__ - ) => { - "use strict"; - - const AuthProvider = __nccwpck_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.assign(command, { user: credentials.username }); - } - - return command; - } - - module.exports = X509; - - /***/ - }, - - /***/ 9815: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const KillCursor = __nccwpck_require__(9814).KillCursor; - const GetMore = __nccwpck_require__(9814).GetMore; - const calculateDurationInMs = - __nccwpck_require__(1371).calculateDurationInMs; - const extractCommand = __nccwpck_require__(7703).extractCommand; - - // helper methods - const namespace = (command) => command.ns; - const databaseName = (command) => command.ns.split(".")[0]; - const generateConnectionId = (pool) => - pool.options - ? `${pool.options.host}:${pool.options.port}` - : pool.address; - const isLegacyPool = (pool) => pool.s && pool.queue; - - 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 extractedCommand = extractCommand(command); - const commandName = extractedCommand.name; - const connectionDetails = extractConnectionDetails(pool); - - Object.assign(this, connectionDetails, { - requestId: command.requestId, - databaseName: databaseName(command), - commandName, - command: extractedCommand.shouldRedact ? {} : extractedCommand.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 extractedCommand = extractCommand(command); - const commandName = extractedCommand.name; - const connectionDetails = extractConnectionDetails(pool); - - Object.assign(this, connectionDetails, { - requestId: command.requestId, - commandName, - duration: calculateDurationInMs(started), - reply: extractedCommand.shouldRedact - ? {} - : 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 extractedCommand = extractCommand(command); - const commandName = extractedCommand.name; - const connectionDetails = extractConnectionDetails(pool); - - Object.assign(this, connectionDetails, { - requestId: command.requestId, - commandName, - duration: calculateDurationInMs(started), - failure: extractedCommand.shouldRedact ? {} : error, - }); + // Add projection document + buffers.push(projection); } - } - - 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, - __nccwpck_require__ - ) => { - "use strict"; - - var retrieveBSON = __nccwpck_require__(7746).retrieveBSON; - var BSON = retrieveBSON(); - var Long = BSON.Long; - const Buffer = __nccwpck_require__(1867).Buffer; - - // Incrementing request id - var _requestId = 0; - - // Wire command operation ids - var opcodes = __nccwpck_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); - + const totalLength = header.length + query.length + (projection ? projection.length : 0); // Set up the index - var index = 4; - + let 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; + header[index + 3] = (constants_1.OP_QUERY >> 24) & 0xff; + header[index + 2] = (constants_1.OP_QUERY >> 16) & 0xff; + header[index + 1] = (constants_1.OP_QUERY >> 8) & 0xff; + header[index] = constants_1.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; + 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 || {}; + } +} +exports.Query = Query; +/************************************************************** + * GETMORE + **************************************************************/ +/** @internal */ +class GetMore { + constructor(ns, cursorId, 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; + } + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin() { + const length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; // Create command buffer - var index = 0; + let index = 0; // Allocate buffer - var _buffer = Buffer.alloc(length); - + const _buffer = Buffer.alloc(length); // Write header information // index = write32bit(index, _buffer, length); _buffer[index + 3] = (length >> 24) & 0xff; @@ -20200,39 +16225,33 @@ _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; + _buffer[index + 3] = (constants_1.OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (constants_1.OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (constants_1.OP_GETMORE >> 8) & 0xff; + _buffer[index] = constants_1.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; + 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; @@ -20240,7 +16259,6 @@ _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; @@ -20248,36 +16266,33 @@ _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) { + return [_buffer]; + } +} +exports.GetMore = GetMore; +/************************************************************** + * KILLCURSOR + **************************************************************/ +/** @internal */ +class KillCursor { + constructor(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; - + } + // Uses a single allocated buffer for the process, avoiding multiple memory allocations + toBin() { + const length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; // Create command buffer - var index = 0; - var _buffer = Buffer.alloc(length); - + let index = 0; + const _buffer = Buffer.alloc(length); // Write header information // index = write32bit(index, _buffer, length); _buffer[index + 3] = (length >> 24) & 0xff; @@ -20285,102548 +16300,68470 @@ _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; + _buffer[index + 3] = (constants_1.OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (constants_1.OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (constants_1.OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = constants_1.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, - bsonRegExp: 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; - this.bsonRegExp = - typeof opts.bsonRegExp === "boolean" ? opts.bsonRegExp : 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 bsonRegExp = - typeof options.bsonRegExp === "boolean" - ? options.bsonRegExp - : this.opts.bsonRegExp; - var bsonSize, _options; - - // Set up the options - _options = { - promoteLongs: promoteLongs, - promoteValues: promoteValues, - promoteBuffers: promoteBuffers, - bsonRegExp: bsonRegExp, - }; - - // 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, - __nccwpck_require__ - ) => { - "use strict"; - - const net = __nccwpck_require__(1631); - const tls = __nccwpck_require__(4016); - const Connection = __nccwpck_require__(6096); - const MongoError = __nccwpck_require__(3111).MongoError; - const MongoNetworkError = __nccwpck_require__(3111).MongoNetworkError; - const MongoNetworkTimeoutError = - __nccwpck_require__(3111).MongoNetworkTimeoutError; - const defaultAuthProviders = - __nccwpck_require__(2192).defaultAuthProviders; - const AuthContext = __nccwpck_require__(557).AuthContext; - const WIRE_CONSTANTS = __nccwpck_require__(7161); - const makeClientMetadata = __nccwpck_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]; - if (authProvider == null) { - return callback( - new MongoError( - `No AuthProvider for ${credentials.mechanism} defined.` - ) - ); - } - 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 && !net.isIP(result.host)) { - 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 : 0; - 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, - __nccwpck_require__ - ) => { - "use strict"; - - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const crypto = __nccwpck_require__(6417); - const debugOptions = __nccwpck_require__(7746).debugOptions; - const parseHeader = __nccwpck_require__(7272).parseHeader; - const decompress = __nccwpck_require__(7793).decompress; - const Response = __nccwpck_require__(9814).Response; - const BinMsg = __nccwpck_require__(8988).BinMsg; - const MongoNetworkError = __nccwpck_require__(3111).MongoNetworkError; - const MongoNetworkTimeoutError = - __nccwpck_require__(3111).MongoNetworkTimeoutError; - const MongoError = __nccwpck_require__(3111).MongoError; - const Logger = __nccwpck_require__(104); - const OP_COMPRESSED = __nccwpck_require__(7272).opcodes.OP_COMPRESSED; - const OP_MSG = __nccwpck_require__(7272).opcodes.OP_MSG; - const MESSAGE_HEADER_SIZE = __nccwpck_require__(7272).MESSAGE_HEADER_SIZE; - const Buffer = __nccwpck_require__(1867).Buffer; - const Query = __nccwpck_require__(9814).Query; - const CommandResult = __nccwpck_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", - "bsonRegExp", - "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=0] 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 {boolean} [options.bsonRegExp] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @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 - : 0; - - // 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, - bsonRegExp: - typeof options.bsonRegExp === "boolean" - ? options.bsonRegExp - : 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.length} ] to ${this.address}` - ); - } else { - for (let i = 0; i < buffer.length; i++) - this.logger.debug( - `writing buffer [ ${buffer[i].length} ] 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 - : 0; - 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, - __nccwpck_require__ - ) => { - "use strict"; - - var f = __nccwpck_require__(1669).format, - MongoError = __nccwpck_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) { - // eslint-disable-next-line no-console - 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, - __nccwpck_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 = __nccwpck_require__(1867).Buffer; - const opcodes = __nccwpck_require__(7272).opcodes; - const databaseNamespace = __nccwpck_require__(7272).databaseNamespace; - const ReadPreference = __nccwpck_require__(4485); - const MongoError = __nccwpck_require__(3111).MongoError; - - // 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, - bsonRegExp: 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.bsonRegExp = - typeof opts.bsonRegExp === "boolean" ? opts.bsonRegExp : 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; - const bsonRegExp = - typeof options.bsonRegExp === "boolean" - ? options.bsonRegExp - : this.opts.bsonRegExp; - - // Set up the options - const _options = { - promoteLongs: promoteLongs, - promoteValues: promoteValues, - promoteBuffers: promoteBuffers, - bsonRegExp: bsonRegExp, - }; - - while (this.index < this.data.length) { - const payloadType = this.data.readUInt8(this.index++); - if (payloadType === 1) { - // It was decided that no driver makes use of payload type 1 - throw new MongoError( - "OP_MSG Payload Type 1 detected unsupported protocol" - ); - } 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, - __nccwpck_require__ - ) => { - "use strict"; - - const inherits = __nccwpck_require__(1669).inherits; - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const MongoError = __nccwpck_require__(3111).MongoError; - const MongoTimeoutError = __nccwpck_require__(3111).MongoTimeoutError; - const MongoWriteConcernError = - __nccwpck_require__(3111).MongoWriteConcernError; - const Logger = __nccwpck_require__(104); - const f = __nccwpck_require__(1669).format; - const Msg = __nccwpck_require__(8988).Msg; - const CommandResult = __nccwpck_require__(2337); - const MESSAGE_HEADER_SIZE = __nccwpck_require__(7272).MESSAGE_HEADER_SIZE; - const COMPRESSION_DETAILS_SIZE = - __nccwpck_require__(7272).COMPRESSION_DETAILS_SIZE; - const opcodes = __nccwpck_require__(7272).opcodes; - const compress = __nccwpck_require__(7793).compress; - const compressorIDs = __nccwpck_require__(7793).compressorIDs; - const uncompressibleCommands = - __nccwpck_require__(7793).uncompressibleCommands; - const apm = __nccwpck_require__(9815); - const Buffer = __nccwpck_require__(1867).Buffer; - const connect = __nccwpck_require__(6573); - const updateSessionFromResponse = - __nccwpck_require__(5474).updateSessionFromResponse; - const eachAsync = __nccwpck_require__(1178).eachAsync; - const makeStateMachine = __nccwpck_require__(1178).makeStateMachine; - const now = __nccwpck_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=0] TCP Socket timeout setting - * @param {number} [options.monitoringSocketTimeout=0] 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.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @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: 0, - 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, - bsonRegExp: 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.length, - 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, - bsonRegExp: 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.bsonRegExp = - typeof options.bsonRegExp === "boolean" ? options.bsonRegExp : 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, - __nccwpck_require__ - ) => { - "use strict"; - - const require_optional = __nccwpck_require__(3182)(require); - - function debugOptions(debugFields, options) { - const finaloptions = {}; - debugFields.forEach(function (n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; - } - - function retrieveBSON() { - const BSON = __nccwpck_require__(4044); - BSON.native = false; - - const optionalBSON = require_optional("bson-ext"); - if (optionalBSON) { - optionalBSON.native = true; - return optionalBSON; - } - - 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() { - let snappy = require_optional("snappy"); - if (!snappy) { - snappy = { - compress: noSnappyWarning, - uncompress: noSnappyWarning, - compressSync: noSnappyWarning, - uncompressSync: noSnappyWarning, - }; - } - return snappy; - } - - module.exports = { - debugOptions, - retrieveBSON, - retrieveSnappy, - }; - - /***/ - }, - - /***/ 4847: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Logger = __nccwpck_require__(104); - const retrieveBSON = __nccwpck_require__(7746).retrieveBSON; - const MongoError = __nccwpck_require__(3111).MongoError; - const MongoNetworkError = __nccwpck_require__(3111).MongoNetworkError; - const collationNotSupported = - __nccwpck_require__(1178).collationNotSupported; - const ReadPreference = __nccwpck_require__(4485); - const isUnifiedTopology = __nccwpck_require__(1178).isUnifiedTopology; - const executeOperation = __nccwpck_require__(2548); - const Readable = __nccwpck_require__(2413).Readable; - const SUPPORTS = __nccwpck_require__(1371).SUPPORTS; - const MongoDBNamespace = __nccwpck_require__(1371).MongoDBNamespace; - const mergeOptions = __nccwpck_require__(1371).mergeOptions; - const OperationBase = __nccwpck_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; - } - - // Add bsonRegExp to cursor state - if (typeof topologyOptions.bsonRegExp === "boolean") { - this.cursorState.bsonRegExp = topologyOptions.bsonRegExp; - } else if (typeof options.bsonRegExp === "boolean") { - this.cursorState.bsonRegExp = options.bsonRegExp; - } - - 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: 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() { - const clonedOptions = mergeOptions({}, this.options); - delete clonedOptions.session; - return this.topology.cursor(this.ns, this.cmd, clonedOptions); - } - - /** - * 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] = - __nccwpck_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 && typeof options.beforeHandshake === "boolean") { - this[kBeforeHandshake] = options.beforeHandshake; - } - } - } - - /** - * 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, - __nccwpck_require__ - ) => { - "use strict"; - - let BSON = __nccwpck_require__(4044); - const require_optional = __nccwpck_require__(3182)(require); - const EJSON = __nccwpck_require__(1178).retrieveEJSON(); - - try { - // Ensure you always wrap an optional require in the try block NODE-3199 - // 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: __nccwpck_require__(3111).MongoError, - MongoNetworkError: __nccwpck_require__(3111).MongoNetworkError, - MongoParseError: __nccwpck_require__(3111).MongoParseError, - MongoTimeoutError: __nccwpck_require__(3111).MongoTimeoutError, - MongoServerSelectionError: - __nccwpck_require__(3111).MongoServerSelectionError, - MongoWriteConcernError: - __nccwpck_require__(3111).MongoWriteConcernError, - // Core - Connection: __nccwpck_require__(6096), - Server: __nccwpck_require__(6495), - ReplSet: __nccwpck_require__(1134), - Mongos: __nccwpck_require__(8175), - Logger: __nccwpck_require__(104), - Cursor: __nccwpck_require__(4847).CoreCursor, - ReadPreference: __nccwpck_require__(4485), - Sessions: __nccwpck_require__(5474), - BSON: BSON, - EJSON: EJSON, - Topology: __nccwpck_require__(4149).Topology, - // Raw operations - Query: __nccwpck_require__(9814).Query, - // Auth mechanisms - MongoCredentials: __nccwpck_require__(2222).MongoCredentials, - defaultAuthProviders: __nccwpck_require__(2192).defaultAuthProviders, - MongoCR: __nccwpck_require__(4228), - X509: __nccwpck_require__(7324), - Plain: __nccwpck_require__(8728), - GSSAPI: __nccwpck_require__(2640), - ScramSHA1: __nccwpck_require__(864).ScramSHA1, - ScramSHA256: __nccwpck_require__(864).ScramSHA256, - // Utilities - parseConnectionString: __nccwpck_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, - __nccwpck_require__ - ) => { - "use strict"; - - const ServerType = __nccwpck_require__(2291).ServerType; - const EventEmitter = __nccwpck_require__(8614); - const connect = __nccwpck_require__(6573); - const Connection = __nccwpck_require__(9820).Connection; - const common = __nccwpck_require__(2291); - const makeStateMachine = __nccwpck_require__(1178).makeStateMachine; - const MongoNetworkError = __nccwpck_require__(3111).MongoNetworkError; - const BSON = __nccwpck_require__(7746).retrieveBSON(); - const makeInterruptableAsyncInterval = - __nccwpck_require__(1371).makeInterruptableAsyncInterval; - const calculateDurationInMs = - __nccwpck_require__(1371).calculateDurationInMs; - const now = __nccwpck_require__(1371).now; - - const sdamEvents = __nccwpck_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: 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, - bsonRegExp: true, - } - ); - - // ensure no authentication is used for monitoring - delete connectOptions.credentials; - - // ensure encryption is not requested for monitoring - delete connectOptions.autoEncrypter; - - 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() { - const topologyVersion = this[kServer].description.topologyVersion; - if (isInCloseState(this) || topologyVersion == null) { - 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) { - 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 = { ismaster: true }; - const options = { socketTimeout: connectTimeoutMS }; - - if (isAwaitable) { - cmd.maxAwaitTimeMS = maxAwaitTimeMS; - cmd.topologyVersion = makeTopologyVersion(topologyVersion); - if (connectTimeoutMS) { - options.socketTimeout = connectTimeoutMS + maxAwaitTimeMS; - } - options.exhaustAllowed = true; - if (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 rttPinger = monitor[kRTTPinger]; - - const duration = - isAwaitable && rttPinger - ? rttPinger.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: 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, - __nccwpck_require__ - ) => { - "use strict"; - - const EventEmitter = __nccwpck_require__(8614); - const ConnectionPool = __nccwpck_require__(2529).ConnectionPool; - const CMAP_EVENT_NAMES = __nccwpck_require__(897).CMAP_EVENT_NAMES; - const MongoError = __nccwpck_require__(3111).MongoError; - const relayEvents = __nccwpck_require__(1178).relayEvents; - const BSON = __nccwpck_require__(7746).retrieveBSON(); - const Logger = __nccwpck_require__(104); - const ServerDescription = __nccwpck_require__(750).ServerDescription; - const compareTopologyVersion = - __nccwpck_require__(750).compareTopologyVersion; - const ReadPreference = __nccwpck_require__(4485); - const Monitor = __nccwpck_require__(1203).Monitor; - const MongoNetworkError = __nccwpck_require__(3111).MongoNetworkError; - const MongoNetworkTimeoutError = - __nccwpck_require__(3111).MongoNetworkTimeoutError; - const collationNotSupported = - __nccwpck_require__(1178).collationNotSupported; - const debugOptions = __nccwpck_require__(7746).debugOptions; - const isSDAMUnrecoverableError = - __nccwpck_require__(3111).isSDAMUnrecoverableError; - const isRetryableWriteError = - __nccwpck_require__(3111).isRetryableWriteError; - const isNodeShuttingDownError = - __nccwpck_require__(3111).isNodeShuttingDownError; - const isNetworkErrorBeforeHandshake = - __nccwpck_require__(3111).isNetworkErrorBeforeHandshake; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const makeStateMachine = __nccwpck_require__(1178).makeStateMachine; - const extractCommand = __nccwpck_require__(7703).extractCommand; - const common = __nccwpck_require__(2291); - const ServerType = common.ServerType; - const isTransactionCommand = - __nccwpck_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", - "bsonRegExp", - "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 supportsRetryableWrites() { - return supportsRetryableWrites(this); - } - - 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()) { - const extractedCommand = extractCommand(cmd); - this.s.logger.debug( - `executing command [${JSON.stringify({ - ns, - cmd: extractedCommand.shouldRedact - ? `${extractedCommand.name} details REDACTED` - : 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: 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, - __nccwpck_require__ - ) => { - "use strict"; - - const arrayStrictEqual = __nccwpck_require__(1178).arrayStrictEqual; - const tagsStrictEqual = __nccwpck_require__(1178).tagsStrictEqual; - const errorStrictEqual = __nccwpck_require__(1178).errorStrictEqual; - const ServerType = __nccwpck_require__(2291).ServerType; - const now = __nccwpck_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: 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, - __nccwpck_require__ - ) => { - "use strict"; - - const ServerType = __nccwpck_require__(2291).ServerType; - const TopologyType = __nccwpck_require__(2291).TopologyType; - const ReadPreference = __nccwpck_require__(4485); - const MongoError = __nccwpck_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, - __nccwpck_require__ - ) => { - "use strict"; - var __webpack_unused_export__; - - const Logger = __nccwpck_require__(104); - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const dns = __nccwpck_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, - __nccwpck_require__ - ) => { - "use strict"; - - const Denque = __nccwpck_require__(2342); - const EventEmitter = __nccwpck_require__(8614); - const ServerDescription = __nccwpck_require__(750).ServerDescription; - const ServerType = __nccwpck_require__(2291).ServerType; - const TopologyDescription = __nccwpck_require__(7962).TopologyDescription; - const TopologyType = __nccwpck_require__(2291).TopologyType; - const events = __nccwpck_require__(2785); - const Server = __nccwpck_require__(7062).Server; - const relayEvents = __nccwpck_require__(1178).relayEvents; - const ReadPreference = __nccwpck_require__(4485); - const CoreCursor = __nccwpck_require__(4847).CoreCursor; - const deprecate = __nccwpck_require__(1669).deprecate; - const BSON = __nccwpck_require__(7746).retrieveBSON(); - const createCompressionInfo = - __nccwpck_require__(2306).createCompressionInfo; - const ClientSession = __nccwpck_require__(5474).ClientSession; - const MongoError = __nccwpck_require__(3111).MongoError; - const MongoServerSelectionError = - __nccwpck_require__(3111).MongoServerSelectionError; - const resolveClusterTime = __nccwpck_require__(2306).resolveClusterTime; - const SrvPoller = __nccwpck_require__(9663) /* .SrvPoller */.D; - const getMMAPError = __nccwpck_require__(2306).getMMAPError; - const makeStateMachine = __nccwpck_require__(1178).makeStateMachine; - const eachAsync = __nccwpck_require__(1178).eachAsync; - const emitDeprecationWarning = - __nccwpck_require__(1371).emitDeprecationWarning; - const ServerSessionPool = __nccwpck_require__(5474).ServerSessionPool; - const makeClientMetadata = __nccwpck_require__(1178).makeClientMetadata; - const CMAP_EVENT_NAMES = __nccwpck_require__(897).CMAP_EVENT_NAMES; - const compareTopologyVersion = - __nccwpck_require__(750).compareTopologyVersion; - const emitWarning = __nccwpck_require__(1371).emitWarning; - - const common = __nccwpck_require__(2291); - const drainTimerQueue = common.drainTimerQueue; - const clearAndRemoveTimerFrom = common.clearAndRemoveTimerFrom; - - const serverSelection = __nccwpck_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: 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); - - 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 - ); + index = index + 4; + // Write all the cursor ids into the array + for (let 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; } - - /** - * 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 notAlreadyRetrying = !options.retrying; - const retryWrites = !!options.retryWrites; - const hasSession = !!options.session; - const supportsRetryableWrites = server.supportsRetryableWrites; - const notInTransaction = - !hasSession || !options.session.inTransaction(); - const willRetryWrite = - notAlreadyRetrying && - retryWrites && - hasSession && - supportsRetryableWrites && - notInTransaction && - 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); + // Return buffer + return [_buffer]; + } +} +exports.KillCursor = KillCursor; +/** @internal */ +class Response { + constructor(message, msgHeader, msgBody, opts) { + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.opts = opts !== null && opts !== void 0 ? opts : { + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false + }; + // 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 BSON.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 this.opts.promoteLongs === 'boolean' ? this.opts.promoteLongs : true; + this.promoteValues = + typeof this.opts.promoteValues === 'boolean' ? this.opts.promoteValues : true; + this.promoteBuffers = + typeof this.opts.promoteBuffers === 'boolean' ? this.opts.promoteBuffers : false; + this.bsonRegExp = typeof this.opts.bsonRegExp === 'boolean' ? this.opts.bsonRegExp : false; + } + isParsed() { + return this.parsed; + } + parse(options) { + var _a, _b, _c, _d; + // Don't parse again if not needed + if (this.parsed) + return; + options = options !== null && options !== void 0 ? options : {}; + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const promoteLongs = (_a = options.promoteLongs) !== null && _a !== void 0 ? _a : this.opts.promoteLongs; + const promoteValues = (_b = options.promoteValues) !== null && _b !== void 0 ? _b : this.opts.promoteValues; + const promoteBuffers = (_c = options.promoteBuffers) !== null && _c !== void 0 ? _c : this.opts.promoteBuffers; + const bsonRegExp = (_d = options.bsonRegExp) !== null && _d !== void 0 ? _d : this.opts.bsonRegExp; + let bsonSize; + // Set up the options + const _options = { + promoteLongs, + promoteValues, + promoteBuffers, + bsonRegExp + }; + // 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 (let 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); } - ); - } - - /** - * 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; + else { + this.documents[i] = BSON.deserialize(this.data.slice(this.index, this.index + bsonSize), _options); + } + // Adjust the index + this.index = this.index + bsonSize; } - - isDestroyed() { - return this.s.state === STATE_CLOSED; + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + const doc = BSON.deserialize(this.documents[0], _options); + this.documents = [doc]; } - - unref() { - emitWarning("not implemented: `unref`"); + // Set parsed + this.parsed = true; + } +} +exports.Response = Response; +// 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;] +// }; +// Msg Flags +const OPTS_CHECKSUM_PRESENT = 1; +const OPTS_MORE_TO_COME = 2; +const OPTS_EXHAUST_ALLOWED = 1 << 16; +/** @internal */ +class Msg { + constructor(ns, command, options) { + // Basic options needed to be passed in + if (command == null) + throw new error_1.MongoInvalidArgumentError('Query document must be specified for query'); + // Basic options + this.ns = ns; + this.command = command; + this.command.$db = (0, utils_1.databaseNamespace)(ns); + if (options.readPreference && options.readPreference.mode !== read_preference_1.ReadPreference.PRIMARY) { + this.command.$readPreference = options.readPreference.toJSON(); } - - // 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; + // Ensure empty options + this.options = options !== null && options !== void 0 ? 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; } - - get logicalSessionTimeoutMinutes() { - return this.description.logicalSessionTimeoutMinutes; + if (this.moreToCome) { + flags |= OPTS_MORE_TO_COME; } - - get bson() { - return this.s.bson; + if (this.exhaustAllowed) { + flags |= OPTS_EXHAUST_ALLOWED; } - } - - 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) + const header = Buffer.alloc(4 * 4 + // Header + 4 // Flags ); - - 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(); - } + 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(constants_1.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 BSON.serialize(document, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined }); - } - - /** - * 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; + } + static getRequestId() { + _requestId = (_requestId + 1) & 0x7fffffff; + return _requestId; + } +} +exports.Msg = Msg; +/** @internal */ +class BinMsg { + constructor(message, msgHeader, msgBody, opts) { + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.opts = opts !== null && opts !== void 0 ? opts : { + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + bsonRegExp: false + }; + // 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 this.opts.promoteLongs === 'boolean' ? this.opts.promoteLongs : true; + this.promoteValues = + typeof this.opts.promoteValues === 'boolean' ? this.opts.promoteValues : true; + this.promoteBuffers = + typeof this.opts.promoteBuffers === 'boolean' ? this.opts.promoteBuffers : false; + this.bsonRegExp = typeof this.opts.bsonRegExp === 'boolean' ? this.opts.bsonRegExp : false; + this.documents = []; + } + isParsed() { + return this.parsed; + } + parse(options) { + var _a, _b, _c, _d, _e; + // Don't parse again if not needed + if (this.parsed) + return; + options = options !== null && options !== void 0 ? 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 = (_a = options.promoteLongs) !== null && _a !== void 0 ? _a : this.opts.promoteLongs; + const promoteValues = (_b = options.promoteValues) !== null && _b !== void 0 ? _b : this.opts.promoteValues; + const promoteBuffers = (_c = options.promoteBuffers) !== null && _c !== void 0 ? _c : this.opts.promoteBuffers; + const bsonRegExp = (_d = options.bsonRegExp) !== null && _d !== void 0 ? _d : this.opts.bsonRegExp; + const validation = (_e = options.validation) !== null && _e !== void 0 ? _e : { utf8: { writeErrors: false } }; + // Set up the options + const bsonOptions = { + promoteLongs, + promoteValues, + promoteBuffers, + bsonRegExp, + validation + // Due to the strictness of the BSON libraries validation option we need this cast + }; + while (this.index < this.data.length) { + const payloadType = this.data.readUInt8(this.index++); + 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 : BSON.deserialize(bin, bsonOptions)); + this.index += bsonSize; + } + else if (payloadType === 1) { + // It was decided that no driver makes use of payload type 1 + // TODO(NODE-3483): Replace with MongoDeprecationError + throw new error_1.MongoRuntimeError('OP_MSG Payload Type 1 detected unsupported protocol'); + } } - - 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; + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + bsonOptions.fieldsAsRaw = fieldsAsRaw; + const doc = BSON.deserialize(this.documents[0], bsonOptions); + this.documents = [doc]; } - - 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; + this.parsed = true; + } +} +exports.BinMsg = BinMsg; +//# sourceMappingURL=commands.js.map + +/***/ }), + +/***/ 5579: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LEGAL_TCP_SOCKET_OPTIONS = exports.LEGAL_TLS_SOCKET_OPTIONS = exports.connect = void 0; +const net = __nccwpck_require__(1631); +const tls = __nccwpck_require__(4016); +const connection_1 = __nccwpck_require__(9820); +const error_1 = __nccwpck_require__(9386); +const defaultAuthProviders_1 = __nccwpck_require__(7162); +const auth_provider_1 = __nccwpck_require__(4802); +const utils_1 = __nccwpck_require__(1371); +const constants_1 = __nccwpck_require__(6042); +const bson_1 = __nccwpck_require__(5578); +const FAKE_MONGODB_SERVICE_ID = typeof process.env.FAKE_MONGODB_SERVICE_ID === 'string' && + process.env.FAKE_MONGODB_SERVICE_ID.toLowerCase() === 'true'; +function connect(options, callback) { + makeConnection(options, (err, socket) => { + var _a; + if (err || !socket) { + return callback(err); } - - // 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); - } + let ConnectionType = (_a = options.connectionType) !== null && _a !== void 0 ? _a : connection_1.Connection; + if (options.autoEncrypter) { + ConnectionType = connection_1.CryptoConnection; } - - // 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); + performInitialHandshake(new ConnectionType(socket, options), options, callback); + }); +} +exports.connect = connect; +function checkSupportedServer(ismaster, options) { + var _a; + const serverVersionHighEnough = ismaster && + (typeof ismaster.maxWireVersion === 'number' || ismaster.maxWireVersion instanceof bson_1.Int32) && + ismaster.maxWireVersion >= constants_1.MIN_SUPPORTED_WIRE_VERSION; + const serverVersionLowEnough = ismaster && + (typeof ismaster.minWireVersion === 'number' || ismaster.minWireVersion instanceof bson_1.Int32) && + ismaster.minWireVersion <= constants_1.MAX_SUPPORTED_WIRE_VERSION; + if (serverVersionHighEnough) { + if (serverVersionLowEnough) { + return null; } - } - - function executeWriteOperation(args, options, callback) { - if (typeof options === "function") (callback = options), (options = {}); - options = options || {}; - - // TODO: 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; - - topology.selectServer( - writableServerSelector(), - options, - (err, server) => { - if (err) { - callback(err, null); - return; - } - - const notAlreadyRetrying = !args.retrying; - const retryWrites = !!options.retryWrites; - const hasSession = !!options.session; - const supportsRetryableWrites = server.supportsRetryableWrites; - const notInTransaction = - !hasSession || !options.session.inTransaction(); - const notExplaining = options.explain === undefined; - const willRetryWrite = - notAlreadyRetrying && - retryWrites && - hasSession && - supportsRetryableWrites && - notInTransaction && - notExplaining; - - 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); - } + const message = `Server at ${options.hostAddress} reports minimum wire version ${JSON.stringify(ismaster.minWireVersion)}, but this version of the Node.js Driver requires at most ${constants_1.MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_1.MAX_SUPPORTED_SERVER_VERSION})`; + return new error_1.MongoCompatibilityError(message); + } + const message = `Server at ${options.hostAddress} reports maximum wire version ${(_a = JSON.stringify(ismaster.maxWireVersion)) !== null && _a !== void 0 ? _a : 0}, but this version of the Node.js Driver requires at least ${constants_1.MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_1.MIN_SUPPORTED_SERVER_VERSION})`; + return new error_1.MongoCompatibilityError(message); +} +function performInitialHandshake(conn, options, _callback) { + const callback = function (err, ret) { + if (err && conn) { + conn.destroy(); } - } - - function processWaitQueue(topology) { - if (topology.s.state === STATE_CLOSED) { - drainWaitQueue( - topology[kWaitQueue], - new MongoError("Topology is closed, please connect") - ); - return; + _callback(err, ret); + }; + const credentials = options.credentials; + if (credentials) { + if (!(credentials.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_DEFAULT) && + !defaultAuthProviders_1.AUTH_PROVIDERS.get(credentials.mechanism)) { + callback(new error_1.MongoInvalidArgumentError(`AuthMechanism '${credentials.mechanism}' not supported`)); + 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); + } + const authContext = new auth_provider_1.AuthContext(conn, credentials, options); + prepareHandshakeDocument(authContext, (err, handshakeDoc) => { + if (err || !handshakeDoc) { + return callback(err); } - - if (topology[kWaitQueue].length > 0) { - // ensure all server monitors attempt monitoring soon - topology.s.servers.forEach((server) => - process.nextTick(() => server.requestCheck()) - ); + const handshakeOptions = Object.assign({}, options); + if (typeof options.connectTimeoutMS === 'number') { + // The handshake technically is a monitoring check, so its socket timeout should be connectTimeoutMS + handshakeOptions.socketTimeoutMS = options.connectTimeoutMS; } - } - - /** - * 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, - __nccwpck_require__ - ) => { - "use strict"; - - const ServerType = __nccwpck_require__(2291).ServerType; - const ServerDescription = __nccwpck_require__(750).ServerDescription; - const WIRE_CONSTANTS = __nccwpck_require__(7161); - const TopologyType = __nccwpck_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: 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. - this.logicalSessionTimeoutMinutes = null; - for (const addressServerTuple of this.servers) { - const server = addressServerTuple[1]; - if (server.isReadable) { - if (server.logicalSessionTimeoutMinutes == null) { - // If any of the servers have a null logicalSessionsTimeout, then the whole topology does - this.logicalSessionTimeoutMinutes = null; - break; - } - - if (this.logicalSessionTimeoutMinutes == null) { - // First server with a non null logicalSessionsTimeout - this.logicalSessionTimeoutMinutes = - server.logicalSessionTimeoutMinutes; - continue; - } - - // Always select the smaller of the: - // current server logicalSessionsTimeout and the topologies logicalSessionsTimeout - this.logicalSessionTimeoutMinutes = Math.min( - this.logicalSessionTimeoutMinutes, - server.logicalSessionTimeoutMinutes - ); + const start = new Date().getTime(); + conn.command((0, utils_1.ns)('admin.$cmd'), handshakeDoc, handshakeOptions, (err, response) => { + if (err) { + callback(err); + return; } - } - } - - /** - * 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 ((response === null || response === void 0 ? void 0 : response.ok) === 0) { + callback(new error_1.MongoServerError(response)); + return; } - } - - 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 - ); + if ('isWritablePrimary' in response) { + // Provide pre-hello-style response document. + response.ismaster = response.isWritablePrimary; } - } - - // 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 (response.helloOk) { + conn.helloOk = true; } - } - - if (topologyType === TopologyType.Sharded) { - if ( - [ServerType.Mongos, ServerType.Unknown].indexOf(serverType) === -1 - ) { - serverDescriptions.delete(address); + const supportedServerErr = checkSupportedServer(response, options); + if (supportedServerErr) { + callback(supportedServerErr); + return; } - } - - 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 (options.loadBalanced) { + // TODO: Durran: Remove when server support exists. (NODE-3431) + if (FAKE_MONGODB_SERVICE_ID) { + response.serviceId = response.topologyVersion.processId; + } + if (!response.serviceId) { + return callback(new error_1.MongoCompatibilityError('Driver attempted to initialize in load balancing mode, ' + + 'but the server does not support this mode.')); + } } - } - - 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); + // 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 + authContext.response = response; + const resolvedCredentials = credentials.resolveAuthMechanism(response); + const provider = defaultAuthProviders_1.AUTH_PROVIDERS.get(resolvedCredentials.mechanism); + if (!provider) { + return callback(new error_1.MongoInvalidArgumentError(`No AuthProvider for ${resolvedCredentials.mechanism} defined.`)); + } + provider.auth(authContext, err => { + if (err) + return callback(err); + callback(undefined, conn); + }); + return; } - } - - 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; - } - return undefined; + callback(undefined, conn); + }); + }); +} +function prepareHandshakeDocument(authContext, callback) { + const options = authContext.options; + const compressors = options.compressors ? options.compressors : []; + const { serverApi } = authContext.connection; + const handshakeDoc = { + [(serverApi === null || serverApi === void 0 ? void 0 : serverApi.version) ? 'hello' : 'ismaster']: true, + helloOk: true, + client: options.metadata || (0, utils_1.makeClientMetadata)(options), + compression: compressors, + loadBalanced: options.loadBalanced + }; + const credentials = authContext.credentials; + if (credentials) { + if (credentials.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_DEFAULT && credentials.username) { + handshakeDoc.saslSupportedMechs = `${credentials.source}.${credentials.username}`; + const provider = defaultAuthProviders_1.AUTH_PROVIDERS.get(defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA256); + if (!provider) { + // This auth mechanism is always present. + return callback(new error_1.MongoInvalidArgumentError(`No AuthProvider for ${defaultAuthProviders_1.AuthMechanism.MONGODB_SCRAM_SHA256} defined.`)); + } + return provider.prepare(handshakeDoc, authContext, callback); + } + const provider = defaultAuthProviders_1.AUTH_PROVIDERS.get(credentials.mechanism); + if (!provider) { + return callback(new error_1.MongoInvalidArgumentError(`No AuthProvider for ${credentials.mechanism} defined.`)); + } + return provider.prepare(handshakeDoc, authContext, callback); + } + callback(undefined, handshakeDoc); +} +/** @public */ +exports.LEGAL_TLS_SOCKET_OPTIONS = [ + 'ALPNProtocols', + 'ca', + 'cert', + 'checkServerIdentity', + 'ciphers', + 'crl', + 'ecdhCurve', + 'key', + 'minDHSize', + 'passphrase', + 'pfx', + 'rejectUnauthorized', + 'secureContext', + 'secureProtocol', + 'servername', + 'session' +]; +/** @public */ +exports.LEGAL_TCP_SOCKET_OPTIONS = [ + 'family', + 'hints', + 'localAddress', + 'localPort', + 'lookup' +]; +function parseConnectOptions(options) { + const hostAddress = options.hostAddress; + if (!hostAddress) + throw new error_1.MongoInvalidArgumentError('Option "hostAddress" is required'); + const result = {}; + for (const name of exports.LEGAL_TCP_SOCKET_OPTIONS) { + if (options[name] != null) { + result[name] = options[name]; } - - /** - * Determines if the topology description has any known servers - */ - get hasKnownServers() { - return Array.from(this.servers.values()).some( - (sd) => sd.type !== ServerType.Unknown - ); + } + if (typeof hostAddress.socketPath === 'string') { + result.path = hostAddress.socketPath; + return result; + } + else if (typeof hostAddress.host === 'string') { + result.host = hostAddress.host; + result.port = hostAddress.port; + return result; + } + else { + // This should never happen since we set up HostAddresses + // But if we don't throw here the socket could hang until timeout + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError(`Unexpected HostAddress ${JSON.stringify(hostAddress)}`); + } +} +function parseSslOptions(options) { + const result = parseConnectOptions(options); + // Merge in valid SSL options + for (const name of exports.LEGAL_TLS_SOCKET_OPTIONS) { + if (options[name] != null) { + result[name] = options[name]; } - - /** - * Determines if this topology description has a data-bearing server available. - */ - get hasDataBearingServers() { - return Array.from(this.servers.values()).some( - (sd) => sd.isDataBearing - ); + } + // Set default sni servername to be the same as host + if (result.servername == null && result.host && !net.isIP(result.host)) { + result.servername = result.host; + } + return result; +} +const SOCKET_ERROR_EVENT_LIST = ['error', 'close', 'timeout', 'parseError']; +const SOCKET_ERROR_EVENTS = new Set(SOCKET_ERROR_EVENT_LIST); +function makeConnection(options, _callback) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + const useTLS = (_a = options.tls) !== null && _a !== void 0 ? _a : false; + const keepAlive = (_b = options.keepAlive) !== null && _b !== void 0 ? _b : true; + const socketTimeoutMS = (_d = (_c = options.socketTimeoutMS) !== null && _c !== void 0 ? _c : Reflect.get(options, 'socketTimeout')) !== null && _d !== void 0 ? _d : 0; + const noDelay = (_e = options.noDelay) !== null && _e !== void 0 ? _e : true; + const connectionTimeout = (_f = options.connectTimeoutMS) !== null && _f !== void 0 ? _f : 30000; + const rejectUnauthorized = (_g = options.rejectUnauthorized) !== null && _g !== void 0 ? _g : true; + const keepAliveInitialDelay = (_j = (((_h = options.keepAliveInitialDelay) !== null && _h !== void 0 ? _h : 120000) > socketTimeoutMS + ? Math.round(socketTimeoutMS / 2) + : options.keepAliveInitialDelay)) !== null && _j !== void 0 ? _j : 120000; + let socket; + const callback = function (err, ret) { + if (err && socket) { + socket.destroy(); } - - /** - * 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); + _callback(err, ret); + }; + if (useTLS) { + const tlsSocket = tls.connect(parseSslOptions(options)); + if (typeof tlsSocket.disableRenegotiation === 'function') { + tlsSocket.disableRenegotiation(); } - } - - function topologyTypeForServerType(serverType) { - if (serverType === ServerType.Standalone) { - return TopologyType.Single; + socket = tlsSocket; + } + else { + socket = net.createConnection(parseConnectOptions(options)); + } + socket.setKeepAlive(keepAlive, keepAliveInitialDelay); + socket.setTimeout(connectionTimeout); + socket.setNoDelay(noDelay); + const connectEvent = useTLS ? 'secureConnect' : 'connect'; + let cancellationHandler; + function errorHandler(eventName) { + return (err) => { + SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); + if (cancellationHandler && options.cancellationToken) { + options.cancellationToken.removeListener('cancel', cancellationHandler); + } + socket.removeListener(connectEvent, connectHandler); + callback(connectionFailureError(eventName, err)); + }; + } + function connectHandler() { + SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); + if (cancellationHandler && options.cancellationToken) { + options.cancellationToken.removeListener('cancel', cancellationHandler); } - - if (serverType === ServerType.Mongos) { - return TopologyType.Sharded; + if ('authorizationError' in socket) { + if (socket.authorizationError && rejectUnauthorized) { + return callback(socket.authorizationError); + } } - - if (serverType === ServerType.RSPrimary) { - return TopologyType.ReplicaSetWithPrimary; + socket.setTimeout(socketTimeoutMS); + callback(undefined, socket); + } + SOCKET_ERROR_EVENTS.forEach(event => socket.once(event, errorHandler(event))); + if (options.cancellationToken) { + cancellationHandler = errorHandler('cancel'); + options.cancellationToken.once('cancel', cancellationHandler); + } + socket.once(connectEvent, connectHandler); +} +function connectionFailureError(type, err) { + switch (type) { + case 'error': + return new error_1.MongoNetworkError(err); + case 'timeout': + return new error_1.MongoNetworkTimeoutError('connection timed out'); + case 'close': + return new error_1.MongoNetworkError('connection closed'); + case 'cancel': + return new error_1.MongoNetworkError('connection establishment was cancelled'); + default: + return new error_1.MongoNetworkError('unknown network error'); + } +} +//# sourceMappingURL=connect.js.map + +/***/ }), + +/***/ 9820: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.hasSessionSupport = exports.CryptoConnection = exports.APM_EVENTS = exports.Connection = void 0; +const message_stream_1 = __nccwpck_require__(2425); +const stream_description_1 = __nccwpck_require__(6292); +const command_monitoring_events_1 = __nccwpck_require__(5975); +const sessions_1 = __nccwpck_require__(5259); +const utils_1 = __nccwpck_require__(1371); +const error_1 = __nccwpck_require__(9386); +const commands_1 = __nccwpck_require__(3726); +const bson_1 = __nccwpck_require__(5578); +const shared_1 = __nccwpck_require__(1580); +const read_preference_1 = __nccwpck_require__(9802); +const mongo_types_1 = __nccwpck_require__(696); +/** @internal */ +const kStream = Symbol('stream'); +/** @internal */ +const kQueue = Symbol('queue'); +/** @internal */ +const kMessageStream = Symbol('messageStream'); +/** @internal */ +const kGeneration = Symbol('generation'); +/** @internal */ +const kLastUseTime = Symbol('lastUseTime'); +/** @internal */ +const kClusterTime = Symbol('clusterTime'); +/** @internal */ +const kDescription = Symbol('description'); +/** @internal */ +const kIsMaster = Symbol('ismaster'); +/** @internal */ +const kAutoEncrypter = Symbol('autoEncrypter'); +/** @internal */ +const kFullResult = Symbol('fullResult'); +/** @internal */ +class Connection extends mongo_types_1.TypedEventEmitter { + constructor(stream, options) { + var _a, _b; + super(); + this.id = options.id; + this.address = streamIdentifier(stream); + this.socketTimeoutMS = (_a = options.socketTimeoutMS) !== null && _a !== void 0 ? _a : 0; + this.monitorCommands = options.monitorCommands; + this.serverApi = options.serverApi; + this.closed = false; + this.destroyed = false; + this[kDescription] = new stream_description_1.StreamDescription(this.address, options); + this[kGeneration] = options.generation; + this[kLastUseTime] = (0, utils_1.now)(); + // setup parser stream and message handling + this[kQueue] = new Map(); + this[kMessageStream] = new message_stream_1.MessageStream({ + ...options, + maxBsonMessageSize: (_b = this.ismaster) === null || _b === void 0 ? void 0 : _b.maxBsonMessageSize + }); + this[kMessageStream].on('message', messageHandler(this)); + this[kStream] = stream; + stream.on('error', () => { + /* ignore errors, listen to `close` instead */ + }); + this[kMessageStream].on('error', error => this.handleIssue({ destroy: error })); + stream.on('close', () => this.handleIssue({ isClose: true })); + stream.on('timeout', () => this.handleIssue({ isTimeout: true, destroy: true })); + // 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); + this[kDescription] = Object.freeze(this[kDescription]); + // TODO: remove this, and only use the `StreamDescription` in the future + this[kIsMaster] = response; + } + get serviceId() { + var _a; + return (_a = this.ismaster) === null || _a === void 0 ? void 0 : _a.serviceId; + } + get loadBalanced() { + return this.description.loadBalanced; + } + get generation() { + return this[kGeneration] || 0; + } + set generation(generation) { + this[kGeneration] = generation; + } + get idleTime() { + return (0, utils_1.calculateDurationInMs)(this[kLastUseTime]); + } + get clusterTime() { + return this[kClusterTime]; + } + get stream() { + return this[kStream]; + } + markAvailable() { + this[kLastUseTime] = (0, utils_1.now)(); + } + handleIssue(issue) { + if (this.closed) { + return; } - - if ( - serverType === ServerType.RSGhost || - serverType === ServerType.Unknown - ) { - return TopologyType.Unknown; + if (issue.destroy) { + this[kStream].destroy(typeof issue.destroy === 'boolean' ? undefined : issue.destroy); } - - return TopologyType.ReplicaSetNoPrimary; - } - - function compareObjectId(oid1, oid2) { - if (oid1 == null) { - return -1; + this.closed = true; + for (const [, op] of this[kQueue]) { + if (issue.isTimeout) { + op.cb(new error_1.MongoNetworkTimeoutError(`connection ${this.id} to ${this.address} timed out`, { + beforeHandshake: this.ismaster == null + })); + } + else if (issue.isClose) { + op.cb(new error_1.MongoNetworkError(`connection ${this.id} to ${this.address} closed`)); + } + else { + op.cb(typeof issue.destroy === 'boolean' ? undefined : issue.destroy); + } } - - if (oid2 == null) { - return 1; + this[kQueue].clear(); + this.emit(Connection.CLOSE); + } + destroy(options, callback) { + if (typeof options === 'function') { + callback = options; + options = { force: false }; } - - if (oid1.id instanceof Buffer && oid2.id instanceof Buffer) { - const oid1Buffer = oid1.id; - const oid2Buffer = oid2.id; - return oid1Buffer.compare(oid2Buffer); + this.removeAllListeners(Connection.PINNED); + this.removeAllListeners(Connection.UNPINNED); + options = Object.assign({ force: false }, options); + if (this[kStream] == null || this.destroyed) { + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + return; } - - 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, - ]; + if (options.force) { + this[kStream].destroy(); + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + return; } - - 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, - ]; + this[kStream].end(() => { + this.destroyed = true; + if (typeof callback === 'function') { + callback(); + } + }); + } + /** @internal */ + command(ns, cmd, options, callback) { + if (!(ns instanceof utils_1.MongoDBNamespace)) { + // TODO(NODE-3483): Replace this with a MongoCommandError + throw new error_1.MongoRuntimeError('Must provide a MongoDBNamespace instance'); + } + const readPreference = (0, shared_1.getReadPreference)(cmd, options); + const shouldUseOpMsg = supportsOpMsg(this); + const session = options === null || options === void 0 ? void 0 : options.session; + let clusterTime = this.clusterTime; + let finalCmd = Object.assign({}, cmd); + if (this.serverApi) { + const { version, strict, deprecationErrors } = this.serverApi; + finalCmd.apiVersion = version; + if (strict != null) + finalCmd.apiStrict = strict; + if (deprecationErrors != null) + finalCmd.apiDeprecationErrors = deprecationErrors; + } + if (hasSessionSupport(this) && session) { + if (session.clusterTime && + clusterTime && + session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime)) { + clusterTime = session.clusterTime; + } + const err = (0, sessions_1.applySession)(session, finalCmd, options); + if (err) { + return callback(err); } - } - - maxElectionId = serverDescription.electionId; } - - if ( - serverDescription.setVersion != null && - (maxSetVersion == null || - serverDescription.setVersion > maxSetVersion) - ) { - maxSetVersion = serverDescription.setVersion; + // if we have a known cluster time, gossip it + if (clusterTime) { + finalCmd.$clusterTime = clusterTime; } - - // 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; - } + if ((0, shared_1.isSharded)(this) && !shouldUseOpMsg && readPreference && readPreference.mode !== 'primary') { + finalCmd = { + $query: finalCmd, + $readPreference: readPreference.toJSON() + }; } - - // 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"); + const commandOptions = Object.assign({ + command: true, + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false, + // This value is not overridable + slaveOk: readPreference.slaveOk() + }, options); + const cmdNs = `${ns.db}.$cmd`; + const message = shouldUseOpMsg + ? new commands_1.Msg(cmdNs, finalCmd, commandOptions) + : new commands_1.Query(cmdNs, finalCmd, commandOptions); + try { + write(this, message, commandOptions, callback); } - - if ( - setName !== serverDescription.setName || - (serverDescription.me && - serverDescription.address !== serverDescription.me) - ) { - serverDescriptions.delete(serverDescription.address); + catch (err) { + callback(err); } - - 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]; + } + /** @internal */ + query(ns, cmd, options, callback) { + var _a; + const isExplain = cmd.$explain != null; + const readPreference = (_a = options.readPreference) !== null && _a !== void 0 ? _a : read_preference_1.ReadPreference.primary; + const batchSize = options.batchSize || 0; + const limit = options.limit; + const numberToSkip = options.skip || 0; + let numberToReturn = 0; + if (limit && + (limit < 0 || (limit !== 0 && limit < batchSize) || (limit > 0 && batchSize === 0))) { + numberToReturn = limit; } - - 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); + else { + numberToReturn = batchSize; } - - return [topologyType, setName]; - } - - function checkHasPrimary(serverDescriptions) { - for (const addr of serverDescriptions.keys()) { - if (serverDescriptions.get(addr).type === ServerType.RSPrimary) { - return TopologyType.ReplicaSetWithPrimary; - } + if (isExplain) { + // 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(limit || 0); } - - return TopologyType.ReplicaSetNoPrimary; - } - - module.exports = { - TopologyDescription, - }; - - /***/ - }, - - /***/ 5474: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const retrieveBSON = __nccwpck_require__(7746).retrieveBSON; - const EventEmitter = __nccwpck_require__(8614); - const BSON = retrieveBSON(); - const Binary = BSON.Binary; - const uuidV4 = __nccwpck_require__(1178).uuidV4; - const MongoError = __nccwpck_require__(3111).MongoError; - const isRetryableError = __nccwpck_require__(3111).isRetryableError; - const MongoNetworkError = __nccwpck_require__(3111).MongoNetworkError; - const MongoWriteConcernError = - __nccwpck_require__(3111).MongoWriteConcernError; - const Transaction = __nccwpck_require__(1707).Transaction; - const TxnState = __nccwpck_require__(1707).TxnState; - const isPromiseLike = __nccwpck_require__(1178).isPromiseLike; - const ReadPreference = __nccwpck_require__(4485); - const maybePromise = __nccwpck_require__(1371).maybePromise; - const isTransactionCommand = - __nccwpck_require__(1707).isTransactionCommand; - const resolveClusterTime = __nccwpck_require__(2306).resolveClusterTime; - const isSharded = __nccwpck_require__(7272).isSharded; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const now = __nccwpck_require__(1371).now; - const calculateDurationInMs = - __nccwpck_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; + const queryOptions = { + numberToSkip, + numberToReturn, + pre32Limit: typeof limit === 'number' ? limit : undefined, + checkKeys: false, + slaveOk: readPreference.slaveOk() + }; + if (options.projection) { + queryOptions.returnFieldSelector = options.projection; } - - 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(); + const query = new commands_1.Query(ns.toString(), cmd, queryOptions); + if (typeof options.tailable === 'boolean') { + query.tailable = options.tailable; } - - /** - * The server id associated with this session - * @type {SessionId} - */ - get id() { - return this.serverSession.id; + if (typeof options.oplogReplay === 'boolean') { + query.oplogReplay = options.oplogReplay; } - - get serverSession() { - if (this[kServerSession] == null) { - this[kServerSession] = this.sessionPool.acquire(); - } - - return this[kServerSession]; + if (typeof options.timeout === 'boolean') { + query.noCursorTimeout = !options.timeout; } - - /** - * 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(); + else if (typeof options.noCursorTimeout === 'boolean') { + query.noCursorTimeout = options.noCursorTimeout; + } + if (typeof options.awaitData === 'boolean') { + query.awaitData = options.awaitData; + } + if (typeof options.partial === 'boolean') { + query.partial = options.partial; + } + write(this, query, { [kFullResult]: true, ...(0, bson_1.pluckBSONSerializeOptions)(options) }, (err, result) => { + if (err || !result) + return callback(err, result); + if (isExplain && result.documents && result.documents[0]) { + return callback(undefined, result.documents[0]); } - - 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(); + callback(undefined, result); + }); + } + /** @internal */ + getMore(ns, cursorId, options, callback) { + const fullResult = !!options[kFullResult]; + const wireVersion = (0, utils_1.maxWireVersion)(this); + if (!cursorId) { + // TODO(NODE-3483): Replace this with a MongoCommandError + callback(new error_1.MongoRuntimeError('Invalid internal cursor state, no known cursor id')); + return; + } + if (wireVersion < 4) { + const getMoreOp = new commands_1.GetMore(ns.toString(), cursorId, { numberToReturn: options.batchSize }); + const queryOptions = (0, shared_1.applyCommonQueryOptions)({}, Object.assign(options, { ...(0, bson_1.pluckBSONSerializeOptions)(options) })); + queryOptions[kFullResult] = true; + queryOptions.command = true; + write(this, getMoreOp, queryOptions, (err, response) => { + if (fullResult) + return callback(err, response); + if (err) + return callback(err); + callback(undefined, { cursor: { id: response.cursorId, nextBatch: response.documents } }); + }); + return; + } + const getMoreCmd = { + getMore: cursorId, + collection: ns.collection + }; + if (typeof options.batchSize === 'number') { + getMoreCmd.batchSize = Math.abs(options.batchSize); + } + if (typeof options.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = options.maxAwaitTimeMS; + } + const commandOptions = Object.assign({ + returnFieldSelector: null, + documentsReturnedIn: 'nextBatch' + }, options); + this.command(ns, getMoreCmd, commandOptions, callback); + } + /** @internal */ + killCursors(ns, cursorIds, options, callback) { + if (!cursorIds || !Array.isArray(cursorIds)) { + // TODO(NODE-3483): Replace this with a MongoCommandError + throw new error_1.MongoRuntimeError(`Invalid list of cursor ids provided: ${cursorIds}`); + } + if ((0, utils_1.maxWireVersion)(this) < 4) { + try { + write(this, new commands_1.KillCursor(ns.toString(), cursorIds), { noResponse: true, ...options }, callback); } - - if (session.serverSession && session.inTransaction()) { - session.abortTransaction((err) => { - if (err) return done(err); - completeEndSession(); - }); - - return; + catch (err) { + callback(err); } - - 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); + this.command(ns, { killCursors: ns.collection, cursors: cursorIds }, { [kFullResult]: true, ...options }, (err, response) => { + if (err || !response) + return callback(err); + if (response.cursorNotFound) { + return callback(new error_1.MongoNetworkError('cursor killed or timed out'), null); + } + if (!Array.isArray(response.documents) || response.documents.length === 0) { + return callback( + // TODO(NODE-3483) + new error_1.MongoRuntimeError(`invalid killCursors result returned for cursor id ${cursorIds[0]}`)); + } + callback(undefined, response.documents[0]); + }); + } +} +exports.Connection = Connection; +/** @event */ +Connection.COMMAND_STARTED = 'commandStarted'; +/** @event */ +Connection.COMMAND_SUCCEEDED = 'commandSucceeded'; +/** @event */ +Connection.COMMAND_FAILED = 'commandFailed'; +/** @event */ +Connection.CLUSTER_TIME_RECEIVED = 'clusterTimeReceived'; +/** @event */ +Connection.CLOSE = 'close'; +/** @event */ +Connection.MESSAGE = 'message'; +/** @event */ +Connection.PINNED = 'pinned'; +/** @event */ +Connection.UNPINNED = 'unpinned'; +/** @public */ +exports.APM_EVENTS = [ + Connection.COMMAND_STARTED, + Connection.COMMAND_SUCCEEDED, + Connection.COMMAND_FAILED +]; +/** @internal */ +class CryptoConnection extends Connection { + constructor(stream, options) { + super(stream, options); + this[kAutoEncrypter] = options.autoEncrypter; + } + /** @internal @override */ + command(ns, cmd, options, callback) { + const autoEncrypter = this[kAutoEncrypter]; + if (!autoEncrypter) { + return callback(new error_1.MongoMissingDependencyError('No AutoEncrypter available for encryption')); + } + const serverWireVersion = (0, utils_1.maxWireVersion)(this); + if (serverWireVersion === 0) { + // This means the initial handshake hasn't happened yet + return super.command(ns, cmd, options, callback); + } + if (serverWireVersion < 8) { + callback(new error_1.MongoCompatibilityError('Auto-encryption requires a minimum MongoDB version of 4.2')); + return; } - - /** - * Increment the transaction number on the internal ServerSession - */ - incrementTransactionNumber() { - this.serverSession.txnNumber++; + autoEncrypter.encrypt(ns.toString(), cmd, options, (err, encrypted) => { + if (err || encrypted == null) { + callback(err, null); + return; + } + super.command(ns, encrypted, options, (err, response) => { + if (err || response == null) { + callback(err, response); + return; + } + autoEncrypter.decrypt(response, options, callback); + }); + }); + } +} +exports.CryptoConnection = CryptoConnection; +/** @internal */ +function hasSessionSupport(conn) { + const description = conn.description; + return description.logicalSessionTimeoutMinutes != null || !!description.loadBalanced; +} +exports.hasSessionSupport = hasSessionSupport; +function supportsOpMsg(conn) { + const description = conn.description; + if (description == null) { + return false; + } + return (0, utils_1.maxWireVersion)(conn) >= 6 && !description.__nodejs_mock_server__; +} +function messageHandler(conn) { + return function messageHandler(message) { + // always emit the message, in case we are streaming + conn.emit('message', message); + const operationDescription = conn[kQueue].get(message.responseTo); + if (!operationDescription) { + return; } - - /** - * @returns {boolean} whether this session is currently in a transaction or not - */ - inTransaction() { - return this.transaction.isActive; + 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 ('moreToCome' in message && message.moreToCome) { + // requeue the callback for next synthetic request + conn[kQueue].set(message.requestId, operationDescription); } - - /** - * 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); + else if (operationDescription.socketTimeoutOverride) { + conn[kStream].setTimeout(conn.socketTimeoutMS); } - - /** - * 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) - ); + try { + // Pass in the entire description because it has BSON parsing options + message.parse(operationDescription); } - - /** - * 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) - ); + catch (err) { + // If this error is generated by our own code, it will already have the correct class applied + // if it is not, then it is coming from a catastrophic data parse failure or the BSON library + // in either case, it should not be wrapped + callback(err); + return; } - - /** - * This is here to ensure that ClientSession is never serialized to BSON. - * @ignore - */ - toBSON() { - throw new Error("ClientSession cannot be serialized to BSON."); + if (message.documents[0]) { + const document = message.documents[0]; + const session = operationDescription.session; + if (session) { + (0, sessions_1.updateSessionFromResponse)(session, document); + } + if (document.$clusterTime) { + conn[kClusterTime] = document.$clusterTime; + conn.emit(Connection.CLUSTER_TIME_RECEIVED, document.$clusterTime); + } + if (operationDescription.command) { + if (document.writeConcernError) { + callback(new error_1.MongoWriteConcernError(document.writeConcernError, document)); + return; + } + if (document.ok === 0 || document.$err || document.errmsg || document.code) { + callback(new error_1.MongoServerError(document)); + return; + } + } + else { + // Pre 3.2 support + if (document.ok === 0 || document.$err || document.errmsg) { + callback(new error_1.MongoServerError(document)); + return; + } + } } - - /** - * 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); + callback(undefined, operationDescription.fullResult ? message : message.documents[0]); + }; +} +function streamIdentifier(stream) { + if (typeof stream.address === 'function') { + return `${stream.remoteAddress}:${stream.remotePort}`; + } + return (0, utils_1.uuidV4)().toString('hex'); +} +function write(conn, command, options, callback) { + if (typeof options === 'function') { + callback = options; + } + options = options !== null && options !== void 0 ? options : {}; + const operationDescription = { + requestId: command.requestId, + cb: callback, + session: options.session, + fullResult: !!options[kFullResult], + 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, + bsonRegExp: typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false, + raw: typeof options.raw === 'boolean' ? options.raw : false, + started: 0 + }; + if (conn[kDescription] && conn[kDescription].compressor) { + operationDescription.agreedCompressor = conn[kDescription].compressor; + if (conn[kDescription].zlibCompressionLevel) { + operationDescription.zlibCompressionLevel = conn[kDescription].zlibCompressionLevel; } - } - - 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 (typeof options.socketTimeoutMS === 'number') { + operationDescription.socketTimeoutOverride = true; + conn[kStream].setTimeout(options.socketTimeoutMS); + } + // if command monitoring is enabled we need to modify the callback here + if (conn.monitorCommands) { + conn.emit(Connection.COMMAND_STARTED, new command_monitoring_events_1.CommandStartedEvent(conn, command)); + operationDescription.started = (0, utils_1.now)(); + operationDescription.cb = (err, reply) => { + if (err) { + conn.emit(Connection.COMMAND_FAILED, new command_monitoring_events_1.CommandFailedEvent(conn, command, err, operationDescription.started)); } - - if (err.hasErrorLabel("TransientTransactionError")) { - return attemptTransaction(session, startTime, fn, options); + else { + if (reply && (reply.ok === 0 || reply.$err)) { + conn.emit(Connection.COMMAND_FAILED, new command_monitoring_events_1.CommandFailedEvent(conn, command, reply, operationDescription.started)); + } + else { + conn.emit(Connection.COMMAND_SUCCEEDED, new command_monitoring_events_1.CommandSucceededEvent(conn, command, reply, operationDescription.started)); + } } - } - - throw err; + if (typeof callback === 'function') { + callback(err, reply); + } + }; + } + if (!operationDescription.noResponse) { + conn[kQueue].set(operationDescription.requestId, operationDescription); + } + try { + conn[kMessageStream].writeCommand(command, operationDescription); + } + catch (e) { + if (!operationDescription.noResponse) { + conn[kQueue].delete(operationDescription.requestId); + operationDescription.cb(e); + return; + } + } + if (operationDescription.noResponse) { + operationDescription.cb(); + } +} +//# sourceMappingURL=connection.js.map + +/***/ }), + +/***/ 2529: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CMAP_EVENTS = exports.ConnectionPool = void 0; +const Denque = __nccwpck_require__(2342); +const connection_1 = __nccwpck_require__(9820); +const logger_1 = __nccwpck_require__(8874); +const metrics_1 = __nccwpck_require__(2610); +const connect_1 = __nccwpck_require__(5579); +const utils_1 = __nccwpck_require__(1371); +const error_1 = __nccwpck_require__(9386); +const errors_1 = __nccwpck_require__(2926); +const connection_pool_events_1 = __nccwpck_require__(8191); +const mongo_types_1 = __nccwpck_require__(696); +/** @internal */ +const kLogger = Symbol('logger'); +/** @internal */ +const kConnections = Symbol('connections'); +/** @internal */ +const kPermits = Symbol('permits'); +/** @internal */ +const kMinPoolSizeTimer = Symbol('minPoolSizeTimer'); +/** @internal */ +const kGeneration = Symbol('generation'); +/** @internal */ +const kServiceGenerations = Symbol('serviceGenerations'); +/** @internal */ +const kConnectionCounter = Symbol('connectionCounter'); +/** @internal */ +const kCancellationToken = Symbol('cancellationToken'); +/** @internal */ +const kWaitQueue = Symbol('waitQueue'); +/** @internal */ +const kCancelled = Symbol('cancelled'); +/** @internal */ +const kMetrics = Symbol('metrics'); +/** @internal */ +const kCheckedOut = Symbol('checkedOut'); +/** @internal */ +const kProcessingWaitQueue = Symbol('processingWaitQueue'); +/** + * A pool of connections which dynamically resizes, and emit events related to pool activity + * @internal + */ +class ConnectionPool extends mongo_types_1.TypedEventEmitter { + /** @internal */ + constructor(options) { + var _a, _b, _c, _d; + super(); + this.closed = false; + this.options = Object.freeze({ + ...options, + connectionType: connection_1.Connection, + maxPoolSize: (_a = options.maxPoolSize) !== null && _a !== void 0 ? _a : 100, + minPoolSize: (_b = options.minPoolSize) !== null && _b !== void 0 ? _b : 0, + maxIdleTimeMS: (_c = options.maxIdleTimeMS) !== null && _c !== void 0 ? _c : 0, + waitQueueTimeoutMS: (_d = options.waitQueueTimeoutMS) !== null && _d !== void 0 ? _d : 0, + autoEncrypter: options.autoEncrypter, + metadata: options.metadata }); - } - - 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 (this.options.minPoolSize > this.options.maxPoolSize) { + throw new error_1.MongoInvalidArgumentError('Connection pool minimum size must not be greater than maximum pool size'); + } + this[kLogger] = new logger_1.Logger('ConnectionPool'); + this[kConnections] = new Denque(); + this[kPermits] = this.options.maxPoolSize; + this[kMinPoolSizeTimer] = undefined; + this[kGeneration] = 0; + this[kServiceGenerations] = new Map(); + this[kConnectionCounter] = (0, utils_1.makeCounter)(1); + this[kCancellationToken] = new mongo_types_1.CancellationToken(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kWaitQueue] = new Denque(); + this[kMetrics] = new metrics_1.ConnectionPoolMetrics(); + this[kCheckedOut] = 0; + this[kProcessingWaitQueue] = false; + process.nextTick(() => { + this.emit(ConnectionPool.CONNECTION_POOL_CREATED, new connection_pool_events_1.ConnectionPoolCreatedEvent(this)); + ensureMinPoolSize(this); + }); + } + /** The address of the endpoint the pool is connected to */ + get address() { + return this.options.hostAddress.toString(); + } + /** An integer representing the SDAM generation of the pool */ + get generation() { + return this[kGeneration]; + } + /** An integer expressing how many total connections (active + in use) the pool currently has */ + get totalConnectionCount() { + return this[kConnections].length + (this.options.maxPoolSize - this[kPermits]); + } + /** An integer expressing how many connections are currently available in the pool. */ + get availableConnectionCount() { + return this[kConnections].length; + } + get waitQueueSize() { + return this[kWaitQueue].length; + } + get loadBalanced() { + return this.options.loadBalanced; + } + get serviceGenerations() { + return this[kServiceGenerations]; + } + get currentCheckedOutCount() { + return this[kCheckedOut]; + } + /** + * Get the metrics information for the pool when a wait queue timeout occurs. + */ + waitQueueErrorMetrics() { + return this[kMetrics].info(this.options.maxPoolSize); + } + /** + * 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. + */ + checkOut(callback) { + this.emit(ConnectionPool.CONNECTION_CHECK_OUT_STARTED, new connection_pool_events_1.ConnectionCheckOutStartedEvent(this)); + if (this.closed) { + this.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, 'poolClosed')); + callback(new errors_1.PoolClosedError(this)); + return; + } + const waitQueueMember = { callback }; + const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS; + if (waitQueueTimeoutMS) { + waitQueueMember.timer = setTimeout(() => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timer = undefined; + this.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, 'timeout')); + waitQueueMember.callback(new errors_1.WaitQueueTimeoutError(this.loadBalanced + ? this.waitQueueErrorMetrics() + : 'Timed out while checking out a connection from connection pool', this.address)); + }, waitQueueTimeoutMS); + } + this[kCheckedOut] = this[kCheckedOut] + 1; + this[kWaitQueue].push(waitQueueMember); + process.nextTick(processWaitQueue, this); + } + /** + * Check a connection into the pool. + * + * @param 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].unshift(connection); } - - if (!isPromiseLike(promise)) { - session.abortTransaction(); - throw new TypeError( - "Function provided to `withTransaction` must return a Promise" - ); + this[kCheckedOut] = this[kCheckedOut] - 1; + this.emit(ConnectionPool.CONNECTION_CHECKED_IN, new connection_pool_events_1.ConnectionCheckedInEvent(this, connection)); + if (willDestroy) { + const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale'; + destroyConnection(this, connection, reason); } - - 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; + process.nextTick(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(serviceId) { + if (this.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = this.serviceGenerations.get(sid); + // Only need to worry if the generation exists, since it should + // always be there but typescript needs the check. + if (generation == null) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('Service generations are required in load balancer mode.'); + } + else { + // Increment the generation for the service id. + this.serviceGenerations.set(sid, generation + 1); } - - if (session.transaction.isActive) { - return session - .abortTransaction() - .then(() => maybeRetryOrThrow(err)); + } + else { + this[kGeneration] += 1; + } + this.emit('connectionPoolCleared', new connection_pool_events_1.ConnectionPoolClearedEvent(this, serviceId)); + } + close(_options, _cb) { + let options = _options; + const callback = (_cb !== null && _cb !== void 0 ? _cb : _options); + if (typeof options === 'function') { + 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(); + if (waitQueueMember) { + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + if (!waitQueueMember[kCancelled]) { + // TODO(NODE-3483): Replace with MongoConnectionPoolClosedError + waitQueueMember.callback(new error_1.MongoRuntimeError('Connection pool closed')); + } } - - 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; + // clear the min pool size timer + const minPoolSizeTimer = this[kMinPoolSizeTimer]; + if (minPoolSizeTimer) { + clearTimeout(minPoolSizeTimer); } - - 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); + // end the connection counter + if (typeof this[kConnectionCounter].return === 'function') { + this[kConnectionCounter].return(undefined); + } + // mark the pool as closed immediately + this.closed = true; + (0, utils_1.eachAsync)(this[kConnections].toArray(), (conn, cb) => { + this.emit(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, conn, 'poolClosed')); + conn.destroy(options, cb); + }, err => { + this[kConnections].clear(); + this.emit(ConnectionPool.CONNECTION_POOL_CLOSED, new connection_pool_events_1.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` + * + * @remarks When in load balancer mode, connections can be pinned to cursors or transactions. + * In these cases we pass the connection in to this method to ensure it is used and a new + * connection is not checked out. + * + * @param conn - A pinned connection for use in load balancing mode. + * @param fn - A function which operates on a managed connection + * @param callback - The original callback + */ + withConnection(conn, fn, callback) { + if (conn) { + // use the provided connection, and do _not_ check it in after execution + fn(undefined, conn, (fnErr, result) => { + if (typeof callback === 'function') { + if (fnErr) { + callback(fnErr); + } + else { + callback(undefined, result); + } + } + }); return; - } - - if (txnState === TxnState.TRANSACTION_ABORTED) { - callback(new MongoError("Cannot call abortTransaction twice")); + } + 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); + } + }); + }); + } +} +exports.ConnectionPool = ConnectionPool; +/** + * Emitted when the connection pool is created. + * @event + */ +ConnectionPool.CONNECTION_POOL_CREATED = 'connectionPoolCreated'; +/** + * Emitted once when the connection pool is closed + * @event + */ +ConnectionPool.CONNECTION_POOL_CLOSED = 'connectionPoolClosed'; +/** + * Emitted each time the connection pool is cleared and it's generation incremented + * @event + */ +ConnectionPool.CONNECTION_POOL_CLEARED = 'connectionPoolCleared'; +/** + * Emitted when a connection is created. + * @event + */ +ConnectionPool.CONNECTION_CREATED = 'connectionCreated'; +/** + * Emitted when a connection becomes established, and is ready to use + * @event + */ +ConnectionPool.CONNECTION_READY = 'connectionReady'; +/** + * Emitted when a connection is closed + * @event + */ +ConnectionPool.CONNECTION_CLOSED = 'connectionClosed'; +/** + * Emitted when an attempt to check out a connection begins + * @event + */ +ConnectionPool.CONNECTION_CHECK_OUT_STARTED = 'connectionCheckOutStarted'; +/** + * Emitted when an attempt to check out a connection fails + * @event + */ +ConnectionPool.CONNECTION_CHECK_OUT_FAILED = 'connectionCheckOutFailed'; +/** + * Emitted each time a connection is successfully checked out of the connection pool + * @event + */ +ConnectionPool.CONNECTION_CHECKED_OUT = 'connectionCheckedOut'; +/** + * Emitted each time a connection is successfully checked into the connection pool + * @event + */ +ConnectionPool.CONNECTION_CHECKED_IN = 'connectionCheckedIn'; +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) { + const serviceId = connection.serviceId; + if (pool.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = pool.serviceGenerations.get(sid); + return connection.generation !== generation; + } + return connection.generation !== pool[kGeneration]; +} +function connectionIsIdle(pool, connection) { + return !!(pool.options.maxIdleTimeMS && connection.idleTime > pool.options.maxIdleTimeMS); +} +function createConnection(pool, callback) { + const connectOptions = { + ...pool.options, + id: pool[kConnectionCounter].next().value, + generation: pool[kGeneration], + cancellationToken: pool[kCancellationToken] + }; + pool[kPermits]--; + (0, connect_1.connect)(connectOptions, (err, connection) => { + if (err || !connection) { + pool[kPermits]++; + pool[kLogger].debug(`connection attempt failed with error [${JSON.stringify(err)}]`); + if (typeof callback === 'function') { + callback(err); + } return; - } - - if ( - txnState === TxnState.TRANSACTION_COMMITTED || - txnState === TxnState.TRANSACTION_COMMITTED_EMPTY - ) { - callback( - new MongoError( - "Cannot call abortTransaction after calling commitTransaction" - ) - ); + } + // The pool might have closed since we started trying to create a connection + if (pool.closed) { + connection.destroy({ force: true }); 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 }; + // forward all events from the connection to the pool + for (const event of [...connection_1.APM_EVENTS, connection_1.Connection.CLUSTER_TIME_RECEIVED]) { + connection.on(event, (e) => pool.emit(event, e)); + } + pool.emit(ConnectionPool.CONNECTION_CREATED, new connection_pool_events_1.ConnectionCreatedEvent(pool, connection)); + if (pool.loadBalanced) { + connection.on(connection_1.Connection.PINNED, pinType => pool[kMetrics].markPinned(pinType)); + connection.on(connection_1.Connection.UNPINNED, pinType => pool[kMetrics].markUnpinned(pinType)); + const serviceId = connection.serviceId; + if (serviceId) { + let generation; + const sid = serviceId.toHexString(); + if ((generation = pool.serviceGenerations.get(sid))) { + connection.generation = generation; + } + else { + pool.serviceGenerations.set(sid, 0); + connection.generation = 0; + } + } } - - if (txnState === TxnState.TRANSACTION_COMMITTED) { - writeConcern = Object.assign({ wtimeout: 10000 }, writeConcern, { - w: "majority", - }); + connection.markAvailable(); + pool.emit(ConnectionPool.CONNECTION_READY, new connection_pool_events_1.ConnectionReadyEvent(pool, connection)); + // if a callback has been provided, check out the connection immediately + if (typeof callback === 'function') { + callback(undefined, connection); + return; } - - if (writeConcern) { - Object.assign(command, { writeConcern }); + // otherwise add it to the pool for later acquisition, and try to process the wait queue + pool[kConnections].push(connection); + process.nextTick(processWaitQueue, pool); + }); +} +function destroyConnection(pool, connection, reason) { + pool.emit(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(pool, connection, reason)); + // allow more connections to be created + pool[kPermits]++; + // destroy the connection + process.nextTick(() => connection.destroy()); +} +function processWaitQueue(pool) { + if (pool.closed || pool[kProcessingWaitQueue]) { + return; + } + pool[kProcessingWaitQueue] = true; + while (pool.waitQueueSize) { + const waitQueueMember = pool[kWaitQueue].peekFront(); + if (!waitQueueMember) { + pool[kWaitQueue].shift(); + continue; } - - if ( - commandName === "commitTransaction" && - session.transaction.options.maxTimeMS - ) { - Object.assign(command, { - maxTimeMS: session.transaction.options.maxTimeMS, - }); + if (waitQueueMember[kCancelled]) { + pool[kWaitQueue].shift(); + continue; } - - 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); + if (!pool.availableConnectionCount) { + break; } - - // The spec indicates that we should ignore all errors on `abortTransaction` - function transactionError(err) { - return commandName === "commitTransaction" ? err : null; + const connection = pool[kConnections].shift(); + if (!connection) { + break; } - - 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) - ); + const isStale = connectionIsStale(pool, connection); + const isIdle = connectionIsIdle(pool, connection); + if (!isStale && !isIdle && !connection.closed) { + pool.emit(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(pool, connection)); + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); } - - 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; + pool[kWaitQueue].shift(); + waitQueueMember.callback(undefined, connection); } - } - - /** - * 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 = []; + else { + const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle'; + destroyConnection(pool, connection, reason); } - - /** - * 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(); + } + const maxPoolSize = pool.options.maxPoolSize; + if (pool.waitQueueSize && (maxPoolSize <= 0 || pool.totalConnectionCount < maxPoolSize)) { + createConnection(pool, (err, connection) => { + const waitQueueMember = pool[kWaitQueue].shift(); + if (!waitQueueMember || waitQueueMember[kCancelled]) { + if (!err && connection) { + pool[kConnections].push(connection); } - } - ); - - 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; + pool[kProcessingWaitQueue] = false; + return; } - } + if (err) { + pool.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(pool, err)); + } + else if (connection) { + pool.emit(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(pool, connection)); + } + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + waitQueueMember.callback(err, connection); + pool[kProcessingWaitQueue] = false; + process.nextTick(() => processWaitQueue(pool)); + }); + } + else { + pool[kProcessingWaitQueue] = false; + } +} +exports.CMAP_EVENTS = [ + ConnectionPool.CONNECTION_POOL_CREATED, + ConnectionPool.CONNECTION_POOL_CLOSED, + ConnectionPool.CONNECTION_CREATED, + ConnectionPool.CONNECTION_READY, + ConnectionPool.CONNECTION_CLOSED, + ConnectionPool.CONNECTION_CHECK_OUT_STARTED, + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + ConnectionPool.CONNECTION_CHECKED_OUT, + ConnectionPool.CONNECTION_CHECKED_IN, + ConnectionPool.CONNECTION_POOL_CLEARED +]; +//# sourceMappingURL=connection_pool.js.map + +/***/ }), + +/***/ 8191: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConnectionPoolClearedEvent = exports.ConnectionCheckedInEvent = exports.ConnectionCheckedOutEvent = exports.ConnectionCheckOutFailedEvent = exports.ConnectionCheckOutStartedEvent = exports.ConnectionClosedEvent = exports.ConnectionReadyEvent = exports.ConnectionCreatedEvent = exports.ConnectionPoolClosedEvent = exports.ConnectionPoolCreatedEvent = exports.ConnectionPoolMonitoringEvent = void 0; +/** + * The base export class for all monitoring events published from the connection pool + * @public + * @category Event + */ +class ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + this.time = new Date(); + this.address = pool.address; + } +} +exports.ConnectionPoolMonitoringEvent = ConnectionPoolMonitoringEvent; +/** + * An event published when a connection pool is created + * @public + * @category Event + */ +class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + super(pool); + this.options = pool.options; + } +} +exports.ConnectionPoolCreatedEvent = ConnectionPoolCreatedEvent; +/** + * An event published when a connection pool is closed + * @public + * @category Event + */ +class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + super(pool); + } +} +exports.ConnectionPoolClosedEvent = ConnectionPoolClosedEvent; +/** + * An event published when a connection pool creates a new connection + * @public + * @category Event + */ +class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} +exports.ConnectionCreatedEvent = ConnectionCreatedEvent; +/** + * An event published when a connection is ready for use + * @public + * @category Event + */ +class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} +exports.ConnectionReadyEvent = ConnectionReadyEvent; +/** + * An event published when a connection is closed + * @public + * @category Event + */ +class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection, reason) { + super(pool); + this.connectionId = connection.id; + this.reason = reason || 'unknown'; + this.serviceId = connection.serviceId; + } +} +exports.ConnectionClosedEvent = ConnectionClosedEvent; +/** + * An event published when a request to check a connection out begins + * @public + * @category Event + */ +class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + super(pool); + } +} +exports.ConnectionCheckOutStartedEvent = ConnectionCheckOutStartedEvent; +/** + * An event published when a request to check a connection out fails + * @public + * @category Event + */ +class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, reason) { + super(pool); + this.reason = reason; + } +} +exports.ConnectionCheckOutFailedEvent = ConnectionCheckOutFailedEvent; +/** + * An event published when a connection is checked out of the connection pool + * @public + * @category Event + */ +class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} +exports.ConnectionCheckedOutEvent = ConnectionCheckedOutEvent; +/** + * An event published when a connection is checked into the connection pool + * @public + * @category Event + */ +class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, connection) { + super(pool); + this.connectionId = connection.id; + } +} +exports.ConnectionCheckedInEvent = ConnectionCheckedInEvent; +/** + * An event published when a connection pool is cleared + * @public + * @category Event + */ +class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool, serviceId) { + super(pool); + this.serviceId = serviceId; + } +} +exports.ConnectionPoolClearedEvent = ConnectionPoolClearedEvent; +//# sourceMappingURL=connection_pool_events.js.map - 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; - } - } +/***/ 2926: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!session.hasTimedOut(sessionTimeoutMinutes)) { - if (session.isDirty) { - return; - } +"use strict"; - // otherwise, readd this session to the session pool - this.sessions.unshift(session); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WaitQueueTimeoutError = exports.PoolClosedError = void 0; +const error_1 = __nccwpck_require__(9386); +/** + * An error indicating a connection pool is closed + * @category Error + */ +class PoolClosedError extends error_1.MongoDriverError { + constructor(pool) { + super('Attempted to check out a connection from closed connection pool'); + this.address = pool.address; + } + get name() { + return 'MongoPoolClosedError'; + } +} +exports.PoolClosedError = PoolClosedError; +/** + * An error thrown when a request to check out a connection times out + * @category Error + */ +class WaitQueueTimeoutError extends error_1.MongoDriverError { + constructor(message, address) { + super(message); + this.address = address; + } + get name() { + return 'MongoWaitQueueTimeoutError'; + } +} +exports.WaitQueueTimeoutError = WaitQueueTimeoutError; +//# sourceMappingURL=errors.js.map + +/***/ }), + +/***/ 2425: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MessageStream = void 0; +const stream_1 = __nccwpck_require__(2413); +const commands_1 = __nccwpck_require__(3726); +const error_1 = __nccwpck_require__(9386); +const constants_1 = __nccwpck_require__(6042); +const compression_1 = __nccwpck_require__(807); +const utils_1 = __nccwpck_require__(1371); +const MESSAGE_HEADER_SIZE = 16; +const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID +const kDefaultMaxBsonMessageSize = 1024 * 1024 * 16 * 4; +/** @internal */ +const kBuffer = Symbol('buffer'); +/** + * A duplex stream that is capable of reading and writing raw wire protocol messages, with + * support for optional compression + * @internal + */ +class MessageStream extends stream_1.Duplex { + constructor(options = {}) { + super(options); + this.maxBsonMessageSize = options.maxBsonMessageSize || kDefaultMaxBsonMessageSize; + this[kBuffer] = new utils_1.BufferPool(); + } + _write(chunk, _, callback) { + this[kBuffer].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: agreed compressor should live in `StreamDescription` + const compressorName = operationDescription && operationDescription.agreedCompressor + ? operationDescription.agreedCompressor + : 'none'; + if (compressorName === 'none' || !canCompress(command)) { + const data = command.toBin(); + this.push(Array.isArray(data) ? Buffer.concat(data) : data); + return; } - } - - // TODO: 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; + // 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 + (0, compression_1.compress)({ options: operationDescription }, messageToBeCompressed, (err, compressedMessage) => { + if (err || !compressedMessage) { + operationDescription.cb(err); + 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(constants_1.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(compression_1.Compressor[compressorName], 8); // compressorID + this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); + }); + } +} +exports.MessageStream = MessageStream; +// 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 commands_1.Msg ? command.command : command.query; + const commandName = Object.keys(commandDoc)[0]; + return !compression_1.uncompressibleCommands.has(commandName); +} +function processIncomingData(stream, callback) { + const buffer = stream[kBuffer]; + if (buffer.length < 4) { + callback(); + return; + } + const sizeOfMessage = buffer.peek(4).readInt32LE(); + if (sizeOfMessage < 0) { + callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}`)); + return; + } + if (sizeOfMessage > stream.maxBsonMessageSize) { + callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}`)); + return; + } + if (sizeOfMessage > buffer.length) { + callback(); + return; + } + const message = buffer.read(sizeOfMessage); + const messageHeader = { + length: message.readInt32LE(0), + requestId: message.readInt32LE(4), + responseTo: message.readInt32LE(8), + opCode: message.readInt32LE(12) + }; + let ResponseType = messageHeader.opCode === constants_1.OP_MSG ? commands_1.BinMsg : commands_1.Response; + if (messageHeader.opCode !== constants_1.OP_COMPRESSED) { + const messageBody = message.slice(MESSAGE_HEADER_SIZE); + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + if (buffer.length >= 4) { + processIncomingData(stream, callback); } - - if ( - command.mapReduce && - options && - options.out && - (options.out.inline === 1 || options.out === "inline") - ) { - return true; + else { + callback(); } - - 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: 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; + 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 === constants_1.OP_MSG ? commands_1.BinMsg : commands_1.Response; + (0, compression_1.decompress)(compressorID, compressedBuffer, (err, messageBody) => { + if (err || !messageBody) { + callback(err); + 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); + if (messageBody.length !== messageHeader.length) { + callback(new error_1.MongoDecompressionError('Message body and message header must be the same length')); + return; } - - // now attempt to apply transaction-specific sessions data - if (!inTransaction) { - if (session.transaction.state !== TxnState.NO_TRANSACTION) { - session.transaction.transition(TxnState.NO_TRANSACTION); - } - - // TODO: 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; + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + if (buffer.length >= 4) { + processIncomingData(stream, callback); } - - if ( - options.readPreference && - !options.readPreference.equals(ReadPreference.primary) - ) { - return new MongoError( - `Read preference in a transaction must be primary, not: ${options.readPreference.mode}` - ); + else { + callback(); } + }); +} +//# sourceMappingURL=message_stream.js.map - // `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; +/***/ 2610: +/***/ ((__unused_webpack_module, exports) => { - const readConcern = - session.transaction.options.readConcern || - session.clientOptions.readConcern; - if (readConcern) { - command.readConcern = readConcern; - } +"use strict"; - if (session.supports.causalConsistency && session.operationTime) { - command.readConcern = command.readConcern || {}; - Object.assign(command.readConcern, { - afterClusterTime: session.operationTime, - }); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConnectionPoolMetrics = void 0; +/** @internal */ +class ConnectionPoolMetrics { + constructor() { + this.txnConnections = 0; + this.cursorConnections = 0; + this.otherConnections = 0; + } + /** + * Mark a connection as pinned for a specific operation. + */ + markPinned(pinType) { + if (pinType === ConnectionPoolMetrics.TXN) { + this.txnConnections += 1; } - } - - function updateSessionFromResponse(session, document) { - if (document.$clusterTime) { - resolveClusterTime(session, document.$clusterTime); + else if (pinType === ConnectionPoolMetrics.CURSOR) { + this.cursorConnections += 1; } - - if ( - document.operationTime && - session && - session.supports.causalConsistency - ) { - session.advanceOperationTime(document.operationTime); + else { + this.otherConnections += 1; } - - if (document.recoveryToken && session && session.inTransaction()) { - session.transaction._recoveryToken = document.recoveryToken; + } + /** + * Unmark a connection as pinned for an operation. + */ + markUnpinned(pinType) { + if (pinType === ConnectionPoolMetrics.TXN) { + this.txnConnections -= 1; } - } - - module.exports = { - ClientSession, - ServerSession, - ServerSessionPool, - TxnState, - applySession, - updateSessionFromResponse, - commandSupportsReadConcern, - }; - - /***/ - }, - - /***/ 8175: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const inherits = __nccwpck_require__(1669).inherits; - const f = __nccwpck_require__(1669).format; - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const CoreCursor = __nccwpck_require__(4847).CoreCursor; - const Logger = __nccwpck_require__(104); - const retrieveBSON = __nccwpck_require__(7746).retrieveBSON; - const MongoError = __nccwpck_require__(3111).MongoError; - const Server = __nccwpck_require__(6495); - const diff = __nccwpck_require__(2306).diff; - const cloneOptions = __nccwpck_require__(2306).cloneOptions; - const SessionMixins = __nccwpck_require__(2306).SessionMixins; - const isRetryableWritesSupported = - __nccwpck_require__(2306).isRetryableWritesSupported; - const relayEvents = __nccwpck_require__(1178).relayEvents; - const BSON = retrieveBSON(); - const getMMAPError = __nccwpck_require__(2306).getMMAPError; - const makeClientMetadata = __nccwpck_require__(1178).makeClientMetadata; - const legacyIsRetryableWriteError = - __nccwpck_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 - ) - ); + else if (pinType === ConnectionPoolMetrics.CURSOR) { + this.cursorConnections -= 1; } - } - - // - // 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.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @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; + else { + this.otherConnections -= 1; + } + } + /** + * Return information about the cmap metrics as a string. + */ + info(maxPoolSize) { + return ('Timed out while checking out a connection from connection pool: ' + + `maxPoolSize: ${maxPoolSize}, ` + + `connections in use by cursors: ${this.cursorConnections}, ` + + `connections in use by transactions: ${this.txnConnections}, ` + + `connections in use by other operations: ${this.otherConnections}`); + } + /** + * Reset the metrics to the initial values. + */ + reset() { + this.txnConnections = 0; + this.cursorConnections = 0; + this.otherConnections = 0; + } +} +exports.ConnectionPoolMetrics = ConnectionPoolMetrics; +ConnectionPoolMetrics.TXN = 'txn'; +ConnectionPoolMetrics.CURSOR = 'cursor'; +ConnectionPoolMetrics.OTHER = 'other'; +//# sourceMappingURL=metrics.js.map + +/***/ }), + +/***/ 6292: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.StreamDescription = void 0; +const server_description_1 = __nccwpck_require__(9753); +const common_1 = __nccwpck_require__(472); +const RESPONSE_FIELDS = [ + 'minWireVersion', + 'maxWireVersion', + 'maxBsonObjectSize', + 'maxMessageSizeBytes', + 'maxWriteBatchSize', + 'logicalSessionTimeoutMinutes' +]; +/** @public */ +class StreamDescription { + constructor(address, options) { + this.address = address; + this.type = common_1.ServerType.Unknown; + this.minWireVersion = undefined; + this.maxWireVersion = undefined; + this.maxBsonObjectSize = 16777216; + this.maxMessageSizeBytes = 48000000; + this.maxWriteBatchSize = 100000; + this.logicalSessionTimeoutMinutes = options === null || options === void 0 ? void 0 : options.logicalSessionTimeoutMinutes; + this.loadBalanced = !!(options === null || options === void 0 ? void 0 : options.loadBalanced); + this.compressors = + options && options.compressors && Array.isArray(options.compressors) + ? options.compressors + : []; + } + receiveResponse(response) { + this.type = (0, server_description_1.parseServerType)(response); + for (const field of RESPONSE_FIELDS) { + if (response[field] != null) { + this[field] = response[field]; + } + // testing case + if ('__nodejs_mock_server__' in response) { + this.__nodejs_mock_server__ = response['__nodejs_mock_server__']; } - - 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 - ) - ); + if (response.compression) { + this.compressor = this.compressors.filter(c => { var _a; return (_a = response.compression) === null || _a === void 0 ? void 0 : _a.includes(c); })[0]; } - - // 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); + } +} +exports.StreamDescription = StreamDescription; +//# sourceMappingURL=stream_description.js.map + +/***/ }), + +/***/ 807: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.decompress = exports.compress = exports.uncompressibleCommands = exports.Compressor = void 0; +const zlib = __nccwpck_require__(8761); +const deps_1 = __nccwpck_require__(6763); +const error_1 = __nccwpck_require__(9386); +/** @public */ +exports.Compressor = Object.freeze({ + none: 0, + snappy: 1, + zlib: 2 +}); +exports.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) { + const zlibOptions = {}; + switch (self.options.agreedCompressor) { + case 'snappy': { + if ('kModuleError' in deps_1.Snappy) { + return callback(deps_1.Snappy['kModuleError']); + } + if (deps_1.Snappy[deps_1.PKG_VERSION].major <= 6) { + deps_1.Snappy.compress(dataToBeCompressed, callback); + } + else { + deps_1.Snappy.compress(dataToBeCompressed) + .then(buffer => callback(undefined, buffer)) + .catch(error => callback(error)); + } + break; } - } - - 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); + case 'zlib': + // Determine zlibCompressionLevel + if (self.options.zlibCompressionLevel) { + zlibOptions.level = self.options.zlibCompressionLevel; } - } 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") - ); + zlib.deflate(dataToBeCompressed, zlibOptions, callback); + break; + default: + throw new error_1.MongoInvalidArgumentError(`Unknown compressor ${self.options.agreedCompressor} failed to compress`); + } +} +exports.compress = compress; +// Decompress a message using the given compressor +function decompress(compressorID, compressedData, callback) { + if (compressorID < 0 || compressorID > Math.max(2)) { + throw new error_1.MongoDecompressionError(`Server sent message compressed using an unsupported compressor. (Received compressor ID ${compressorID})`); + } + switch (compressorID) { + case exports.Compressor.snappy: { + if ('kModuleError' in deps_1.Snappy) { + return callback(deps_1.Snappy['kModuleError']); } - - // Topology monitor - topologyMonitor(self, { firstConnect: true }); - } + if (deps_1.Snappy[deps_1.PKG_VERSION].major <= 6) { + deps_1.Snappy.uncompress(compressedData, { asBuffer: true }, callback); + } + else { + deps_1.Snappy.uncompress(compressedData, { asBuffer: true }) + .then(buffer => callback(undefined, buffer)) + .catch(error => callback(error)); + } + break; + } + case exports.Compressor.zlib: + zlib.inflate(compressedData, callback); + break; + default: + callback(undefined, compressedData); + } +} +exports.decompress = decompress; +//# sourceMappingURL=compression.js.map + +/***/ }), + +/***/ 6042: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.OP_MSG = exports.OP_COMPRESSED = exports.OP_KILL_CURSORS = exports.OP_DELETE = exports.OP_GETMORE = exports.OP_QUERY = exports.OP_INSERT = exports.OP_UPDATE = exports.OP_REPLY = exports.MAX_SUPPORTED_WIRE_VERSION = exports.MIN_SUPPORTED_WIRE_VERSION = exports.MAX_SUPPORTED_SERVER_VERSION = exports.MIN_SUPPORTED_SERVER_VERSION = void 0; +exports.MIN_SUPPORTED_SERVER_VERSION = '3.6'; +exports.MAX_SUPPORTED_SERVER_VERSION = '5.1'; +exports.MIN_SUPPORTED_WIRE_VERSION = 6; +exports.MAX_SUPPORTED_WIRE_VERSION = 14; +exports.OP_REPLY = 1; +exports.OP_UPDATE = 2001; +exports.OP_INSERT = 2002; +exports.OP_QUERY = 2004; +exports.OP_GETMORE = 2005; +exports.OP_DELETE = 2006; +exports.OP_KILL_CURSORS = 2007; +exports.OP_COMPRESSED = 2012; +exports.OP_MSG = 2013; +//# sourceMappingURL=constants.js.map + +/***/ }), + +/***/ 1580: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isSharded = exports.applyCommonQueryOptions = exports.getReadPreference = void 0; +const common_1 = __nccwpck_require__(472); +const topology_description_1 = __nccwpck_require__(5645); +const error_1 = __nccwpck_require__(9386); +const read_preference_1 = __nccwpck_require__(9802); +function getReadPreference(cmd, options) { + // Default to command version of the readPreference + let readPreference = cmd.readPreference || read_preference_1.ReadPreference.primary; + // If we have an option readPreference override the command one + if (options === null || options === void 0 ? void 0 : options.readPreference) { + readPreference = options.readPreference; + } + if (typeof readPreference === 'string') { + readPreference = read_preference_1.ReadPreference.fromString(readPreference); + } + if (!(readPreference instanceof read_preference_1.ReadPreference)) { + throw new error_1.MongoInvalidArgumentError('Option "readPreference" must be a ReadPreference instance'); + } + return readPreference; +} +exports.getReadPreference = getReadPreference; +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, + bsonRegExp: typeof options.bsonRegExp === 'boolean' ? options.bsonRegExp : false + }); + if (options.session) { + queryOptions.session = options.session; + } + return queryOptions; +} +exports.applyCommonQueryOptions = applyCommonQueryOptions; +function isSharded(topologyOrServer) { + if (topologyOrServer.description && topologyOrServer.description.type === common_1.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 topology_description_1.TopologyDescription) { + const servers = Array.from(topologyOrServer.description.servers.values()); + return servers.some((server) => server.type === common_1.ServerType.Mongos); + } + return false; +} +exports.isSharded = isSharded; +//# sourceMappingURL=shared.js.map + +/***/ }), + +/***/ 5193: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Collection = void 0; +const utils_1 = __nccwpck_require__(1371); +const read_preference_1 = __nccwpck_require__(9802); +const utils_2 = __nccwpck_require__(1371); +const bson_1 = __nccwpck_require__(5578); +const error_1 = __nccwpck_require__(9386); +const unordered_1 = __nccwpck_require__(325); +const ordered_1 = __nccwpck_require__(5035); +const change_stream_1 = __nccwpck_require__(1117); +const write_concern_1 = __nccwpck_require__(2481); +const read_concern_1 = __nccwpck_require__(7289); +const aggregation_cursor_1 = __nccwpck_require__(3363); +const bulk_write_1 = __nccwpck_require__(6976); +const count_documents_1 = __nccwpck_require__(5131); +const indexes_1 = __nccwpck_require__(4218); +const distinct_1 = __nccwpck_require__(6469); +const drop_1 = __nccwpck_require__(2360); +const estimated_document_count_1 = __nccwpck_require__(4451); +const find_and_modify_1 = __nccwpck_require__(711); +const insert_1 = __nccwpck_require__(4179); +const update_1 = __nccwpck_require__(1134); +const delete_1 = __nccwpck_require__(5831); +const is_capped_1 = __nccwpck_require__(4956); +const map_reduce_1 = __nccwpck_require__(2779); +const options_operation_1 = __nccwpck_require__(43); +const rename_1 = __nccwpck_require__(2808); +const stats_1 = __nccwpck_require__(968); +const execute_operation_1 = __nccwpck_require__(2548); +const find_cursor_1 = __nccwpck_require__(3930); +/** + * 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** + * @public + * + * @example + * ```js + * 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) { + * expect(err).to.not.exist; + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * ``` + */ +class Collection { + /** + * Create a new Collection instance + * @internal + */ + constructor(db, name, options) { + var _a, _b; + (0, utils_2.checkCollectionName)(name); + // Internal state + this.s = { + db, + options, + namespace: new utils_2.MongoDBNamespace(db.databaseName, name), + pkFactory: (_b = (_a = db.options) === null || _a === void 0 ? void 0 : _a.pkFactory) !== null && _b !== void 0 ? _b : utils_1.DEFAULT_PK_FACTORY, + readPreference: read_preference_1.ReadPreference.fromOptions(options), + bsonOptions: (0, bson_1.resolveBSONOptions)(options, db), + readConcern: read_concern_1.ReadConcern.fromOptions(options), + writeConcern: write_concern_1.WriteConcern.fromOptions(options), + slaveOk: options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk }; - } - - 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); + } + /** + * The name of the database this collection belongs to + */ + get dbName() { + return this.s.namespace.db; + } + /** + * The name of this collection + */ + get collectionName() { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return this.s.namespace.collection; + } + /** + * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` + */ + get namespace() { + 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 + */ + get readConcern() { + if (this.s.readConcern == null) { + return this.s.db.readConcern; } - - // Start all the servers - servers.forEach((server) => connect(server, timeoutInterval++)); - } - - function pickProxy(self, session) { - // TODO: Destructure :) - const transaction = session && session.transaction; - - if (transaction && transaction.server) { - if (transaction.server.isConnected()) { - return transaction.server; - } else { - transaction.unpinServer(); - } + return this.s.readConcern; + } + /** + * The current readPreference of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get readPreference() { + if (this.s.readPreference == null) { + return this.s.db.readPreference; } - - // 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; - } + return this.s.readPreference; + } + get bsonOptions() { + return this.s.bsonOptions; + } + /** + * The current writeConcern of the collection. If not explicitly defined for + * this collection, will be inherited from the parent DB + */ + get writeConcern() { + if (this.s.writeConcern == null) { + return this.s.db.writeConcern; } - - // 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; + return this.s.writeConcern; + } + /** The current index hint for the collection */ + get hint() { + return this.s.collectionHint; + } + set hint(v) { + this.s.collectionHint = (0, utils_2.normalizeHintField)(v); + } + insertOne(doc, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; } - - if ( - transaction && - transaction.isActive && - proxy && - proxy.isConnected() - ) { - transaction.pinServer(proxy); + // CSFLE passes in { w: 'majority' } to ensure the lib works in both 3.x and 4.x + // we support that option style here only + if (options && Reflect.get(options, 'w')) { + options.writeConcern = write_concern_1.WriteConcern.fromOptions(Reflect.get(options, 'w')); + } + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new insert_1.InsertOneOperation(this, doc, (0, utils_1.resolveOptions)(this, options)), callback); + } + insertMany(docs, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options ? Object.assign({}, options) : { ordered: true }; + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new insert_1.InsertManyOperation(this, docs, (0, utils_1.resolveOptions)(this, options)), callback); + } + bulkWrite(operations, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options || { ordered: true }; + if (!Array.isArray(operations)) { + throw new error_1.MongoInvalidArgumentError('Argument "operations" must be an array of documents'); + } + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new bulk_write_1.BulkWriteOperation(this, operations, (0, utils_1.resolveOptions)(this, options)), callback); + } + updateOne(filter, update, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new update_1.UpdateOneOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)), callback); + } + replaceOne(filter, replacement, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new update_1.ReplaceOneOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options)), callback); + } + updateMany(filter, update, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new update_1.UpdateManyOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)), callback); + } + deleteOne(filter, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new delete_1.DeleteOneOperation(this, filter, (0, utils_1.resolveOptions)(this, options)), callback); + } + deleteMany(filter, options, callback) { + if (filter == null) { + filter = {}; + options = {}; + callback = undefined; + } + else if (typeof filter === 'function') { + callback = filter; + filter = {}; + options = {}; + } + else if (typeof options === 'function') { + callback = options; + options = {}; + } + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new delete_1.DeleteManyOperation(this, filter, (0, utils_1.resolveOptions)(this, options)), callback); + } + rename(newName, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + // Intentionally, we do not inherit options from parent for this operation. + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new rename_1.RenameOperation(this, newName, { + ...options, + readPreference: read_preference_1.ReadPreference.PRIMARY + }), callback); + } + drop(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new drop_1.DropCollectionOperation(this.s.db, this.collectionName, options), callback); + } + findOne(filter, options, callback) { + if (callback != null && typeof callback !== 'function') { + throw new error_1.MongoInvalidArgumentError('Third parameter to `findOne()` must be a callback or undefined'); + } + if (typeof filter === 'function') { + callback = filter; + filter = {}; + options = {}; + } + if (typeof options === 'function') { + callback = options; + options = {}; } - - // 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); - } + const finalFilter = filter !== null && filter !== void 0 ? filter : {}; + const finalOptions = options !== null && options !== void 0 ? options : {}; + return this.find(finalFilter, finalOptions).limit(-1).batchSize(1).next(callback); + } + find(filter, options) { + if (arguments.length > 2) { + throw new error_1.MongoInvalidArgumentError('Method "collection.find()" accepts at most two arguments'); } - - for (i = 0; i < to.length; i++) { - if (to[i].name === proxy.name) { - to.splice(i, 1); - } + if (typeof options === 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "options" must not be function'); } - - 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); - } + return new find_cursor_1.FindCursor((0, utils_2.getTopology)(this), this.s.namespace, filter, (0, utils_1.resolveOptions)(this, options)); + } + options(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new options_operation_1.OptionsOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); + } + isCapped(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new is_capped_1.IsCappedOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); + } + createIndex(indexSpec, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new indexes_1.CreateIndexOperation(this, this.collectionName, indexSpec, (0, utils_1.resolveOptions)(this, options)), callback); + } + createIndexes(indexSpecs, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options ? Object.assign({}, options) : {}; + if (typeof options.maxTimeMS !== 'number') + delete options.maxTimeMS; + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new indexes_1.CreateIndexesOperation(this, this.collectionName, indexSpecs, (0, utils_1.resolveOptions)(this, options)), callback); + } + dropIndex(indexName, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = (0, utils_1.resolveOptions)(this, options); + // Run only against primary + options.readPreference = read_preference_1.ReadPreference.primary; + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new indexes_1.DropIndexOperation(this, indexName, options), callback); + } + dropIndexes(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new indexes_1.DropIndexesOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); + } + /** + * Get the list of all indexes information for the collection. + * + * @param options - Optional settings for the command + */ + listIndexes(options) { + return new indexes_1.ListIndexesCursor(this, (0, utils_1.resolveOptions)(this, options)); + } + indexExists(indexes, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new indexes_1.IndexExistsOperation(this, indexes, (0, utils_1.resolveOptions)(this, options)), callback); + } + indexInformation(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new indexes_1.IndexInformationOperation(this.s.db, this.collectionName, (0, utils_1.resolveOptions)(this, options)), callback); + } + estimatedDocumentCount(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new estimated_document_count_1.EstimatedDocumentCountOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); + } + countDocuments(filter, options, callback) { + if (filter == null) { + (filter = {}), (options = {}), (callback = undefined); } - } - - 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(); + else if (typeof filter === 'function') { + (callback = filter), (filter = {}), (options = {}); + } + else { + if (arguments.length === 2) { + if (typeof options === 'function') + (callback = options), (options = {}); } - }; - }; - - // 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; + filter !== null && filter !== void 0 ? filter : (filter = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new count_documents_1.CountDocumentsOperation(this, filter, (0, utils_1.resolveOptions)(this, options)), callback); + } + // Implementation + distinct(key, filter, options, callback) { + if (typeof filter === 'function') { + (callback = filter), (filter = {}), (options = {}); + } + else { + if (arguments.length === 3 && typeof options === 'function') { + (callback = options), (options = {}); } - - // 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); + filter !== null && filter !== void 0 ? filter : (filter = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new distinct_1.DistinctOperation(this, key, filter, (0, utils_1.resolveOptions)(this, options)), callback); + } + indexes(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new indexes_1.IndexesOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); + } + stats(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new stats_1.CollStatsOperation(this, options), callback); + } + findOneAndDelete(filter, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new find_and_modify_1.FindOneAndDeleteOperation(this, filter, (0, utils_1.resolveOptions)(this, options)), callback); + } + findOneAndReplace(filter, replacement, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new find_and_modify_1.FindOneAndReplaceOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options)), callback); + } + findOneAndUpdate(filter, update, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new find_and_modify_1.FindOneAndUpdateOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)), callback); + } + /** + * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2 + * + * @param pipeline - An array of aggregation pipelines to execute + * @param options - Optional settings for the command + */ + aggregate(pipeline = [], options) { + if (arguments.length > 2) { + throw new error_1.MongoInvalidArgumentError('Method "collection.aggregate()" accepts at most two arguments'); } - } - - 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; + if (!Array.isArray(pipeline)) { + throw new error_1.MongoInvalidArgumentError('Argument "pipeline" must be an array of aggregation stages'); } - - // 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 = {}; + if (typeof options === 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "options" must not be function'); } - - options = options || {}; - - stateTransition(this, DESTROYING); - if (this.haTimeoutId) { - clearTimeout(this.haTimeoutId); + return new aggregation_cursor_1.AggregationCursor((0, utils_2.getTopology)(this), this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options)); + } + /** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * + * @since 3.0.0 + * @param 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 options - Optional settings for the command + */ + watch(pipeline = [], options = {}) { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; } - - 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; + return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options)); + } + mapReduce(map, reduce, options, callback) { + (0, utils_1.emitWarningOnce)('collection.mapReduce is deprecated. Use the aggregation pipeline instead. Visit https://docs.mongodb.com/manual/reference/map-reduce-to-aggregation-pipeline for more information on how to translate map-reduce operations to the aggregation pipeline.'); + if ('function' === typeof options) + (callback = options), (options = {}); + // Out must always be defined (make sure we don't break weirdly on pre 1.8+ servers) + // TODO NODE-3339: Figure out if this is still necessary given we no longer officially support pre-1.8 + if ((options === null || options === void 0 ? void 0 : options.out) == null) { + throw new error_1.MongoInvalidArgumentError('Option "out" must be defined, see mongodb docs for possible values'); } - - // 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: 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() && - options.explain === undefined; - - 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; + if ('function' === typeof map) { + map = map.toString(); } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; + if ('function' === typeof reduce) { + reduce = reduce.toString(); } - - // 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 ('function' === typeof options.finalize) { + options.finalize = options.finalize.toString(); } - - if (this.state === DESTROYED) { - return callback(new MongoError(f("topology was destroyed"))); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new map_reduce_1.MapReduceOperation(this, map, reduce, (0, utils_1.resolveOptions)(this, options)), callback); + } + /** Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. */ + initializeUnorderedBulkOp(options) { + return new unordered_1.UnorderedBulkOperation(this, (0, utils_1.resolveOptions)(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. */ + initializeOrderedBulkOp(options) { + return new ordered_1.OrderedBulkOperation(this, (0, utils_1.resolveOptions)(this, options)); + } + /** Get the db scoped logger */ + getLogger() { + return this.s.db.s.logger; + } + get logger() { + return this.s.db.s.logger; + } + /** + * 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. + * + * @deprecated Use insertOne, insertMany or bulkWrite instead. + * @param docs - The documents to insert + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + insert(docs, options, callback) { + (0, utils_1.emitWarningOnce)('collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.'); + if (typeof options === 'function') + (callback = options), (options = {}); + options = options || { ordered: false }; + docs = !Array.isArray(docs) ? [docs] : docs; + if (options.keepGoing === true) { + options.ordered = false; } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add( - "insert", - ns, - ops, - options, - callback - ); + return this.insertMany(docs, options, callback); + } + /** + * Updates documents. + * + * @deprecated use updateOne, updateMany or bulkWrite + * @param selector - The selector for the update operation. + * @param update - The update operations to be applied to the documents + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + update(selector, update, options, callback) { + (0, utils_1.emitWarningOnce)('collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.'); + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.updateMany(selector, update, options, callback); + } + /** + * Remove documents. + * + * @deprecated use deleteOne, deleteMany or bulkWrite + * @param selector - The selector for the update operation. + * @param options - Optional settings for the command + * @param callback - An optional callback, a Promise will be returned if none is provided + */ + remove(selector, options, callback) { + (0, utils_1.emitWarningOnce)('collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.'); + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.deleteMany(selector, options, callback); + } + count(filter, options, callback) { + if (typeof filter === 'function') { + (callback = filter), (filter = {}), (options = {}); } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError("no mongos proxy available")); + else { + if (typeof options === 'function') + (callback = options), (options = {}); } - - // 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 - ); + filter !== null && filter !== void 0 ? filter : (filter = {}); + return (0, execute_operation_1.executeOperation)((0, utils_2.getTopology)(this), new count_documents_1.CountDocumentsOperation(this, filter, (0, utils_1.resolveOptions)(this, options)), callback); + } +} +exports.Collection = Collection; +//# sourceMappingURL=collection.js.map + +/***/ }), + +/***/ 5341: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DEFAULT_OPTIONS = exports.OPTIONS = exports.parseOptions = exports.checkTLSOptions = exports.resolveSRVRecord = void 0; +const dns = __nccwpck_require__(881); +const fs = __nccwpck_require__(5747); +const mongodb_connection_string_url_1 = __nccwpck_require__(4927); +const url_1 = __nccwpck_require__(8835); +const defaultAuthProviders_1 = __nccwpck_require__(7162); +const read_preference_1 = __nccwpck_require__(9802); +const read_concern_1 = __nccwpck_require__(7289); +const write_concern_1 = __nccwpck_require__(2481); +const error_1 = __nccwpck_require__(9386); +const utils_1 = __nccwpck_require__(1371); +const mongo_client_1 = __nccwpck_require__(1545); +const mongo_credentials_1 = __nccwpck_require__(4418); +const logger_1 = __nccwpck_require__(8874); +const promise_provider_1 = __nccwpck_require__(2725); +const encrypter_1 = __nccwpck_require__(3012); +const compression_1 = __nccwpck_require__(807); +const VALID_TXT_RECORDS = ['authSource', 'replicaSet', 'loadBalanced']; +const LB_SINGLE_HOST_ERROR = 'loadBalanced option only supported with a single host in the URI'; +const LB_REPLICA_SET_ERROR = 'loadBalanced option not supported with a replicaSet option'; +const LB_DIRECT_CONNECTION_ERROR = 'loadBalanced option not supported when directConnection is provided'; +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param srvAddress - The address to check against a domain + * @param parentDomain - The domain to check the provided address against + * @returns 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 uri - The connection string to parse + * @param options - Optional user provided connection string options + */ +function resolveSRVRecord(options, callback) { + if (typeof options.srvHost !== 'string') { + return callback(new error_1.MongoAPIError('Option "srvHost" must not be empty')); + } + if (options.srvHost.split('.').length < 3) { + // TODO(NODE-3484): Replace with MongoConnectionStringError + return callback(new error_1.MongoAPIError('URI must include hostname, domain name, and tld')); + } + // Resolve the SRV record and use the result as the list of hosts to connect to. + const lookupAddress = options.srvHost; + dns.resolveSrv(`_${options.srvServiceName}._tcp.${lookupAddress}`, (err, addresses) => { + if (err) + return callback(err); + if (addresses.length === 0) { + return callback(new error_1.MongoAPIError('No addresses found at host')); } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError("no mongos proxy available")); + for (const { name } of addresses) { + if (!matchesParentDomain(name, lookupAddress)) { + return callback(new error_1.MongoAPIError('Server record does not share hostname with parent URI')); + } } - - // 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 - ); + const hostAddresses = addresses.map(r => { var _a; return utils_1.HostAddress.fromString(`${r.name}:${(_a = r.port) !== null && _a !== void 0 ? _a : 27017}`); }); + const lbError = validateLoadBalancedOptions(hostAddresses, options, true); + if (lbError) { + return callback(lbError); + } + // Resolve TXT record and add options from there if they exist. + dns.resolveTxt(lookupAddress, (err, record) => { + var _a, _b, _c; + if (err) { + if (err.code !== 'ENODATA' && err.code !== 'ENOTFOUND') { + return callback(err); + } + } + else { + if (record.length > 1) { + return callback(new error_1.MongoParseError('Multiple text records not allowed')); + } + const txtRecordOptions = new url_1.URLSearchParams(record[0].join('')); + const txtRecordOptionKeys = [...txtRecordOptions.keys()]; + if (txtRecordOptionKeys.some(key => !VALID_TXT_RECORDS.includes(key))) { + return callback(new error_1.MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(', ')}`)); + } + if (VALID_TXT_RECORDS.some(option => txtRecordOptions.get(option) === '')) { + return callback(new error_1.MongoParseError('Cannot have empty URI params in DNS TXT Record')); + } + const source = (_a = txtRecordOptions.get('authSource')) !== null && _a !== void 0 ? _a : undefined; + const replicaSet = (_b = txtRecordOptions.get('replicaSet')) !== null && _b !== void 0 ? _b : undefined; + const loadBalanced = (_c = txtRecordOptions.get('loadBalanced')) !== null && _c !== void 0 ? _c : undefined; + if (!options.userSpecifiedAuthSource && source) { + options.credentials = mongo_credentials_1.MongoCredentials.merge(options.credentials, { source }); + } + if (!options.userSpecifiedReplicaSet && replicaSet) { + options.replicaSet = replicaSet; + } + if (loadBalanced === 'true') { + options.loadBalanced = true; + } + if (options.replicaSet && options.srvMaxHosts > 0) { + return callback(new error_1.MongoParseError('Cannot combine replicaSet option with srvMaxHosts')); + } + const lbError = validateLoadBalancedOptions(hostAddresses, options, true); + if (lbError) { + return callback(lbError); + } + } + callback(undefined, hostAddresses); + }); + }); +} +exports.resolveSRVRecord = resolveSRVRecord; +/** + * Checks if TLS options are valid + * + * @param options - The options used for options parsing + * @throws MongoParseError if TLS options are invalid + */ +function checkTLSOptions(options) { + if (!options) + return; + const check = (a, b) => { + if (Reflect.has(options, a) && Reflect.has(options, b)) { + throw new error_1.MongoParseError(`The '${a}' option cannot be used with '${b}'`); + } + }; + check('tlsInsecure', 'tlsAllowInvalidCertificates'); + check('tlsInsecure', 'tlsAllowInvalidHostnames'); + check('tlsInsecure', 'tlsDisableCertificateRevocationCheck'); + check('tlsInsecure', 'tlsDisableOCSPEndpointCheck'); + check('tlsAllowInvalidCertificates', 'tlsDisableCertificateRevocationCheck'); + check('tlsAllowInvalidCertificates', 'tlsDisableOCSPEndpointCheck'); + check('tlsDisableCertificateRevocationCheck', 'tlsDisableOCSPEndpointCheck'); +} +exports.checkTLSOptions = checkTLSOptions; +const TRUTHS = new Set(['true', 't', '1', 'y', 'yes']); +const FALSEHOODS = new Set(['false', 'f', '0', 'n', 'no', '-1']); +function getBoolean(name, value) { + if (typeof value === 'boolean') + return value; + const valueString = String(value).toLowerCase(); + if (TRUTHS.has(valueString)) + return true; + if (FALSEHOODS.has(valueString)) + return false; + throw new error_1.MongoParseError(`Expected ${name} to be stringified boolean value, got: ${value}`); +} +function getInt(name, value) { + if (typeof value === 'number') + return Math.trunc(value); + const parsedValue = Number.parseInt(String(value), 10); + if (!Number.isNaN(parsedValue)) + return parsedValue; + throw new error_1.MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`); +} +function getUint(name, value) { + const parsedValue = getInt(name, value); + if (parsedValue < 0) { + throw new error_1.MongoParseError(`${name} can only be a positive int value, got: ${value}`); + } + return parsedValue; +} +function toRecord(value) { + const record = Object.create(null); + const keyValuePairs = value.split(','); + for (const keyValue of keyValuePairs) { + const [key, value] = keyValue.split(':'); + if (value == null) { + throw new error_1.MongoParseError('Cannot have undefined values in key value pairs'); + } + try { + // try to get a boolean + record[key] = getBoolean('', value); } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError("no mongos proxy available")); + catch { + try { + // try to get a number + record[key] = getInt('', value); + } + catch { + // keep value as a string + record[key] = value; + } } - - // 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 || {}); + } + return record; +} +class CaseInsensitiveMap extends Map { + constructor(entries = []) { + super(entries.map(([k, v]) => [k.toLowerCase(), v])); + } + has(k) { + return super.has(k.toLowerCase()); + } + get(k) { + return super.get(k.toLowerCase()); + } + set(k, v) { + return super.set(k.toLowerCase(), v); + } + delete(k) { + return super.delete(k.toLowerCase()); + } +} +function parseOptions(uri, mongoClient = undefined, options = {}) { + if (mongoClient != null && !(mongoClient instanceof mongo_client_1.MongoClient)) { + options = mongoClient; + mongoClient = undefined; + } + const url = new mongodb_connection_string_url_1.default(uri); + const { hosts, isSRV } = url; + const mongoOptions = Object.create(null); + mongoOptions.hosts = isSRV ? [] : hosts.map(utils_1.HostAddress.fromString); + const urlOptions = new CaseInsensitiveMap(); + if (url.pathname !== '/' && url.pathname !== '') { + const dbName = decodeURIComponent(url.pathname[0] === '/' ? url.pathname.slice(1) : url.pathname); + if (dbName) { + urlOptions.set('dbName', [dbName]); } - - if (this.state === DESTROYED) { - return callback(new MongoError(f("topology was destroyed"))); + } + if (url.username !== '') { + const auth = { + username: decodeURIComponent(url.username) + }; + if (typeof url.password === 'string') { + auth.password = decodeURIComponent(url.password); } - - 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 - ); + urlOptions.set('auth', [auth]); + } + for (const key of url.searchParams.keys()) { + const values = [...url.searchParams.getAll(key)]; + if (values.includes('')) { + throw new error_1.MongoAPIError('URI cannot contain options with no value'); } - - // No server returned we had an error - if (server == null) { - return callback(new MongoError("no mongos proxy available")); + if (!urlOptions.has(key)) { + urlOptions.set(key, values); } - - // 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, + } + const objectOptions = new CaseInsensitiveMap(Object.entries(options).filter(([, v]) => v != null)); + // Validate options that can only be provided by one of uri or object + if (urlOptions.has('serverApi')) { + throw new error_1.MongoParseError('URI cannot contain `serverApi`, it can only be passed to the client'); + } + if (objectOptions.has('loadBalanced')) { + throw new error_1.MongoParseError('loadBalanced is only a valid option in the URI'); + } + // All option collection + const allOptions = new CaseInsensitiveMap(); + const allKeys = new Set([ + ...urlOptions.keys(), + ...objectOptions.keys(), + ...exports.DEFAULT_OPTIONS.keys() + ]); + for (const key of allKeys) { + const values = []; + if (objectOptions.has(key)) { + values.push(objectOptions.get(key)); + } + if (urlOptions.has(key)) { + values.push(...urlOptions.get(key)); + } + if (exports.DEFAULT_OPTIONS.has(key)) { + values.push(exports.DEFAULT_OPTIONS.get(key)); + } + allOptions.set(key, values); + } + if (allOptions.has('tlsCertificateKeyFile') && !allOptions.has('tlsCertificateFile')) { + allOptions.set('tlsCertificateFile', allOptions.get('tlsCertificateKeyFile')); + } + if (allOptions.has('tls') || allOptions.has('ssl')) { + const tlsAndSslOpts = (allOptions.get('tls') || []) + .concat(allOptions.get('ssl') || []) + .map(getBoolean.bind(null, 'tls/ssl')); + if (new Set(tlsAndSslOpts).size !== 1) { + throw new error_1.MongoParseError('All values of tls/ssl must be the same.'); + } + } + const unsupportedOptions = (0, utils_1.setDifference)(allKeys, Array.from(Object.keys(exports.OPTIONS)).map(s => s.toLowerCase())); + if (unsupportedOptions.size !== 0) { + const optionWord = unsupportedOptions.size > 1 ? 'options' : 'option'; + const isOrAre = unsupportedOptions.size > 1 ? 'are' : 'is'; + throw new error_1.MongoParseError(`${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported`); + } + // Option parsing and setting + for (const [key, descriptor] of Object.entries(exports.OPTIONS)) { + const values = allOptions.get(key); + if (!values || values.length === 0) + continue; + setOption(mongoOptions, key, descriptor, values); + } + if (mongoOptions.credentials) { + const isGssapi = mongoOptions.credentials.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_GSSAPI; + const isX509 = mongoOptions.credentials.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_X509; + const isAws = mongoOptions.credentials.mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_AWS; + if ((isGssapi || isX509) && + allOptions.has('authSource') && + mongoOptions.credentials.source !== '$external') { + // If authSource was explicitly given and its incorrect, we error + throw new error_1.MongoParseError(`${mongoOptions.credentials} can only have authSource set to '$external'`); + } + if (!(isGssapi || isX509 || isAws) && mongoOptions.dbName && !allOptions.has('authSource')) { + // inherit the dbName unless GSSAPI or X509, then silently ignore dbName + // and there was no specific authSource given + mongoOptions.credentials = mongo_credentials_1.MongoCredentials.merge(mongoOptions.credentials, { + source: mongoOptions.dbName }); - 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; + mongoOptions.credentials.validate(); + } + if (!mongoOptions.dbName) { + // dbName default is applied here because of the credential validation above + mongoOptions.dbName = 'test'; + } + checkTLSOptions(mongoOptions); + if (options.promiseLibrary) + promise_provider_1.PromiseProvider.set(options.promiseLibrary); + const lbError = validateLoadBalancedOptions(hosts, mongoOptions, isSRV); + if (lbError) { + throw lbError; + } + if (mongoClient && mongoOptions.autoEncryption) { + encrypter_1.Encrypter.checkForMongoCrypt(); + mongoOptions.encrypter = new encrypter_1.Encrypter(mongoClient, uri, options); + mongoOptions.autoEncrypter = mongoOptions.encrypter.autoEncrypter; + } + // Potential SRV Overrides and SRV connection string validations + mongoOptions.userSpecifiedAuthSource = + objectOptions.has('authSource') || urlOptions.has('authSource'); + mongoOptions.userSpecifiedReplicaSet = + objectOptions.has('replicaSet') || urlOptions.has('replicaSet'); + if (isSRV) { + // SRV Record is resolved upon connecting + mongoOptions.srvHost = hosts[0]; + if (mongoOptions.directConnection) { + throw new error_1.MongoAPIError('SRV URI does not support directConnection'); + } + if (mongoOptions.srvMaxHosts > 0 && typeof mongoOptions.replicaSet === 'string') { + throw new error_1.MongoParseError('Cannot use srvMaxHosts option with replicaSet'); + } + // SRV turns on TLS by default, but users can override and turn it off + const noUserSpecifiedTLS = !objectOptions.has('tls') && !urlOptions.has('tls'); + const noUserSpecifiedSSL = !objectOptions.has('ssl') && !urlOptions.has('ssl'); + if (noUserSpecifiedTLS && noUserSpecifiedSSL) { + mongoOptions.tls = true; } - - 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() - ); + } + else { + const userSpecifiedSrvOptions = urlOptions.has('srvMaxHosts') || + objectOptions.has('srvMaxHosts') || + urlOptions.has('srvServiceName') || + objectOptions.has('srvServiceName'); + if (userSpecifiedSrvOptions) { + throw new error_1.MongoParseError('Cannot use srvMaxHosts or srvServiceName with a non-srv connection string'); } - - 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, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const emitWarningOnce = __nccwpck_require__(1371).emitWarningOnce; - - /** - * 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}`); + } + return mongoOptions; +} +exports.parseOptions = parseOptions; +function validateLoadBalancedOptions(hosts, mongoOptions, isSrv) { + if (mongoOptions.loadBalanced) { + if (hosts.length > 1) { + return new error_1.MongoParseError(LB_SINGLE_HOST_ERROR); } - - // TODO(major): tags MUST be an array of tagsets - if (tags && !Array.isArray(tags)) { - emitWarningOnce( - "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]; - } + if (mongoOptions.replicaSet) { + return new error_1.MongoParseError(LB_REPLICA_SET_ERROR); } - - 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 (mongoOptions.directConnection) { + return new error_1.MongoParseError(LB_DIRECT_CONNECTION_ERROR); } - - 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" - ); - } + if (isSrv && mongoOptions.srvMaxHosts > 0) { + return new error_1.MongoParseError('Cannot limit srv hosts with loadBalanced enabled'); } - }; - - // 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, - }); - } + } +} +function setOption(mongoOptions, key, descriptor, values) { + const { target, type, transform, deprecated } = descriptor; + const name = target !== null && target !== void 0 ? target : key; + if (deprecated) { + const deprecatedMsg = typeof deprecated === 'string' ? `: ${deprecated}` : ''; + (0, utils_1.emitWarning)(`${key} is a deprecated option${deprecatedMsg}`); + } + switch (type) { + case 'boolean': + mongoOptions[name] = getBoolean(name, values[0]); + break; + case 'int': + mongoOptions[name] = getInt(name, values[0]); + break; + case 'uint': + mongoOptions[name] = getUint(name, values[0]); + break; + case 'string': + if (values[0] == null) { + break; + } + mongoOptions[name] = String(values[0]); + break; + case 'record': + if (!(0, utils_1.isRecord)(values[0])) { + throw new error_1.MongoParseError(`${name} must be an object`); + } + mongoOptions[name] = values[0]; + break; + case 'any': + mongoOptions[name] = values[0]; + break; + default: { + if (!transform) { + throw new error_1.MongoParseError('Descriptors missing a type must define a transform'); + } + const transformValue = transform({ name, options: mongoOptions, values }); + mongoOptions[name] = transformValue; + break; } - - 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; + } +} +exports.OPTIONS = { + appName: { + target: 'metadata', + transform({ options, values: [value] }) { + return (0, utils_1.makeClientMetadata)({ ...options.driverInfo, appName: String(value) }); } - - 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, + }, + auth: { + target: 'credentials', + transform({ name, options, values: [value] }) { + if (!(0, utils_1.isRecord)(value, ['username', 'password'])) { + throw new error_1.MongoParseError(`${name} must be an object with 'username' and 'password' properties`); + } + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { + username: value.username, + password: value.password }); - } - } 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, - __nccwpck_require__ - ) => { - "use strict"; - - const inherits = __nccwpck_require__(1669).inherits; - const f = __nccwpck_require__(1669).format; - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const ReadPreference = __nccwpck_require__(4485); - const CoreCursor = __nccwpck_require__(4847).CoreCursor; - const retrieveBSON = __nccwpck_require__(7746).retrieveBSON; - const Logger = __nccwpck_require__(104); - const MongoError = __nccwpck_require__(3111).MongoError; - const Server = __nccwpck_require__(6495); - const ReplSetState = __nccwpck_require__(8742); - const Timeout = __nccwpck_require__(2306).Timeout; - const Interval = __nccwpck_require__(2306).Interval; - const SessionMixins = __nccwpck_require__(2306).SessionMixins; - const isRetryableWritesSupported = - __nccwpck_require__(2306).isRetryableWritesSupported; - const relayEvents = __nccwpck_require__(1178).relayEvents; - const BSON = retrieveBSON(); - const getMMAPError = __nccwpck_require__(2306).getMMAPError; - const makeClientMetadata = __nccwpck_require__(1178).makeClientMetadata; - const legacyIsRetryableWriteError = - __nccwpck_require__(2306).legacyIsRetryableWriteError; - const now = __nccwpck_require__(1371).now; - const calculateDurationInMs = - __nccwpck_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 {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @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(); + authMechanism: { + target: 'credentials', + transform({ options, values: [value] }) { + var _a, _b; + const mechanisms = Object.values(defaultAuthProviders_1.AuthMechanism); + const [mechanism] = mechanisms.filter(m => m.match(RegExp(String.raw `\b${value}\b`, 'i'))); + if (!mechanism) { + throw new error_1.MongoParseError(`authMechanism one of ${mechanisms}, got ${value}`); + } + let source = (_a = options.credentials) === null || _a === void 0 ? void 0 : _a.source; + if (mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_PLAIN || + mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_GSSAPI || + mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_AWS || + mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_X509) { + // some mechanisms have '$external' as the Auth Source + source = '$external'; + } + let password = (_b = options.credentials) === null || _b === void 0 ? void 0 : _b.password; + if (mechanism === defaultAuthProviders_1.AuthMechanism.MONGODB_X509 && password === '') { + password = undefined; + } + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { + mechanism, + source, + password + }); } - - // Count lefts - var count = servers.length; - var error = null; - - function done() { - count = count - 1; - if (count === 0) { - callback(error); - } + }, + authMechanismProperties: { + target: 'credentials', + transform({ options, values: [value] }) { + if (typeof value === 'string') { + value = toRecord(value); + } + if (!(0, utils_1.isRecord)(value)) { + throw new error_1.MongoParseError('AuthMechanismProperties must be an object'); + } + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { mechanismProperties: value }); } - - // 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(); + }, + authSource: { + target: 'credentials', + transform({ options, values: [value] }) { + const source = String(value); + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { source }); + } + }, + autoEncryption: { + type: 'record' + }, + bsonRegExp: { + type: 'boolean' + }, + serverApi: { + target: 'serverApi', + transform({ values: [version] }) { + const serverApiToValidate = typeof version === 'string' ? { version } : version; + const versionToValidate = serverApiToValidate && serverApiToValidate.version; + if (!versionToValidate) { + throw new error_1.MongoParseError(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`); } - - 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(); + if (!Object.values(mongo_client_1.ServerApiVersion).some(v => v === versionToValidate)) { + throw new error_1.MongoParseError(`Invalid server API version=${versionToValidate}; must be in the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`); + } + return serverApiToValidate; + } + }, + checkKeys: { + type: 'boolean' + }, + compressors: { + default: 'none', + target: 'compressors', + transform({ values }) { + const compressionList = new Set(); + for (const compVal of values) { + const compValArray = typeof compVal === 'string' ? compVal.split(',') : compVal; + if (!Array.isArray(compValArray)) { + throw new error_1.MongoInvalidArgumentError('compressors must be an array or a comma-delimited list of strings'); } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _self.removeAllListeners(handlers[i]); + for (const c of compValArray) { + if (Object.keys(compression_1.Compressor).includes(String(c))) { + compressionList.add(String(c)); + } + else { + throw new error_1.MongoInvalidArgumentError(`${c} is not a valid compression mechanism. Must be one of: ${Object.keys(compression_1.Compressor)}.`); + } } - - // 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); + return [...compressionList]; } - - // Create new instances - for (var i = 0; i < servers.length; i++) { - execute(servers[i], i); + }, + connectTimeoutMS: { + default: 30000, + type: 'uint' + }, + dbName: { + type: 'string' + }, + directConnection: { + default: false, + type: 'boolean' + }, + driverInfo: { + target: 'metadata', + default: (0, utils_1.makeClientMetadata)(), + transform({ options, values: [value] }) { + var _a, _b; + if (!(0, utils_1.isRecord)(value)) + throw new error_1.MongoParseError('DriverInfo must be an object'); + return (0, utils_1.makeClientMetadata)({ + driverInfo: value, + appName: (_b = (_a = options.metadata) === null || _a === void 0 ? void 0 : _a.application) === null || _b === void 0 ? void 0 : _b.name + }); } - } - - // 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); + }, + family: { + transform({ name, values: [value] }) { + const transformValue = getInt(name, value); + if (transformValue === 4 || transformValue === 6) { + return transformValue; } - - // 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(); + throw new error_1.MongoParseError(`Option 'family' must be 4 or 6 got ${transformValue}.`); + } + }, + fieldsAsRaw: { + type: 'record' + }, + forceServerObjectId: { + default: false, + type: 'boolean' + }, + fsync: { + deprecated: 'Please use journal instead', + target: 'writeConcern', + transform({ name, options, values: [value] }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + fsync: getBoolean(name, value) } - } - - // 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; - } - } + }); + if (!wc) + throw new error_1.MongoParseError(`Unable to make a writeConcern from fsync=${value}`); + return wc; } - - // 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()) - ) { - stateTransition(self, CONNECTED); - - // Emit connected sign - process.nextTick(function () { - self.emit("connect", self); - }); - - // Start topology interval check - topologyMonitor(self, {}); + }, + heartbeatFrequencyMS: { + default: 10000, + type: 'uint' + }, + ignoreUndefined: { + type: 'boolean' + }, + j: { + deprecated: 'Please use journal instead', + target: 'writeConcern', + transform({ name, options, values: [value] }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + journal: getBoolean(name, value) } - } else { - if ( - self.state === DISCONNECTED && - ((self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed) || - self.s.replicaSetState.hasPrimary()) - ) { - stateTransition(self, CONNECTING); - - // Rexecute any stalled operation - rexecuteOperations(self); - - // Emit connected sign - process.nextTick(function () { - self.emit("reconnect", self); - }); + }); + if (!wc) + throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`); + return wc; + } + }, + journal: { + target: 'writeConcern', + transform({ name, options, values: [value] }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + journal: getBoolean(name, value) } - } - - 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); + }); + if (!wc) + throw new error_1.MongoParseError(`Unable to make a writeConcern from journal=${value}`); + return wc; + } + }, + keepAlive: { + default: true, + type: 'boolean' + }, + keepAliveInitialDelay: { + default: 120000, + type: 'uint' + }, + loadBalanced: { + default: false, + type: 'boolean' + }, + localThresholdMS: { + default: 15, + type: 'uint' + }, + logger: { + default: new logger_1.Logger('MongoClient'), + transform({ values: [value] }) { + if (value instanceof logger_1.Logger) { + return value; + } + (0, utils_1.emitWarning)('Alternative loggers might not be supported'); + // TODO: make Logger an interface that others can implement, make usage consistent in driver + // DRIVERS-1204 + } + }, + loggerLevel: { + target: 'logger', + transform({ values: [value] }) { + return new logger_1.Logger('MongoClient', { loggerLevel: value }); + } + }, + maxIdleTimeMS: { + default: 0, + type: 'uint' + }, + maxPoolSize: { + default: 100, + type: 'uint' + }, + maxStalenessSeconds: { + target: 'readPreference', + transform({ name, options, values: [value] }) { + const maxStalenessSeconds = getUint(name, value); + if (options.readPreference) { + return read_preference_1.ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, maxStalenessSeconds } }); - } + } + else { + return new read_preference_1.ReadPreference('secondary', undefined, { maxStalenessSeconds }); + } + } + }, + minInternalBufferSize: { + type: 'uint' + }, + minPoolSize: { + default: 0, + type: 'uint' + }, + minHeartbeatFrequencyMS: { + default: 500, + type: 'uint' + }, + monitorCommands: { + default: false, + type: 'boolean' + }, + name: { + target: 'driverInfo', + transform({ values: [value], options }) { + return { ...options.driverInfo, name: String(value) }; + } + }, + noDelay: { + default: true, + type: 'boolean' + }, + pkFactory: { + default: utils_1.DEFAULT_PK_FACTORY, + transform({ values: [value] }) { + if ((0, utils_1.isRecord)(value, ['createPk']) && typeof value.createPk === 'function') { + return value; + } + throw new error_1.MongoParseError(`Option pkFactory must be an object with a createPk function, got ${value}`); + } + }, + promiseLibrary: { + deprecated: true, + type: 'any' + }, + promoteBuffers: { + type: 'boolean' + }, + promoteLongs: { + type: 'boolean' + }, + promoteValues: { + type: 'boolean' + }, + raw: { + default: false, + type: 'boolean' + }, + readConcern: { + transform({ values: [value], options }) { + if (value instanceof read_concern_1.ReadConcern || (0, utils_1.isRecord)(value, ['level'])) { + return read_concern_1.ReadConcern.fromOptions({ ...options.readConcern, ...value }); + } + throw new error_1.MongoParseError(`ReadConcern must be an object, got ${JSON.stringify(value)}`); + } + }, + readConcernLevel: { + target: 'readConcern', + transform({ values: [level], options }) { + return read_concern_1.ReadConcern.fromOptions({ + ...options.readConcern, + level: level }); - } - }, _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); + } + }, + readPreference: { + default: read_preference_1.ReadPreference.primary, + transform({ values: [value], options }) { + var _a, _b, _c; + if (value instanceof read_preference_1.ReadPreference) { + return read_preference_1.ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, ...value }, + ...value + }); + } + if ((0, utils_1.isRecord)(value, ['mode'])) { + const rp = read_preference_1.ReadPreference.fromOptions({ + readPreference: { ...options.readPreference, ...value }, + ...value + }); + if (rp) + return rp; + else + throw new error_1.MongoParseError(`Cannot make read preference from ${JSON.stringify(value)}`); + } + if (typeof value === 'string') { + const rpOpts = { + hedge: (_a = options.readPreference) === null || _a === void 0 ? void 0 : _a.hedge, + maxStalenessSeconds: (_b = options.readPreference) === null || _b === void 0 ? void 0 : _b.maxStalenessSeconds + }; + return new read_preference_1.ReadPreference(value, (_c = options.readPreference) === null || _c === void 0 ? void 0 : _c.tags, rpOpts); + } + } + }, + readPreferenceTags: { + target: 'readPreference', + transform({ values, options }) { + const readPreferenceTags = []; + for (const tag of values) { + const readPreferenceTag = Object.create(null); + if (typeof tag === 'string') { + for (const [k, v] of Object.entries(toRecord(tag))) { + readPreferenceTag[k] = v; + } } - - 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); + if ((0, utils_1.isRecord)(tag)) { + for (const [k, v] of Object.entries(tag)) { + readPreferenceTag[k] = v; + } } - - 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); - } + readPreferenceTags.push(readPreferenceTag); } - ); - } else { - for (var i = 0; i < servers.length; i++) { - monitorServer(servers[i], self, options); - } + return read_preference_1.ReadPreference.fromOptions({ + readPreference: options.readPreference, + readPreferenceTags + }); } - - // Run the reconnect process - function executeReconnect(self) { - return function () { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; + }, + replicaSet: { + type: 'string' + }, + retryReads: { + default: true, + type: 'boolean' + }, + retryWrites: { + default: true, + type: 'boolean' + }, + serializeFunctions: { + type: 'boolean' + }, + serverSelectionTimeoutMS: { + default: 30000, + type: 'uint' + }, + servername: { + type: 'string' + }, + socketTimeoutMS: { + default: 0, + type: 'uint' + }, + srvMaxHosts: { + type: 'uint', + default: 0 + }, + srvServiceName: { + type: 'string', + default: 'mongodb' + }, + ssl: { + target: 'tls', + type: 'boolean' + }, + sslCA: { + target: 'ca', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslCRL: { + target: 'crl', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslCert: { + target: 'cert', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslKey: { + target: 'key', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + sslPass: { + deprecated: true, + target: 'passphrase', + type: 'string' + }, + sslValidate: { + target: 'rejectUnauthorized', + type: 'boolean' + }, + tls: { + type: 'boolean' + }, + tlsAllowInvalidCertificates: { + target: 'rejectUnauthorized', + transform({ name, values: [value] }) { + // allowInvalidCertificates is the inverse of rejectUnauthorized + return !getBoolean(name, value); + } + }, + tlsAllowInvalidHostnames: { + target: 'checkServerIdentity', + transform({ name, values: [value] }) { + // tlsAllowInvalidHostnames means setting the checkServerIdentity function to a noop + return getBoolean(name, value) ? () => undefined : undefined; + } + }, + tlsCAFile: { + target: 'ca', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + tlsCertificateFile: { + target: 'cert', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + tlsCertificateKeyFile: { + target: 'key', + transform({ values: [value] }) { + return fs.readFileSync(String(value), { encoding: 'ascii' }); + } + }, + tlsCertificateKeyFilePassword: { + target: 'passphrase', + type: 'any' + }, + tlsInsecure: { + transform({ name, options, values: [value] }) { + const tlsInsecure = getBoolean(name, value); + if (tlsInsecure) { + options.checkServerIdentity = () => undefined; + options.rejectUnauthorized = false; + } + else { + options.checkServerIdentity = options.tlsAllowInvalidHostnames + ? () => undefined + : undefined; + options.rejectUnauthorized = options.tlsAllowInvalidCertificates ? false : true; } - - 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() - ); - } - ); - }; + return tlsInsecure; } - - // 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; + }, + w: { + target: 'writeConcern', + transform({ values: [value], options }) { + return write_concern_1.WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, w: value } }); } - - 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 - stateTransition(self, CONNECTED); - - // Set initial connect state - self.initialConnectState.connect = true; - // Emit connect event - process.nextTick(function () { - self.emit("connect", self); + }, + waitQueueTimeoutMS: { + default: 0, + type: 'uint' + }, + writeConcern: { + target: 'writeConcern', + transform({ values: [value], options }) { + if ((0, utils_1.isRecord)(value) || value instanceof write_concern_1.WriteConcern) { + return write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + ...value + } }); - - 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); + else if (value === 'majority' || typeof value === 'number') { + return write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + w: value + } + }); } - } - - // Trigger topologyMonitor - if ( - self.s.connectingServers.length === 0 && - self.state === CONNECTING - ) { - topologyMonitor(self, { haInterval: 1 }); - } + throw new error_1.MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(value)}`); + } + }, + wtimeout: { + deprecated: 'Please use wtimeoutMS instead', + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeout: getUint('wtimeout', value) + } + }); + if (wc) + return wc; + throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`); + } + }, + wtimeoutMS: { + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeoutMS: getUint('wtimeoutMS', value) + } + }); + if (wc) + return wc; + throw new error_1.MongoParseError(`Cannot make WriteConcern from wtimeout`); + } + }, + zlibCompressionLevel: { + default: 0, + type: 'int' + }, + // Custom types for modifying core behavior + connectionType: { type: 'any' }, + srvPoller: { type: 'any' }, + // Accepted NodeJS Options + minDHSize: { type: 'any' }, + pskCallback: { type: 'any' }, + secureContext: { type: 'any' }, + enableTrace: { type: 'any' }, + requestCert: { type: 'any' }, + rejectUnauthorized: { type: 'any' }, + checkServerIdentity: { type: 'any' }, + ALPNProtocols: { type: 'any' }, + SNICallback: { type: 'any' }, + session: { type: 'any' }, + requestOCSP: { type: 'any' }, + localAddress: { type: 'any' }, + localPort: { type: 'any' }, + hints: { type: 'any' }, + lookup: { type: 'any' }, + ca: { type: 'any' }, + cert: { type: 'any' }, + ciphers: { type: 'any' }, + crl: { type: 'any' }, + ecdhCurve: { type: 'any' }, + key: { type: 'any' }, + passphrase: { type: 'any' }, + pfx: { type: 'any' }, + secureProtocol: { type: 'any' }, + index: { type: 'any' }, + // Legacy Options, these are unused but left here to avoid errors with CSFLE lib + useNewUrlParser: { type: 'boolean' }, + useUnifiedTopology: { type: 'boolean' } +}; +exports.DEFAULT_OPTIONS = new CaseInsensitiveMap(Object.entries(exports.OPTIONS) + .filter(([, descriptor]) => descriptor.default != null) + .map(([k, d]) => [k, d.default])); +//# sourceMappingURL=connection_string.js.map + +/***/ }), + +/***/ 147: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SYSTEM_JS_COLLECTION = exports.SYSTEM_COMMAND_COLLECTION = exports.SYSTEM_USER_COLLECTION = exports.SYSTEM_PROFILE_COLLECTION = exports.SYSTEM_INDEX_COLLECTION = exports.SYSTEM_NAMESPACE_COLLECTION = void 0; +exports.SYSTEM_NAMESPACE_COLLECTION = 'system.namespaces'; +exports.SYSTEM_INDEX_COLLECTION = 'system.indexes'; +exports.SYSTEM_PROFILE_COLLECTION = 'system.profile'; +exports.SYSTEM_USER_COLLECTION = 'system.users'; +exports.SYSTEM_COMMAND_COLLECTION = '$cmd'; +exports.SYSTEM_JS_COLLECTION = 'system.js'; +//# sourceMappingURL=constants.js.map + +/***/ }), + +/***/ 7349: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.assertUninitialized = exports.AbstractCursor = exports.CURSOR_FLAGS = void 0; +const utils_1 = __nccwpck_require__(1371); +const bson_1 = __nccwpck_require__(5578); +const sessions_1 = __nccwpck_require__(5259); +const error_1 = __nccwpck_require__(9386); +const read_preference_1 = __nccwpck_require__(9802); +const stream_1 = __nccwpck_require__(2413); +const execute_operation_1 = __nccwpck_require__(2548); +const get_more_1 = __nccwpck_require__(6819); +const read_concern_1 = __nccwpck_require__(7289); +const mongo_types_1 = __nccwpck_require__(696); +/** @internal */ +const kId = Symbol('id'); +/** @internal */ +const kDocuments = Symbol('documents'); +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kNamespace = Symbol('namespace'); +/** @internal */ +const kTopology = Symbol('topology'); +/** @internal */ +const kSession = Symbol('session'); +/** @internal */ +const kOptions = Symbol('options'); +/** @internal */ +const kTransform = Symbol('transform'); +/** @internal */ +const kInitialized = Symbol('initialized'); +/** @internal */ +const kClosed = Symbol('closed'); +/** @internal */ +const kKilled = Symbol('killed'); +/** @public */ +exports.CURSOR_FLAGS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'exhaust', + 'partial' +]; +/** @public */ +class AbstractCursor extends mongo_types_1.TypedEventEmitter { + /** @internal */ + constructor(topology, namespace, options = {}) { + super(); + this[kTopology] = topology; + this[kNamespace] = namespace; + this[kDocuments] = []; // TODO: https://github.com/microsoft/TypeScript/issues/36230 + this[kInitialized] = false; + this[kClosed] = false; + this[kKilled] = false; + this[kOptions] = { + readPreference: options.readPreference && options.readPreference instanceof read_preference_1.ReadPreference + ? options.readPreference + : read_preference_1.ReadPreference.primary, + ...(0, bson_1.pluckBSONSerializeOptions)(options) + }; + const readConcern = read_concern_1.ReadConcern.fromOptions(options); + if (readConcern) { + this[kOptions].readConcern = readConcern; + } + if (typeof options.batchSize === 'number') { + this[kOptions].batchSize = options.batchSize; + } + if (options.comment != null) { + this[kOptions].comment = options.comment; + } + if (typeof options.maxTimeMS === 'number') { + this[kOptions].maxTimeMS = options.maxTimeMS; + } + if (options.session instanceof sessions_1.ClientSession) { + this[kSession] = options.session; + } + } + get id() { + return this[kId]; + } + /** @internal */ + get topology() { + return this[kTopology]; + } + /** @internal */ + get server() { + return this[kServer]; + } + get namespace() { + return this[kNamespace]; + } + get readPreference() { + return this[kOptions].readPreference; + } + get readConcern() { + return this[kOptions].readConcern; + } + /** @internal */ + get session() { + return this[kSession]; + } + set session(clientSession) { + this[kSession] = clientSession; + } + /** @internal */ + get cursorOptions() { + return this[kOptions]; + } + get closed() { + return this[kClosed]; + } + get killed() { + return this[kKilled]; + } + get loadBalanced() { + return this[kTopology].loadBalanced; + } + /** Returns current buffered documents length */ + bufferedCount() { + return this[kDocuments].length; + } + /** Returns current buffered documents */ + readBufferedDocuments(number) { + return this[kDocuments].splice(0, number !== null && number !== void 0 ? number : this[kDocuments].length); + } + [Symbol.asyncIterator]() { + return { + next: () => this.next().then(value => value != null ? { value, done: false } : { value: undefined, done: true }) }; - } - - 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(); - } + } + stream(options) { + if (options === null || options === void 0 ? void 0 : options.transform) { + const transform = options.transform; + const readable = makeCursorStream(this); + return readable.pipe(new stream_1.Transform({ + objectMode: true, + highWaterMark: 1, + transform(chunk, _, callback) { + try { + const transformed = transform(chunk); + callback(undefined, transformed); + } + catch (err) { + callback(err); + } + } + })); + } + return makeCursorStream(this); + } + hasNext(callback) { + return (0, utils_1.maybePromise)(callback, done => { + if (this[kId] === bson_1.Long.ZERO) { + return done(undefined, false); + } + if (this[kDocuments].length) { + return done(undefined, true); + } + next(this, true, (err, doc) => { + if (err) + return done(err); + if (doc) { + this[kDocuments].unshift(doc); + done(undefined, true); + return; + } + done(undefined, false); + }); + }); + } + next(callback) { + return (0, utils_1.maybePromise)(callback, done => { + if (this[kId] === bson_1.Long.ZERO) { + return done(new error_1.MongoCursorExhaustedError()); } - - // 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); + next(this, true, done); + }); + } + tryNext(callback) { + return (0, utils_1.maybePromise)(callback, done => { + if (this[kId] === bson_1.Long.ZERO) { + return done(new error_1.MongoCursorExhaustedError()); + } + next(this, false, done); + }); + } + forEach(iterator, callback) { + if (typeof iterator !== 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "iterator" must be a function'); } - - // Start all the servers - while (servers.length > 0) { - connect(servers.shift(), timeoutInterval++); + return (0, utils_1.maybePromise)(callback, done => { + const transform = this[kTransform]; + const fetchDocs = () => { + next(this, true, (err, doc) => { + if (err || doc == null) + return done(err); + let result; + // NOTE: no need to transform because `next` will do this automatically + try { + result = iterator(doc); // TODO(NODE-3283): Improve transform typing + } + catch (error) { + return done(error); + } + if (result === false) + return done(); + // these do need to be transformed since they are copying the rest of the batch + const internalDocs = this[kDocuments].splice(0, this[kDocuments].length); + for (let i = 0; i < internalDocs.length; ++i) { + try { + result = iterator((transform ? transform(internalDocs[i]) : internalDocs[i]) // TODO(NODE-3283): Improve transform typing + ); + } + catch (error) { + return done(error); + } + if (result === false) + return done(); + } + fetchDocs(); + }); + }; + fetchDocs(); + }); + } + close(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + const needsToEmitClosed = !this[kClosed]; + this[kClosed] = true; + return (0, utils_1.maybePromise)(callback, done => cleanupCursor(this, { needsToEmitClosed }, done)); + } + toArray(callback) { + return (0, utils_1.maybePromise)(callback, done => { + const docs = []; + const transform = this[kTransform]; + const fetchDocs = () => { + // NOTE: if we add a `nextBatch` then we should use it here + next(this, true, (err, doc) => { + if (err) + return done(err); + if (doc == null) + return done(undefined, docs); + // NOTE: no need to transform because `next` will do this automatically + docs.push(doc); + // these do need to be transformed since they are copying the rest of the batch + const internalDocs = (transform + ? this[kDocuments].splice(0, this[kDocuments].length).map(transform) + : this[kDocuments].splice(0, this[kDocuments].length)); // TODO(NODE-3283): Improve transform typing + if (internalDocs) { + docs.push(...internalDocs); + } + fetchDocs(); + }); + }; + fetchDocs(); + }); + } + /** + * Add a cursor flag to the cursor + * + * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -. + * @param value - The flag boolean value. + */ + addCursorFlag(flag, value) { + assertUninitialized(this); + if (!exports.CURSOR_FLAGS.includes(flag)) { + throw new error_1.MongoInvalidArgumentError(`Flag ${flag} is not one of ${exports.CURSOR_FLAGS}`); + } + if (typeof value !== 'boolean') { + throw new error_1.MongoInvalidArgumentError(`Flag ${flag} must be a boolean value`); + } + this[kOptions][flag] = value; + return this; + } + /** + * Map all documents using the provided function + * If there is a transform set on the cursor, that will be called first and the result passed to + * this function's transform. + * + * @remarks + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling map, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor = coll.find(); + * const mappedCursor: FindCursor = cursor.map(doc => Object.keys(doc).length); + * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[] + * ``` + * @param transform - The mapping transformation method. + */ + map(transform) { + assertUninitialized(this); + const oldTransform = this[kTransform]; // TODO(NODE-3283): Improve transform typing + if (oldTransform) { + this[kTransform] = doc => { + return transform(oldTransform(doc)); + }; } - } - - /** - * Emit event if it exists - * @method - */ - function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); + else { + this[kTransform] = transform; } - } - - /** - * 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 availability 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 - ) - ) - ); + return this; + } + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadPreference(readPreference) { + assertUninitialized(this); + if (readPreference instanceof read_preference_1.ReadPreference) { + this[kOptions].readPreference = readPreference; + } + else if (typeof readPreference === 'string') { + this[kOptions].readPreference = read_preference_1.ReadPreference.fromString(readPreference); } - - // 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 = {}; + else { + throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${readPreference}`); } - - options = options || {}; - - let destroyCount = this.s.connectingServers.length + 1; // +1 for the callback from `replicaSetState.destroy` - const serverDestroyed = () => { - destroyCount--; - if (destroyCount > 0) { + return this; + } + /** + * Set the ReadPreference for the cursor. + * + * @param readPreference - The new read preference for the cursor. + */ + withReadConcern(readConcern) { + assertUninitialized(this); + const resolvedReadConcern = read_concern_1.ReadConcern.fromOptions({ readConcern }); + if (resolvedReadConcern) { + this[kOptions].readConcern = resolvedReadConcern; + } + return this; + } + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value) { + assertUninitialized(this); + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Argument for maxTimeMS must be a number'); + } + this[kOptions].maxTimeMS = value; + return this; + } + /** + * Set the batch size for the cursor. + * + * @param value - The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. + */ + batchSize(value) { + assertUninitialized(this); + if (this[kOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support batchSize'); + } + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Operation "batchSize" requires an integer'); + } + this[kOptions].batchSize = value; + return this; + } + /** + * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will + * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even + * if the resultant data has already been retrieved by this cursor. + */ + rewind() { + if (!this[kInitialized]) { return; - } - - // Emit toplogy closing event - emitSDAMEvent(this, "topologyClosed", { topologyId: this.id }); - - if (typeof callback === "function") { - callback(null, null); - } - }; - - if (this.state === DESTROYED) { - if (typeof callback === "function") callback(null, null); - return; } - - // Transition state - stateTransition(this, DESTROYED); - - // 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(); + this[kId] = undefined; + this[kDocuments] = []; + this[kClosed] = false; + this[kKilled] = false; + this[kInitialized] = false; + const session = this[kSession]; + if (session) { + // We only want to end this session if we created it, and it hasn't ended yet + if (session.explicit === false && !session.hasEnded) { + session.endSession(); + } + this[kSession] = undefined; } - - // Reset list of intervalIds - this.intervalIds = []; - - if (destroyCount === 0) { - serverDestroyed(); - return; + } + /** @internal */ + _getMore(batchSize, callback) { + const cursorId = this[kId]; + const cursorNs = this[kNamespace]; + const server = this[kServer]; + if (cursorId == null) { + callback(new error_1.MongoRuntimeError('Unable to iterate cursor with no id')); + return; } - - // Destroy the replicaset - this.s.replicaSetState.destroy(options, serverDestroyed); - - // Destroy all connecting servers - this.s.connectingServers.forEach(function (x) { - x.destroy(options, serverDestroyed); + if (server == null) { + callback(new error_1.MongoRuntimeError('Unable to iterate cursor without selected server')); + return; + } + const getMoreOperation = new get_more_1.GetMoreOperation(cursorNs, cursorId, server, { + ...this[kOptions], + session: this[kSession], + batchSize }); - }; - - /** - * 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(); + (0, execute_operation_1.executeOperation)(this.topology, getMoreOperation, callback); + } +} +exports.AbstractCursor = AbstractCursor; +/** @event */ +AbstractCursor.CLOSE = 'close'; +function nextDocument(cursor) { + if (cursor[kDocuments] == null || !cursor[kDocuments].length) { + return null; + } + const doc = cursor[kDocuments].shift(); + if (doc) { + const transform = cursor[kTransform]; + if (transform) { + return transform(doc); + } + return doc; + } + return null; +} +function next(cursor, blocking, callback) { + const cursorId = cursor[kId]; + if (cursor.closed) { + return callback(undefined, null); + } + if (cursor[kDocuments] && cursor[kDocuments].length) { + callback(undefined, nextDocument(cursor)); + return; + } + if (cursorId == null) { + // All cursors must operate within a session, one must be made implicitly if not explicitly provided + if (cursor[kSession] == null && cursor[kTopology].hasSessionSupport()) { + cursor[kSession] = cursor[kTopology].startSession({ owner: cursor, explicit: false }); + } + cursor._initialize(cursor[kSession], (err, state) => { + if (state) { + const response = state.response; + cursor[kServer] = state.server; + cursor[kSession] = state.session; + if (response.cursor) { + cursor[kId] = + typeof response.cursor.id === 'number' + ? bson_1.Long.fromNumber(response.cursor.id) + : response.cursor.id; + if (response.cursor.ns) { + cursor[kNamespace] = (0, utils_1.ns)(response.cursor.ns); + } + cursor[kDocuments] = response.cursor.firstBatch; + } + else { + // NOTE: This is for support of older servers (<3.2) which do not use commands + cursor[kId] = + typeof response.cursorId === 'number' + ? bson_1.Long.fromNumber(response.cursorId) + : response.cursorId; + cursor[kDocuments] = response.documents; + } + // When server responses return without a cursor document, we close this cursor + // and return the raw server response. This is often the case for explain commands + // for example + if (cursor[kId] == null) { + cursor[kId] = bson_1.Long.ZERO; + // TODO(NODE-3286): ExecutionResult needs to accept a generic parameter + cursor[kDocuments] = [state.response]; + } + } + // the cursor is now initialized, even if an error occurred or it is dead + cursor[kInitialized] = true; + if (err || cursorIsDead(cursor)) { + return cleanupCursor(cursor, { error: err }, () => callback(err, nextDocument(cursor))); + } + next(cursor, blocking, callback); }); - - 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; + } + if (cursorIsDead(cursor)) { + return cleanupCursor(cursor, undefined, () => callback(undefined, null)); + } + // otherwise need to call getMore + const batchSize = cursor[kOptions].batchSize || 1000; + cursor._getMore(batchSize, (err, response) => { + if (response) { + const cursorId = typeof response.cursor.id === 'number' + ? bson_1.Long.fromNumber(response.cursor.id) + : response.cursor.id; + cursor[kDocuments] = response.cursor.nextBatch; + cursor[kId] = cursorId; + } + if (err || cursorIsDead(cursor)) { + return cleanupCursor(cursor, { error: err }, () => callback(err, nextDocument(cursor))); + } + if (cursor[kDocuments].length === 0 && blocking === false) { + return callback(undefined, null); + } + next(cursor, blocking, callback); + }); +} +function cursorIsDead(cursor) { + const cursorId = cursor[kId]; + return !!cursorId && cursorId.isZero(); +} +function cleanupCursor(cursor, options, callback) { + var _a; + const cursorId = cursor[kId]; + const cursorNs = cursor[kNamespace]; + const server = cursor[kServer]; + const session = cursor[kSession]; + const error = options === null || options === void 0 ? void 0 : options.error; + const needsToEmitClosed = (_a = options === null || options === void 0 ? void 0 : options.needsToEmitClosed) !== null && _a !== void 0 ? _a : cursor[kDocuments].length === 0; + if (error) { + if (cursor.loadBalanced && error instanceof error_1.MongoNetworkError) { + return completeCleanup(); } - - 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()); + } + if (cursorId == null || server == null || cursorId.isZero() || cursorNs == null) { + if (needsToEmitClosed) { + cursor[kClosed] = true; + cursor[kId] = bson_1.Long.ZERO; + cursor.emit(AbstractCursor.CLOSE); } - - 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 (session) { + if (session.owner === cursor) { + return session.endSession({ error }, callback); + } + if (!session.inTransaction()) { + (0, sessions_1.maybeClearPinnedConnection)(session, { error }); + } } - - if ( - options.readPreference && - options.readPreference.equals(ReadPreference.primary) - ) { - return this.s.replicaSetState.hasPrimary(); + return callback(); + } + function completeCleanup() { + if (session) { + if (session.owner === cursor) { + return session.endSession({ error }, () => { + cursor.emit(AbstractCursor.CLOSE); + callback(); + }); + } + if (!session.inTransaction()) { + (0, sessions_1.maybeClearPinnedConnection)(session, { error }); + } } - - if ( - options.readPreference && - options.readPreference.equals(ReadPreference.primaryPreferred) - ) { - return ( - this.s.replicaSetState.hasSecondary() || - this.s.replicaSetState.hasPrimary() - ); + cursor.emit(AbstractCursor.CLOSE); + return callback(); + } + cursor[kKilled] = true; + server.killCursors(cursorNs, [cursorId], { ...(0, bson_1.pluckBSONSerializeOptions)(cursor[kOptions]), session }, () => completeCleanup()); +} +/** @internal */ +function assertUninitialized(cursor) { + if (cursor[kInitialized]) { + throw new error_1.MongoCursorInUseError(); + } +} +exports.assertUninitialized = assertUninitialized; +function makeCursorStream(cursor) { + const readable = new stream_1.Readable({ + objectMode: true, + autoDestroy: false, + highWaterMark: 1 + }); + let initialized = false; + let reading = false; + let needToClose = true; // NOTE: we must close the cursor if we never read from it, use `_construct` in future node versions + readable._read = function () { + if (initialized === false) { + needToClose = false; + initialized = true; + } + if (!reading) { + reading = true; + readNext(); } - - if ( - options.readPreference && - options.readPreference.equals(ReadPreference.secondaryPreferred) - ) { - return ( - this.s.replicaSetState.hasSecondary() || - this.s.replicaSetState.hasPrimary() - ); + }; + readable._destroy = function (error, cb) { + if (needToClose) { + cursor.close(err => process.nextTick(cb, err || error)); + } + else { + cb(error); + } + }; + function readNext() { + needToClose = false; + next(cursor, true, (err, result) => { + needToClose = err ? !cursor.closed : result != null; + if (err) { + // NOTE: This is questionable, but we have a test backing the behavior. It seems the + // desired behavior is that a stream ends cleanly when a user explicitly closes + // a client during iteration. Alternatively, we could do the "right" thing and + // propagate the error message by removing this special case. + if (err.message.match(/server is closed/)) { + cursor.close(); + return readable.push(null); + } + // NOTE: This is also perhaps questionable. The rationale here is that these errors tend + // to be "operation interrupted", where a cursor has been closed but there is an + // active getMore in-flight. This used to check if the cursor was killed but once + // that changed to happen in cleanup legitimate errors would not destroy the + // stream. There are change streams test specifically test these cases. + if (err.message.match(/interrupted/)) { + return readable.push(null); + } + return readable.destroy(err); + } + if (result == null) { + readable.push(null); + } + else if (readable.destroyed) { + cursor.close(); + } + else { + if (readable.push(result)) { + return readNext(); + } + reading = false; + } + }); + } + return readable; +} +//# sourceMappingURL=abstract_cursor.js.map + +/***/ }), + +/***/ 3363: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AggregationCursor = void 0; +const aggregate_1 = __nccwpck_require__(1554); +const abstract_cursor_1 = __nccwpck_require__(7349); +const execute_operation_1 = __nccwpck_require__(2548); +const utils_1 = __nccwpck_require__(1371); +/** @internal */ +const kPipeline = Symbol('pipeline'); +/** @internal */ +const kOptions = Symbol('options'); +/** + * 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 + * @public + */ +class AggregationCursor extends abstract_cursor_1.AbstractCursor { + /** @internal */ + constructor(topology, namespace, pipeline = [], options = {}) { + super(topology, namespace, options); + this[kPipeline] = pipeline; + this[kOptions] = options; + } + get pipeline() { + return this[kPipeline]; + } + clone() { + const clonedOptions = (0, utils_1.mergeOptions)({}, this[kOptions]); + delete clonedOptions.session; + return new AggregationCursor(this.topology, this.namespace, this[kPipeline], { + ...clonedOptions + }); + } + map(transform) { + return super.map(transform); + } + /** @internal */ + _initialize(session, callback) { + const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], + ...this.cursorOptions, + session + }); + (0, execute_operation_1.executeOperation)(this.topology, aggregateOperation, (err, response) => { + if (err || response == null) + return callback(err); + // TODO: NODE-2882 + callback(undefined, { server: aggregateOperation.server, session, response }); + }); + } + explain(verbosity, callback) { + if (typeof verbosity === 'function') + (callback = verbosity), (verbosity = true); + if (verbosity == null) + verbosity = true; + return (0, execute_operation_1.executeOperation)(this.topology, new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], + ...this.cursorOptions, + explain: verbosity + }), callback); + } + group($group) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $group }); + return this; + } + /** Add a limit stage to the aggregation pipeline */ + limit($limit) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $limit }); + return this; + } + /** Add a match stage to the aggregation pipeline */ + match($match) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $match }); + return this; + } + /** Add an out stage to the aggregation pipeline */ + out($out) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $out }); + return this; + } + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: AggregationCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.aggregate().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project($project) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $project }); + return this; + } + /** Add a lookup stage to the aggregation pipeline */ + lookup($lookup) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $lookup }); + return this; + } + /** Add a redact stage to the aggregation pipeline */ + redact($redact) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $redact }); + return this; + } + /** Add a skip stage to the aggregation pipeline */ + skip($skip) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $skip }); + return this; + } + /** Add a sort stage to the aggregation pipeline */ + sort($sort) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $sort }); + return this; + } + /** Add a unwind stage to the aggregation pipeline */ + unwind($unwind) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $unwind }); + return this; + } + // deprecated methods + /** @deprecated Add a geoNear stage to the aggregation pipeline */ + geoNear($geoNear) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kPipeline].push({ $geoNear }); + return this; + } +} +exports.AggregationCursor = AggregationCursor; +//# sourceMappingURL=aggregation_cursor.js.map + +/***/ }), + +/***/ 3930: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FindCursor = exports.FLAGS = void 0; +const error_1 = __nccwpck_require__(9386); +const count_1 = __nccwpck_require__(7885); +const execute_operation_1 = __nccwpck_require__(2548); +const find_1 = __nccwpck_require__(9961); +const utils_1 = __nccwpck_require__(1371); +const sort_1 = __nccwpck_require__(8370); +const abstract_cursor_1 = __nccwpck_require__(7349); +/** @internal */ +const kFilter = Symbol('filter'); +/** @internal */ +const kNumReturned = Symbol('numReturned'); +/** @internal */ +const kBuiltOptions = Symbol('builtOptions'); +/** @public Flags allowed for cursor */ +exports.FLAGS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'exhaust', + 'partial' +]; +/** @public */ +class FindCursor extends abstract_cursor_1.AbstractCursor { + /** @internal */ + constructor(topology, namespace, filter, options = {}) { + super(topology, namespace, options); + this[kFilter] = filter || {}; + this[kBuiltOptions] = options; + if (options.sort != null) { + this[kBuiltOptions].sort = (0, sort_1.formatSort)(options.sort); } - - if ( - this.s.options.secondaryOnlyConnectionAllowed && - this.s.replicaSetState.hasSecondary() - ) { - return true; + } + clone() { + const clonedOptions = (0, utils_1.mergeOptions)({}, this[kBuiltOptions]); + delete clonedOptions.session; + return new FindCursor(this.topology, this.namespace, this[kFilter], { + ...clonedOptions + }); + } + map(transform) { + return super.map(transform); + } + /** @internal */ + _initialize(session, callback) { + const findOperation = new find_1.FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + session + }); + (0, execute_operation_1.executeOperation)(this.topology, findOperation, (err, response) => { + if (err || response == null) + return callback(err); + // TODO: We only need this for legacy queries that do not support `limit`, maybe + // the value should only be saved in those cases. + if (response.cursor) { + this[kNumReturned] = response.cursor.firstBatch.length; + } + else { + this[kNumReturned] = response.documents ? response.documents.length : 0; + } + // TODO: NODE-2882 + callback(undefined, { server: findOperation.server, session, response }); + }); + } + /** @internal */ + _getMore(batchSize, callback) { + // NOTE: this is to support client provided limits in pre-command servers + const numReturned = this[kNumReturned]; + if (numReturned) { + const limit = this[kBuiltOptions].limit; + batchSize = + limit && limit > 0 && numReturned + batchSize > limit ? limit - numReturned : batchSize; + if (batchSize <= 0) { + return this.close(callback); + } + } + super._getMore(batchSize, (err, response) => { + if (err) + return callback(err); + // TODO: wrap this in some logic to prevent it from happening if we don't need this support + if (response) { + this[kNumReturned] = this[kNumReturned] + response.cursor.nextBatch.length; + } + callback(undefined, response); + }); + } + count(options, callback) { + if (typeof options === 'boolean') { + throw new error_1.MongoInvalidArgumentError('Invalid first parameter to count'); } - - 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; + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + return (0, execute_operation_1.executeOperation)(this.topology, new count_1.CountOperation(this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + ...options + }), callback); + } + explain(verbosity, callback) { + if (typeof verbosity === 'function') + (callback = verbosity), (verbosity = true); + if (verbosity == null) + verbosity = true; + return (0, execute_operation_1.executeOperation)(this.topology, new find_1.FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + explain: verbosity + }), callback); + } + /** Set the cursor query */ + filter(filter) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kFilter] = filter; + return this; + } + /** + * Set the cursor hint + * + * @param hint - If specified, then the query system will only consider plans using the hinted index. + */ + hint(hint) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].hint = hint; + return this; + } + /** + * Set the cursor min + * + * @param 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. + */ + min(min) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].min = min; + return this; + } + /** + * Set the cursor max + * + * @param 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. + */ + max(max) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].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. + * + * @param value - the returnKey value. + */ + returnKey(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].returnKey = value; + return this; + } + /** + * Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection. + * + * @param value - The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + */ + showRecordId(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].showRecordId = value; + return this; + } + /** + * Add a query modifier to the cursor query + * + * @param name - The query modifier (must start with $, such as $orderby etc) + * @param value - The modifier value. + */ + addQueryModifier(name, value) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (name[0] !== '$') { + throw new error_1.MongoInvalidArgumentError(`${name} is not a valid query modifier`); + } + // Strip of the $ + const field = name.substr(1); + // NOTE: consider some TS magic for this + switch (field) { + case 'comment': + this[kBuiltOptions].comment = value; + break; + case 'explain': + this[kBuiltOptions].explain = value; + break; + case 'hint': + this[kBuiltOptions].hint = value; + break; + case 'max': + this[kBuiltOptions].max = value; + break; + case 'maxTimeMS': + this[kBuiltOptions].maxTimeMS = value; + break; + case 'min': + this[kBuiltOptions].min = value; + break; + case 'orderby': + this[kBuiltOptions].sort = (0, sort_1.formatSort)(value); + break; + case 'query': + this[kFilter] = value; + break; + case 'returnKey': + this[kBuiltOptions].returnKey = value; + break; + case 'showDiskLoc': + this[kBuiltOptions].showRecordId = value; + break; + default: + throw new error_1.MongoInvalidArgumentError(`Invalid query modifier: ${name}`); } - - 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); + return this; + } + /** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * + * @param value - The comment attached to this query. + */ + comment(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].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) + * + * @param value - Number of milliseconds to wait before aborting the tailed query. + */ + maxAwaitTimeMS(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Argument for maxAwaitTimeMS must be a number'); + } + this[kBuiltOptions].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) + * + * @param value - Number of milliseconds to wait before aborting the query. + */ + maxTimeMS(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Argument for maxTimeMS must be a number'); + } + this[kBuiltOptions].maxTimeMS = value; + return this; + } + /** + * Add a project stage to the aggregation pipeline + * + * @remarks + * In order to strictly type this function you must provide an interface + * that represents the effect of your projection on the result documents. + * + * By default chaining a projection to your cursor changes the returned type to the generic + * {@link Document} type. + * You should specify a parameterized type to have assertions on your final results. + * + * @example + * ```typescript + * // Best way + * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true }); + * // Flexible way + * const docs: FindCursor = cursor.project({ _id: 0, a: true }); + * ``` + * + * @remarks + * + * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor, + * it **does not** return a new instance of a cursor. This means when calling project, + * you should always assign the result to a new variable in order to get a correctly typed cursor variable. + * Take note of the following example: + * + * @example + * ```typescript + * const cursor: FindCursor<{ a: number; b: string }> = coll.find(); + * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true }); + * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray(); + * + * // or always use chaining and save the final cursor + * + * const cursor = coll.find().project<{ a: string }>({ + * _id: 0, + * a: { $convert: { input: '$a', to: 'string' } + * }}); + * ``` + */ + project(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].projection = value; + return this; + } + /** + * Sets the sort order of the cursor query. + * + * @param sort - The key or keys set for the sort. + * @param direction - The direction of the sorting (1 or -1). + */ + sort(sort, direction) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (this[kBuiltOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support sorting'); + } + this[kBuiltOptions].sort = (0, sort_1.formatSort)(sort, direction); + return this; + } + /** + * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) + * + * @remarks + * {@link https://docs.mongodb.com/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation} + */ + allowDiskUse() { + (0, abstract_cursor_1.assertUninitialized)(this); + if (!this[kBuiltOptions].sort) { + throw new error_1.MongoInvalidArgumentError('Option "allowDiskUse" requires a sort specification'); + } + this[kBuiltOptions].allowDiskUse = true; + return this; + } + /** + * Set the collation options for the cursor. + * + * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + */ + collation(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + this[kBuiltOptions].collation = value; + return this; + } + /** + * Set the limit for the cursor. + * + * @param value - The limit for the cursor query. + */ + limit(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (this[kBuiltOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support limit'); + } + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Operation "limit" requires an integer'); + } + this[kBuiltOptions].limit = value; + return this; + } + /** + * Set the skip for the cursor. + * + * @param value - The skip for the cursor query. + */ + skip(value) { + (0, abstract_cursor_1.assertUninitialized)(this); + if (this[kBuiltOptions].tailable) { + throw new error_1.MongoTailableCursorError('Tailable cursor does not support skip'); + } + if (typeof value !== 'number') { + throw new error_1.MongoInvalidArgumentError('Operation "skip" requires an integer'); + } + this[kBuiltOptions].skip = value; + return this; + } +} +exports.FindCursor = FindCursor; +//# sourceMappingURL=find_cursor.js.map + +/***/ }), + +/***/ 6662: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Db = void 0; +const utils_1 = __nccwpck_require__(1371); +const aggregation_cursor_1 = __nccwpck_require__(3363); +const bson_1 = __nccwpck_require__(5578); +const read_preference_1 = __nccwpck_require__(9802); +const error_1 = __nccwpck_require__(9386); +const collection_1 = __nccwpck_require__(5193); +const change_stream_1 = __nccwpck_require__(1117); +const CONSTANTS = __nccwpck_require__(147); +const write_concern_1 = __nccwpck_require__(2481); +const read_concern_1 = __nccwpck_require__(7289); +const logger_1 = __nccwpck_require__(8874); +const add_user_1 = __nccwpck_require__(7057); +const collections_1 = __nccwpck_require__(286); +const stats_1 = __nccwpck_require__(968); +const run_command_1 = __nccwpck_require__(1363); +const create_collection_1 = __nccwpck_require__(5561); +const indexes_1 = __nccwpck_require__(4218); +const drop_1 = __nccwpck_require__(2360); +const list_collections_1 = __nccwpck_require__(840); +const profiling_level_1 = __nccwpck_require__(3969); +const remove_user_1 = __nccwpck_require__(1969); +const rename_1 = __nccwpck_require__(2808); +const set_profiling_level_1 = __nccwpck_require__(6301); +const execute_operation_1 = __nccwpck_require__(2548); +const admin_1 = __nccwpck_require__(3238); +// Allowed parameters +const DB_OPTIONS_ALLOW_LIST = [ + 'writeConcern', + 'readPreference', + 'readPreferenceTags', + 'native_parser', + 'forceServerObjectId', + 'pkFactory', + 'serializeFunctions', + 'raw', + 'authSource', + 'ignoreUndefined', + 'readConcern', + 'retryMiliSeconds', + 'numberOfRetries', + 'loggerLevel', + 'logger', + 'promoteBuffers', + 'promoteLongs', + 'bsonRegExp', + 'promoteValues', + 'compression', + 'retryWrites' +]; +/** + * The **Db** class is a class that represents a MongoDB Database. + * @public + * + * @example + * ```js + * const { MongoClient } = require('mongodb'); + * // 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(); + * }); + * ``` + */ +class Db { + /** + * Creates a new Db instance + * + * @param client - The MongoClient for the database. + * @param databaseName - The name of the database this instance represents. + * @param options - Optional settings for Db construction + */ + constructor(client, databaseName, options) { + var _a; + options = options !== null && options !== void 0 ? options : {}; + // Filter the options + options = (0, utils_1.filterOptions)(options, DB_OPTIONS_ALLOW_LIST); + // Ensure we have a valid db name + validateDatabaseName(databaseName); + // Internal state of the db object + this.s = { + // Client + client, + // Options + options, + // Logger instance + logger: new logger_1.Logger('Db', options), + // Unpack read preference + readPreference: read_preference_1.ReadPreference.fromOptions(options), + // Merge bson options + bsonOptions: (0, bson_1.resolveBSONOptions)(options, client), + // Set up the primary key factory or fallback to ObjectId + pkFactory: (_a = options === null || options === void 0 ? void 0 : options.pkFactory) !== null && _a !== void 0 ? _a : utils_1.DEFAULT_PK_FACTORY, + // ReadConcern + readConcern: read_concern_1.ReadConcern.fromOptions(options), + writeConcern: write_concern_1.WriteConcern.fromOptions(options), + // Namespace + namespace: new utils_1.MongoDBNamespace(databaseName) }; - - _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: 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() && - options.explain === undefined; - - 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")); - } + } + get databaseName() { + return this.s.namespace.db; + } + // Options + get options() { + return this.s.options; + } + // slaveOk specified + get slaveOk() { + var _a; + return ((_a = this.s.readPreference) === null || _a === void 0 ? void 0 : _a.preference) !== 'primary' || false; + } + get readConcern() { + return this.s.readConcern; + } + /** + * The current readPreference of the Db. If not explicitly defined for + * this Db, will be inherited from the parent MongoClient + */ + get readPreference() { + if (this.s.readPreference == null) { + return this.s.client.readPreference; + } + return this.s.readPreference; + } + get bsonOptions() { + return this.s.bsonOptions; + } + // get the write Concern + get writeConcern() { + return this.s.writeConcern; + } + get namespace() { + return this.s.namespace.toString(); + } + createCollection(name, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this), new create_collection_1.CreateCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options)), callback); + } + command(command, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + // Intentionally, we do not inherit options from parent for this operation. + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this), new run_command_1.RunCommandOperation(this, command, options !== null && options !== void 0 ? options : {}), callback); + } + /** + * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6 + * + * @param pipeline - An array of aggregation stages to be executed + * @param options - Optional settings for the command + */ + aggregate(pipeline = [], options) { + if (arguments.length > 2) { + throw new error_1.MongoInvalidArgumentError('Method "db.aggregate()" accepts at most two arguments'); } - - 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 - ); + if (typeof pipeline === 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "pipeline" must not be function'); } - - // 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 - ) - ) - ); + if (typeof options === 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "options" must not be function'); } - - 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; + return new aggregation_cursor_1.AggregationCursor((0, utils_1.getTopology)(this), this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options)); + } + /** Return the Admin db instance */ + admin() { + return new admin_1.Admin(this); + } + /** + * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly. + * + * @param name - the collection name we wish to access. + * @returns return the new Collection instance + */ + collection(name, options = {}) { + if (typeof options === 'function') { + throw new error_1.MongoInvalidArgumentError('The callback form of this helper has been removed.'); + } + const finalOptions = (0, utils_1.resolveOptions)(this, options); + return new collection_1.Collection(this, name, finalOptions); + } + stats(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this), new stats_1.DbStatsOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); + } + listCollections(filter = {}, options = {}) { + return new list_collections_1.ListCollectionsCursor(this, filter, (0, utils_1.resolveOptions)(this, options)); + } + renameCollection(fromCollection, toCollection, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + // Intentionally, we do not inherit options from parent for this operation. + options = { ...options, readPreference: read_preference_1.ReadPreference.PRIMARY }; + // Add return new collection + options.new_collection = true; + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this), new rename_1.RenameOperation(this.collection(fromCollection), toCollection, options), callback); + } + dropCollection(name, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this), new drop_1.DropCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options)), callback); + } + dropDatabase(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this), new drop_1.DropDatabaseOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); + } + collections(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this), new collections_1.CollectionsOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); + } + createIndex(name, indexSpec, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this), new indexes_1.CreateIndexOperation(this, name, indexSpec, (0, utils_1.resolveOptions)(this, options)), callback); + } + addUser(username, password, options, callback) { + if (typeof password === 'function') { + (callback = password), (password = undefined), (options = {}); } - - // 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, - __nccwpck_require__ - ) => { - "use strict"; - - var inherits = __nccwpck_require__(1669).inherits, - f = __nccwpck_require__(1669).format, - diff = __nccwpck_require__(2306).diff, - EventEmitter = __nccwpck_require__(8614).EventEmitter, - Logger = __nccwpck_require__(104), - ReadPreference = __nccwpck_require__(4485), - MongoError = __nccwpck_require__(3111).MongoError, - Buffer = __nccwpck_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]; - } + else if (typeof password !== 'string') { + if (typeof options === 'function') { + (callback = options), (options = password), (password = undefined); + } + else { + (options = password), (callback = undefined), (password = undefined); + } } - - 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; + else { + if (typeof options === 'function') + (callback = options), (options = {}); + } + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this), new add_user_1.AddUserOperation(this, username, password, (0, utils_1.resolveOptions)(this, options)), callback); + } + removeUser(username, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this), new remove_user_1.RemoveUserOperation(this, username, (0, utils_1.resolveOptions)(this, options)), callback); + } + setProfilingLevel(level, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this), new set_profiling_level_1.SetProfilingLevelOperation(this, level, (0, utils_1.resolveOptions)(this, options)), callback); + } + profilingLevel(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this), new profiling_level_1.ProfilingLevelOperation(this, (0, utils_1.resolveOptions)(this, options)), callback); + } + indexInformation(name, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + return (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this), new indexes_1.IndexInformationOperation(this, name, (0, utils_1.resolveOptions)(this, options)), callback); + } + /** + * Unref all sockets + * @deprecated This function is deprecated and will be removed in the next major version. + */ + unref() { + (0, utils_1.getTopology)(this).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. + * + * @param 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 options - Optional settings for the command + */ + watch(pipeline = [], options = {}) { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; } - - 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; - } + return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options)); + } + /** Return the db logger */ + getLogger() { + return this.s.logger; + } + get logger() { + return this.s.logger; + } +} +exports.Db = Db; +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; +// TODO(NODE-3484): Refactor into MongoDBNamespace +// Validate the database name +function validateDatabaseName(databaseName) { + if (typeof databaseName !== 'string') + throw new error_1.MongoInvalidArgumentError('Database name must be a string'); + if (databaseName.length === 0) + throw new error_1.MongoInvalidArgumentError('Database name cannot be the empty string'); + if (databaseName === '$external') + return; + const invalidChars = [' ', '.', '$', '/', '\\']; + for (let i = 0; i < invalidChars.length; i++) { + if (databaseName.indexOf(invalidChars[i]) !== -1) + throw new error_1.MongoAPIError(`database names cannot contain the character '${invalidChars[i]}'`); + } +} +//# sourceMappingURL=db.js.map + +/***/ }), + +/***/ 6763: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AutoEncryptionLoggerLevel = exports.aws4 = exports.saslprep = exports.Snappy = exports.Kerberos = exports.PKG_VERSION = void 0; +/* eslint-disable @typescript-eslint/no-var-requires */ +const error_1 = __nccwpck_require__(9386); +const utils_1 = __nccwpck_require__(1371); +exports.PKG_VERSION = Symbol('kPkgVersion'); +function makeErrorModule(error) { + const props = error ? { kModuleError: error } : {}; + return new Proxy(props, { + get: (_, key) => { + if (key === 'kModuleError') { + return error; + } + throw error; + }, + set: () => { + throw error; } - - // 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; + }); +} +exports.Kerberos = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `kerberos` not found. Please install it to enable kerberos authentication')); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + exports.Kerberos = __nccwpck_require__(6330); +} +catch { } // eslint-disable-line +exports.Snappy = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `snappy` not found. Please install it to enable snappy compression')); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + exports.Snappy = __nccwpck_require__(4399); + try { + exports.Snappy[exports.PKG_VERSION] = (0, utils_1.parsePackageVersion)(__nccwpck_require__(8968)); + } + catch { } // eslint-disable-line +} +catch { } // eslint-disable-line +exports.saslprep = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `saslprep` not found.' + + ' Please install it to enable Stringprep Profile for User Names and Passwords')); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + exports.saslprep = __nccwpck_require__(9178); +} +catch { } // eslint-disable-line +exports.aws4 = makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `aws4` not found. Please install it to enable AWS authentication')); +try { + // Ensure you always wrap an optional require in the try block NODE-3199 + exports.aws4 = __nccwpck_require__(6071); +} +catch { } // eslint-disable-line +/** @public */ +exports.AutoEncryptionLoggerLevel = Object.freeze({ + FatalError: 0, + Error: 1, + Warning: 2, + Info: 3, + Trace: 4 +}); +//# sourceMappingURL=deps.js.map + +/***/ }), + +/***/ 3012: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Encrypter = void 0; +/* eslint-disable @typescript-eslint/no-var-requires */ +const mongo_client_1 = __nccwpck_require__(1545); +const error_1 = __nccwpck_require__(9386); +const bson_1 = __nccwpck_require__(5578); +const connect_1 = __nccwpck_require__(5210); +let AutoEncrypterClass; +/** @internal */ +const kInternalClient = Symbol('internalClient'); +/** @internal */ +class Encrypter { + constructor(client, uri, options) { + if (typeof options.autoEncryption !== 'object') { + throw new error_1.MongoInvalidArgumentError('Option "autoEncryption" must be specified'); + } + this.bypassAutoEncryption = !!options.autoEncryption.bypassAutoEncryption; + this.needsConnecting = false; + if (options.maxPoolSize === 0 && options.autoEncryption.keyVaultClient == null) { + options.autoEncryption.keyVaultClient = client; } - - // 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"; + else if (options.autoEncryption.keyVaultClient == null) { + options.autoEncryption.keyVaultClient = this.getInternalClient(client, uri, options); } - - // 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); + if (this.bypassAutoEncryption) { + options.autoEncryption.metadataClient = undefined; } - }; - - 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, - }; + else if (options.maxPoolSize === 0) { + options.autoEncryption.metadataClient = client; + } + else { + options.autoEncryption.metadataClient = this.getInternalClient(client, uri, options); + } + options.autoEncryption.bson = Object.create(null); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + options.autoEncryption.bson.serialize = bson_1.serialize; + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + options.autoEncryption.bson.deserialize = bson_1.deserialize; + this.autoEncrypter = new AutoEncrypterClass(client, options.autoEncryption); + } + getInternalClient(client, uri, options) { + if (!this[kInternalClient]) { + const clonedOptions = {}; + for (const key of Object.keys(options)) { + if (['autoEncryption', 'minPoolSize', 'servers', 'caseTranslate', 'dbName'].includes(key)) + continue; + Reflect.set(clonedOptions, key, Reflect.get(options, key)); } - } + clonedOptions.minPoolSize = 0; + this[kInternalClient] = new mongo_client_1.MongoClient(uri, clonedOptions); + for (const eventName of connect_1.MONGO_CLIENT_EVENTS) { + for (const listener of client.listeners(eventName)) { + this[kInternalClient].on(eventName, listener); + } + } + client.on('newListener', (eventName, listener) => { + this[kInternalClient].on(eventName, listener); + }); + this.needsConnecting = true; } - - // - // 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; + return this[kInternalClient]; + } + connectInternalClient(callback) { + if (this.needsConnecting) { + this.needsConnecting = false; + return this[kInternalClient].connect(callback); } - - // 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 - ); - } + return callback(); + } + close(client, force, callback) { + this.autoEncrypter.teardown(!!force, e => { + if (this[kInternalClient] && client !== this[kInternalClient]) { + return this[kInternalClient].close(force, callback); + } + callback(e); + }); + } + static checkForMongoCrypt() { + let mongodbClientEncryption = undefined; + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + mongodbClientEncryption = __nccwpck_require__(5764); } - - // - // 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; + catch (err) { + throw new error_1.MongoMissingDependencyError('Auto-encryption requested, but the module is not installed. ' + + 'Please add `mongodb-client-encryption` as a dependency of your project'); } + AutoEncrypterClass = mongodbClientEncryption.extension(__nccwpck_require__(8821)).AutoEncrypter; + } +} +exports.Encrypter = Encrypter; +//# sourceMappingURL=encrypter.js.map - // 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; - } +/***/ 9386: +/***/ ((__unused_webpack_module, exports) => { - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; +"use strict"; - // Set the topology - return false; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isResumableError = exports.isNetworkTimeoutError = exports.isSDAMUnrecoverableError = exports.isNodeShuttingDownError = exports.isRetryableError = exports.isRetryableWriteError = exports.isRetryableEndTransactionError = exports.MongoWriteConcernError = exports.MongoServerSelectionError = exports.MongoSystemError = exports.MongoMissingDependencyError = exports.MongoMissingCredentialsError = exports.MongoCompatibilityError = exports.MongoInvalidArgumentError = exports.MongoParseError = exports.MongoNetworkTimeoutError = exports.MongoNetworkError = exports.isNetworkErrorBeforeHandshake = exports.MongoTopologyClosedError = exports.MongoCursorExhaustedError = exports.MongoServerClosedError = exports.MongoCursorInUseError = exports.MongoGridFSChunkError = exports.MongoGridFSStreamError = exports.MongoTailableCursorError = exports.MongoChangeStreamError = exports.MongoKerberosError = exports.MongoExpiredSessionError = exports.MongoTransactionError = exports.MongoNotConnectedError = exports.MongoDecompressionError = exports.MongoBatchReExecutionError = exports.MongoRuntimeError = exports.MongoAPIError = exports.MongoDriverError = exports.MongoServerError = exports.MongoError = exports.GET_MORE_RESUMABLE_CODES = exports.MONGODB_ERROR_CODES = exports.NODE_IS_RECOVERING_ERROR_MESSAGE = exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = void 0; +/** @internal */ +const kErrorLabels = Symbol('errorLabels'); +/** + * @internal + * The legacy error message from the server that indicates the node is not a writable primary + * https://github.com/mongodb/specifications/blob/b07c26dc40d04ac20349f989db531c9845fdd755/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-writable-primary-and-node-is-recovering + */ +exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = 'not master'; +/** + * @internal + * The legacy error message from the server that indicates the node is not a primary or secondary + * https://github.com/mongodb/specifications/blob/b07c26dc40d04ac20349f989db531c9845fdd755/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-writable-primary-and-node-is-recovering + */ +exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = 'not master or secondary'; +/** + * @internal + * The error message from the server that indicates the node is recovering + * https://github.com/mongodb/specifications/blob/b07c26dc40d04ac20349f989db531c9845fdd755/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-writable-primary-and-node-is-recovering + */ +exports.NODE_IS_RECOVERING_ERROR_MESSAGE = 'node is recovering'; +/** @internal MongoDB Error Codes */ +exports.MONGODB_ERROR_CODES = Object.freeze({ + HostUnreachable: 6, + HostNotFound: 7, + NetworkTimeout: 89, + ShutdownInProgress: 91, + PrimarySteppedDown: 189, + ExceededTimeLimit: 262, + SocketException: 9001, + NotWritablePrimary: 10107, + InterruptedAtShutdown: 11600, + InterruptedDueToReplStateChange: 11602, + NotPrimaryNoSecondaryOk: 13435, + NotPrimaryOrSecondary: 13436, + StaleShardVersion: 63, + StaleEpoch: 150, + StaleConfig: 13388, + RetryChangeStream: 234, + FailedToSatisfyReadPreference: 133, + CursorNotFound: 43, + LegacyNotPrimary: 10058, + WriteConcernFailed: 64, + NamespaceNotFound: 26, + IllegalOperation: 20, + MaxTimeMSExpired: 50, + UnknownReplWriteConcern: 79, + UnsatisfiableWriteConcern: 100 +}); +// From spec@https://github.com/mongodb/specifications/blob/f93d78191f3db2898a59013a7ed5650352ef6da8/source/change-streams/change-streams.rst#resumable-error +exports.GET_MORE_RESUMABLE_CODES = new Set([ + exports.MONGODB_ERROR_CODES.HostUnreachable, + exports.MONGODB_ERROR_CODES.HostNotFound, + exports.MONGODB_ERROR_CODES.NetworkTimeout, + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.ExceededTimeLimit, + exports.MONGODB_ERROR_CODES.SocketException, + exports.MONGODB_ERROR_CODES.NotWritablePrimary, + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary, + exports.MONGODB_ERROR_CODES.StaleShardVersion, + exports.MONGODB_ERROR_CODES.StaleEpoch, + exports.MONGODB_ERROR_CODES.StaleConfig, + exports.MONGODB_ERROR_CODES.RetryChangeStream, + exports.MONGODB_ERROR_CODES.FailedToSatisfyReadPreference, + exports.MONGODB_ERROR_CODES.CursorNotFound +]); +/** + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error, it uses the constructor with a string argument + */ +class MongoError extends Error { + constructor(message) { + if (message instanceof Error) { + super(message.message); } - - // 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; + else { + super(message); } - - // - // 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; + } + get name() { + return 'MongoError'; + } + /** Legacy name for server error responses */ + get errmsg() { + return this.message; + } + /** + * Checks the error to see if it has an error label + * + * @param label - The error label to check for + * @returns 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]) : []; + } +} +exports.MongoError = MongoError; +/** + * An error coming from the mongo server + * + * @public + * @category Error + */ +class MongoServerError extends MongoError { + constructor(message) { + super(message.message || message.errmsg || message.$err || 'n/a'); + if (message.errorLabels) { + this[kErrorLabels] = new Set(message.errorLabels); + } + for (const name in message) { + if (name !== 'errorLabels' && name !== 'errmsg' && name !== 'message') + this[name] = message[name]; + } + } + get name() { + return 'MongoServerError'; + } +} +exports.MongoServerError = MongoServerError; +/** + * An error generated by the driver + * + * @public + * @category Error + */ +class MongoDriverError extends MongoError { + constructor(message) { + super(message); + } + get name() { + return 'MongoDriverError'; + } +} +exports.MongoDriverError = MongoDriverError; +/** + * An error generated when the driver API is used incorrectly + * + * @privateRemarks + * Should **never** be directly instantiated + * + * @public + * @category Error + */ +class MongoAPIError extends MongoDriverError { + constructor(message) { + super(message); + } + get name() { + return 'MongoAPIError'; + } +} +exports.MongoAPIError = MongoAPIError; +/** + * An error generated when the driver encounters unexpected input + * or reaches an unexpected/invalid internal state + * + * @privateRemarks + * Should **never** be directly instantiated. + * + * @public + * @category Error + */ +class MongoRuntimeError extends MongoDriverError { + constructor(message) { + super(message); + } + get name() { + return 'MongoRuntimeError'; + } +} +exports.MongoRuntimeError = MongoRuntimeError; +/** + * An error generated when a batch command is reexecuted after one of the commands in the batch + * has failed + * + * @public + * @category Error + */ +class MongoBatchReExecutionError extends MongoAPIError { + constructor(message = 'This batch has already been executed, create new batch to execute') { + super(message); + } + get name() { + return 'MongoBatchReExecutionError'; + } +} +exports.MongoBatchReExecutionError = MongoBatchReExecutionError; +/** + * An error generated when the driver fails to decompress + * data received from the server. + * + * @public + * @category Error + */ +class MongoDecompressionError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoDecompressionError'; + } +} +exports.MongoDecompressionError = MongoDecompressionError; +/** + * An error thrown when the user attempts to operate on a database or collection through a MongoClient + * that has not yet successfully called the "connect" method + * + * @public + * @category Error + */ +class MongoNotConnectedError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoNotConnectedError'; + } +} +exports.MongoNotConnectedError = MongoNotConnectedError; +/** + * An error generated when the user makes a mistake in the usage of transactions. + * (e.g. attempting to commit a transaction with a readPreference other than primary) + * + * @public + * @category Error + */ +class MongoTransactionError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoTransactionError'; + } +} +exports.MongoTransactionError = MongoTransactionError; +/** + * An error generated when the user attempts to operate + * on a session that has expired or has been closed. + * + * @public + * @category Error + */ +class MongoExpiredSessionError extends MongoAPIError { + constructor(message = 'Cannot use a session that has ended') { + super(message); + } + get name() { + return 'MongoExpiredSessionError'; + } +} +exports.MongoExpiredSessionError = MongoExpiredSessionError; +/** + * A error generated when the user attempts to authenticate + * via Kerberos, but fails to connect to the Kerberos client. + * + * @public + * @category Error + */ +class MongoKerberosError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoKerberosError'; + } +} +exports.MongoKerberosError = MongoKerberosError; +/** + * An error generated when a ChangeStream operation fails to execute. + * + * @public + * @category Error + */ +class MongoChangeStreamError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoChangeStreamError'; + } +} +exports.MongoChangeStreamError = MongoChangeStreamError; +/** + * An error thrown when the user calls a function or method not supported on a tailable cursor + * + * @public + * @category Error + */ +class MongoTailableCursorError extends MongoAPIError { + constructor(message = 'Tailable cursor does not support this operation') { + super(message); + } + get name() { + return 'MongoTailableCursorError'; + } +} +exports.MongoTailableCursorError = MongoTailableCursorError; +/** An error generated when a GridFSStream operation fails to execute. + * + * @public + * @category Error + */ +class MongoGridFSStreamError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoGridFSStreamError'; + } +} +exports.MongoGridFSStreamError = MongoGridFSStreamError; +/** + * An error generated when a malformed or invalid chunk is + * encountered when reading from a GridFSStream. + * + * @public + * @category Error + */ +class MongoGridFSChunkError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return 'MongoGridFSChunkError'; + } +} +exports.MongoGridFSChunkError = MongoGridFSChunkError; +/** + * An error thrown when the user attempts to add options to a cursor that has already been + * initialized + * + * @public + * @category Error + */ +class MongoCursorInUseError extends MongoAPIError { + constructor(message = 'Cursor is already initialized') { + super(message); + } + get name() { + return 'MongoCursorInUseError'; + } +} +exports.MongoCursorInUseError = MongoCursorInUseError; +/** + * An error generated when an attempt is made to operate + * on a closed/closing server. + * + * @public + * @category Error + */ +class MongoServerClosedError extends MongoAPIError { + constructor(message = 'Server is closed') { + super(message); + } + get name() { + return 'MongoServerClosedError'; + } +} +exports.MongoServerClosedError = MongoServerClosedError; +/** + * An error thrown when an attempt is made to read from a cursor that has been exhausted + * + * @public + * @category Error + */ +class MongoCursorExhaustedError extends MongoAPIError { + constructor(message) { + super(message || 'Cursor is exhausted'); + } + get name() { + return 'MongoCursorExhaustedError'; + } +} +exports.MongoCursorExhaustedError = MongoCursorExhaustedError; +/** + * An error generated when an attempt is made to operate on a + * dropped, or otherwise unavailable, database. + * + * @public + * @category Error + */ +class MongoTopologyClosedError extends MongoAPIError { + constructor(message = 'Topology is closed') { + super(message); + } + get name() { + return 'MongoTopologyClosedError'; + } +} +exports.MongoTopologyClosedError = MongoTopologyClosedError; +/** @internal */ +const kBeforeHandshake = Symbol('beforeHandshake'); +function isNetworkErrorBeforeHandshake(err) { + return err[kBeforeHandshake] === true; +} +exports.isNetworkErrorBeforeHandshake = isNetworkErrorBeforeHandshake; +/** + * An error indicating an issue with the network, including TCP errors and timeouts. + * @public + * @category Error + */ +class MongoNetworkError extends MongoError { + constructor(message, options) { + super(message); + if (options && typeof options.beforeHandshake === 'boolean') { + this[kBeforeHandshake] = options.beforeHandshake; + } + } + get name() { + return 'MongoNetworkError'; + } +} +exports.MongoNetworkError = MongoNetworkError; +/** + * An error indicating a network timeout occurred + * @public + * @category Error + * + * @privateRemarks + * CSFLE has a dependency on this error with an instanceof check + */ +class MongoNetworkTimeoutError extends MongoNetworkError { + constructor(message, options) { + super(message, options); + } + get name() { + return 'MongoNetworkTimeoutError'; + } +} +exports.MongoNetworkTimeoutError = MongoNetworkTimeoutError; +/** + * An error used when attempting to parse a value (like a connection string) + * @public + * @category Error + */ +class MongoParseError extends MongoDriverError { + constructor(message) { + super(message); + } + get name() { + return 'MongoParseError'; + } +} +exports.MongoParseError = MongoParseError; +/** + * An error generated when the user supplies malformed or unexpected arguments + * or when a required argument or field is not provided. + * + * + * @public + * @category Error + */ +class MongoInvalidArgumentError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoInvalidArgumentError'; + } +} +exports.MongoInvalidArgumentError = MongoInvalidArgumentError; +/** + * An error generated when a feature that is not enabled or allowed for the current server + * configuration is used + * + * + * @public + * @category Error + */ +class MongoCompatibilityError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoCompatibilityError'; + } +} +exports.MongoCompatibilityError = MongoCompatibilityError; +/** + * An error generated when the user fails to provide authentication credentials before attempting + * to connect to a mongo server instance. + * + * + * @public + * @category Error + */ +class MongoMissingCredentialsError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoMissingCredentialsError'; + } +} +exports.MongoMissingCredentialsError = MongoMissingCredentialsError; +/** + * An error generated when a required module or dependency is not present in the local environment + * + * @public + * @category Error + */ +class MongoMissingDependencyError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return 'MongoMissingDependencyError'; + } +} +exports.MongoMissingDependencyError = MongoMissingDependencyError; +/** + * An error signifying a general system issue + * @public + * @category Error + */ +class MongoSystemError extends MongoError { + constructor(message, reason) { + if (reason && reason.error) { + super(reason.error.message || reason.error); + } + else { + super(message); + } + if (reason) { + this.reason = reason; + } + } + get name() { + return 'MongoSystemError'; + } +} +exports.MongoSystemError = MongoSystemError; +/** + * An error signifying a client-side server selection error + * @public + * @category Error + */ +class MongoServerSelectionError extends MongoSystemError { + constructor(message, reason) { + super(message, reason); + } + get name() { + return 'MongoServerSelectionError'; + } +} +exports.MongoServerSelectionError = 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 + * @public + * @category Error + */ +class MongoWriteConcernError extends MongoServerError { + constructor(message, result) { + if (result && Array.isArray(result.errorLabels)) { + message.errorLabels = result.errorLabels; + } + super(message); + this.errInfo = message.errInfo; + if (result != null) { + this.result = makeWriteConcernResultObject(result); + } + } + get name() { + return 'MongoWriteConcernError'; + } +} +exports.MongoWriteConcernError = MongoWriteConcernError; +// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms +const RETRYABLE_ERROR_CODES = new Set([ + exports.MONGODB_ERROR_CODES.HostUnreachable, + exports.MONGODB_ERROR_CODES.HostNotFound, + exports.MONGODB_ERROR_CODES.NetworkTimeout, + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.SocketException, + exports.MONGODB_ERROR_CODES.NotWritablePrimary, + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary +]); +const RETRYABLE_WRITE_ERROR_CODES = new Set([ + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotWritablePrimary, + exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.HostNotFound, + exports.MONGODB_ERROR_CODES.HostUnreachable, + exports.MONGODB_ERROR_CODES.NetworkTimeout, + exports.MONGODB_ERROR_CODES.SocketException, + exports.MONGODB_ERROR_CODES.ExceededTimeLimit +]); +function isRetryableEndTransactionError(error) { + return error.hasErrorLabel('RetryableWriteError'); +} +exports.isRetryableEndTransactionError = isRetryableEndTransactionError; +function isRetryableWriteError(error) { + var _a, _b, _c; + if (error instanceof MongoWriteConcernError) { + return RETRYABLE_WRITE_ERROR_CODES.has((_c = (_b = (_a = error.result) === null || _a === void 0 ? void 0 : _a.code) !== null && _b !== void 0 ? _b : error.code) !== null && _c !== void 0 ? _c : 0); + } + return typeof error.code === 'number' && RETRYABLE_WRITE_ERROR_CODES.has(error.code); +} +exports.isRetryableWriteError = isRetryableWriteError; +/** Determines whether an error is something the driver should attempt to retry */ +function isRetryableError(error) { + return ( + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + (typeof error.code === 'number' && RETRYABLE_ERROR_CODES.has(error.code)) || + error instanceof MongoNetworkError || + !!error.message.match(new RegExp(exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE)) || + !!error.message.match(new RegExp(exports.NODE_IS_RECOVERING_ERROR_MESSAGE))); +} +exports.isRetryableError = isRetryableError; +const SDAM_RECOVERING_CODES = new Set([ + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary +]); +const SDAM_NOTPRIMARY_CODES = new Set([ + exports.MONGODB_ERROR_CODES.NotWritablePrimary, + exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + exports.MONGODB_ERROR_CODES.LegacyNotPrimary +]); +const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.ShutdownInProgress +]); +function isRecoveringError(err) { + if (typeof err.code === 'number') { + // If any error code exists, we ignore the error.message + return SDAM_RECOVERING_CODES.has(err.code); + } + return (new RegExp(exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE).test(err.message) || + new RegExp(exports.NODE_IS_RECOVERING_ERROR_MESSAGE).test(err.message)); +} +function isNotWritablePrimaryError(err) { + if (typeof err.code === 'number') { + // If any error code exists, we ignore the error.message + return SDAM_NOTPRIMARY_CODES.has(err.code); + } + if (isRecoveringError(err)) { + return false; + } + return new RegExp(exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE).test(err.message); +} +function isNodeShuttingDownError(err) { + return !!(typeof err.code === 'number' && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code)); +} +exports.isNodeShuttingDownError = isNodeShuttingDownError; +/** + * 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. + * + * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering + */ +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; + } + return isRecoveringError(error) || isNotWritablePrimaryError(error); +} +exports.isSDAMUnrecoverableError = isSDAMUnrecoverableError; +function isNetworkTimeoutError(err) { + return !!(err instanceof MongoNetworkError && err.message.match(/timed out/)); +} +exports.isNetworkTimeoutError = isNetworkTimeoutError; +// From spec@https://github.com/mongodb/specifications/blob/7a2e93d85935ee4b1046a8d2ad3514c657dc74fa/source/change-streams/change-streams.rst#resumable-error: +// +// An error is considered resumable if it meets any of the following criteria: +// - any error encountered which is not a server error (e.g. a timeout error or network error) +// - any server error response from a getMore command excluding those containing the error label +// NonRetryableChangeStreamError and those containing the following error codes: +// - Interrupted: 11601 +// - CappedPositionLost: 136 +// - CursorKilled: 237 +// +// An error on an aggregate command is not a resumable error. Only errors on a getMore command may be considered resumable errors. +function isResumableError(error, wireVersion) { + if (error instanceof MongoNetworkError) { + return true; + } + if (wireVersion != null && 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 && error instanceof MongoError && error.code === 43) { + return true; + } + return error instanceof MongoError && error.hasErrorLabel('ResumableChangeStreamError'); + } + if (error && typeof error.code === 'number') { + return exports.GET_MORE_RESUMABLE_CODES.has(error.code); + } + return false; +} +exports.isResumableError = isResumableError; +//# sourceMappingURL=error.js.map + +/***/ }), + +/***/ 5293: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Explain = exports.ExplainVerbosity = void 0; +const error_1 = __nccwpck_require__(9386); +/** @public */ +exports.ExplainVerbosity = Object.freeze({ + queryPlanner: 'queryPlanner', + queryPlannerExtended: 'queryPlannerExtended', + executionStats: 'executionStats', + allPlansExecution: 'allPlansExecution' +}); +/** @internal */ +class Explain { + constructor(verbosity) { + if (typeof verbosity === 'boolean') { + this.verbosity = verbosity + ? exports.ExplainVerbosity.allPlansExecution + : exports.ExplainVerbosity.queryPlanner; } - - // - // Server in maintanance mode - // - if ( - ismaster && - !ismaster.ismaster && - !ismaster.secondary && - !ismaster.arbiterOnly - ) { - this.remove(server, { force: true }); - return false; + else { + this.verbosity = verbosity; } - - // - // 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; + } + static fromOptions(options) { + if ((options === null || options === void 0 ? void 0 : options.explain) == null) + return; + const explain = options.explain; + if (typeof explain === 'boolean' || typeof explain === 'string') { + return new Explain(explain); } + throw new error_1.MongoInvalidArgumentError('Field "explain" must be a string or a boolean'); + } +} +exports.Explain = Explain; +//# sourceMappingURL=explain.js.map - // - // 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; - } +/***/ 8385: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Check if we need to replace the server - if (currentElectionId && ismasterElectionId) { - result = compareObjectIds(currentElectionId, ismasterElectionId); +"use strict"; - if (result === 1) { - return false; - } else if (result === 0 && currentSetVersion > ismasterSetVersion) { - return false; - } - } else if ( - !currentElectionId && - ismasterElectionId && - ismasterSetVersion - ) { - if (ismasterSetVersion < this.maxSetVersion) { - return false; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GridFSBucketReadStream = void 0; +const stream_1 = __nccwpck_require__(2413); +const error_1 = __nccwpck_require__(9386); +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * @public + */ +class GridFSBucketReadStream extends stream_1.Readable { + /** @internal + * @param chunks - Handle for chunks collection + * @param files - Handle for files collection + * @param readPreference - The read preference to use + * @param filter - The filter to use to find the file document + */ + constructor(chunks, files, readPreference, filter, options) { + super(); + this.s = { + bytesToTrim: 0, + bytesToSkip: 0, + bytesRead: 0, + chunks, + expected: 0, + files, + filter, + init: false, + expectedEnd: 0, + options: { + start: 0, + end: 0, + ...options + }, + readPreference + }; + } + /** + * Reads from the cursor and pushes to the stream. + * Private Impl, do not call directly + * @internal + */ + _read() { + if (this.destroyed) + return; + waitForFile(this, () => 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')`) + * + * @param start - 0-based offset in bytes to start streaming from + */ + start(start = 0) { + 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')`) + * + * @param end - Offset in bytes to stop reading at + */ + end(end = 0) { + 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. + * + * @param callback - called when the cursor is successfully closed or an error occurred. + */ + abort(callback) { + this.push(null); + this.destroyed = true; + if (this.s.cursor) { + this.s.cursor.close(error => { + this.emit(GridFSBucketReadStream.CLOSE); + callback && callback(error); + }); + } + else { + if (!this.s.init) { + // If not initialized, fire close event because we will never + // get a cursor + this.emit(GridFSBucketReadStream.CLOSE); } - } - - 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; - } + callback && callback(); + } + } +} +exports.GridFSBucketReadStream = GridFSBucketReadStream; +/** + * An error occurred + * @event + */ +GridFSBucketReadStream.ERROR = 'error'; +/** + * Fires when the stream loaded the file document corresponding to the provided id. + * @event + */ +GridFSBucketReadStream.FILE = 'file'; +/** + * Emitted when a chunk of data is available to be consumed. + * @event + */ +GridFSBucketReadStream.DATA = 'data'; +/** + * Fired when the stream is exhausted (no more data events). + * @event + */ +GridFSBucketReadStream.END = 'end'; +/** + * Fired when the stream is exhausted and the underlying cursor is killed + * @event + */ +GridFSBucketReadStream.CLOSE = 'close'; +function throwIfInitialized(stream) { + if (stream.s.init) { + throw new error_1.MongoGridFSStreamError('Options cannot be changed after the stream is initialized'); + } +} +function doRead(stream) { + if (stream.destroyed) + return; + if (!stream.s.cursor) + return; + if (!stream.s.file) + return; + stream.s.cursor.next((error, doc) => { + if (stream.destroyed) { + return; + } + if (error) { + stream.emit(GridFSBucketReadStream.ERROR, error); + return; + } + if (!doc) { + stream.push(null); + process.nextTick(() => { + if (!stream.s.cursor) + return; + stream.s.cursor.close(error => { + if (error) { + stream.emit(GridFSBucketReadStream.ERROR, error); + return; + } + stream.emit(GridFSBucketReadStream.CLOSE); + }); + }); + return; + } + if (!stream.s.file) + return; + const bytesRemaining = stream.s.file.length - stream.s.bytesRead; + const expectedN = stream.s.expected++; + const expectedLength = Math.min(stream.s.file.chunkSize, bytesRemaining); + if (doc.n > expectedN) { + return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ChunkIsMissing: Got unexpected n: ${doc.n}, expected: ${expectedN}`)); + } + if (doc.n < expectedN) { + return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected: ${expectedN}`)); + } + let buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; + if (buf.byteLength !== expectedLength) { + if (bytesRemaining <= 0) { + return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}`)); } - - 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, - }; + return stream.emit(GridFSBucketReadStream.ERROR, new error_1.MongoGridFSChunkError(`ChunkIsWrongSize: Got unexpected length: ${buf.byteLength}, expected: ${expectedLength}`)); } - - // - // 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; + stream.s.bytesRead += buf.byteLength; + if (buf.byteLength === 0) { + return stream.push(null); } - - // - // 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; + let sliceStart = null; + let sliceEnd = null; + if (stream.s.bytesToSkip != null) { + sliceStart = stream.s.bytesToSkip; + stream.s.bytesToSkip = 0; } - - // - // 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; + const atEndOfStream = expectedN === stream.s.expectedEnd - 1; + const bytesLeftToRead = stream.s.options.end - stream.s.bytesToSkip; + if (atEndOfStream && stream.s.bytesToTrim != null) { + sliceEnd = stream.s.file.chunkSize - stream.s.bytesToTrim; } - - // - // 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; + else if (stream.s.options.end && bytesLeftToRead < doc.data.byteLength) { + sliceEnd = bytesLeftToRead; } - - 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; + if (sliceStart != null || sliceEnd != null) { + buf = buf.slice(sliceStart || 0, sliceEnd || buf.byteLength); } - }; - - /** - * 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); + stream.push(buf); + }); +} +function init(stream) { + const findOneOptions = {}; + if (stream.s.readPreference) { + findOneOptions.readPreference = stream.s.readPreference; + } + if (stream.s.options && stream.s.options.sort) { + findOneOptions.sort = stream.s.options.sort; + } + if (stream.s.options && stream.s.options.skip) { + findOneOptions.skip = stream.s.options.skip; + } + stream.s.files.findOne(stream.s.filter, findOneOptions, (error, doc) => { + if (error) { + return stream.emit(GridFSBucketReadStream.ERROR, error); } - }; - - /** - * 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" - ); + if (!doc) { + const identifier = stream.s.filter._id + ? stream.s.filter._id.toString() + : stream.s.filter.filename; + const errmsg = `FileNotFound: file ${identifier} was not found`; + // TODO(NODE-3483) + const err = new error_1.MongoRuntimeError(errmsg); + err.code = 'ENOENT'; // TODO: NODE-3338 set property as part of constructor + return stream.emit(GridFSBucketReadStream.ERROR, err); + } + // If document is empty, kill the stream immediately and don't + // execute any reads + if (doc.length <= 0) { + stream.push(null); + return; } - - // 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" - ); + if (stream.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. + stream.emit(GridFSBucketReadStream.CLOSE); + return; + } + try { + stream.s.bytesToSkip = handleStartOption(stream, doc, stream.s.options); + } + catch (error) { + return stream.emit(GridFSBucketReadStream.ERROR, error); + } + const 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 (stream.s.options && stream.s.options.start != null) { + const skip = Math.floor(stream.s.options.start / doc.chunkSize); + if (skip > 0) { + filter['n'] = { $gte: skip }; } - } } - - // 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); + stream.s.cursor = stream.s.chunks.find(filter).sort({ n: 1 }); + if (stream.s.readPreference) { + stream.s.cursor.withReadPreference(stream.s.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"); + stream.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); + stream.s.file = doc; + try { + stream.s.bytesToTrim = handleEndOption(stream, doc, stream.s.cursor, stream.s.options); } - - if ( - readPreference.equals(ReadPreference.secondaryPreferred) && - secondaries.length === 0 && - this.primary == null - ) { - return new MongoError("no secondary or primary server available"); + catch (error) { + return stream.emit(GridFSBucketReadStream.ERROR, error); } - - if ( - readPreference.equals(ReadPreference.primary) && - this.primary == null - ) { - return new MongoError("no primary server available"); + stream.emit(GridFSBucketReadStream.FILE, doc); + }); +} +function waitForFile(stream, callback) { + if (stream.s.file) { + return callback(); + } + if (!stream.s.init) { + init(stream); + stream.s.init = true; + } + stream.once('file', () => { + callback(); + }); +} +function handleStartOption(stream, doc, options) { + if (options && options.start != null) { + if (options.start > doc.length) { + throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be more than the length of the file (${doc.length})`); } - - // 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; + if (options.start < 0) { + throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be negative`); } - - // 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; + if (options.end != null && options.end < options.start) { + throw new error_1.MongoInvalidArgumentError(`Stream start (${options.start}) must not be greater than stream end (${options.end})`); } - - // 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; - } + 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; + } + throw new error_1.MongoInvalidArgumentError('Start option must be defined'); +} +function handleEndOption(stream, doc, cursor, options) { + if (options && options.end != null) { + if (options.end > doc.length) { + throw new error_1.MongoInvalidArgumentError(`Stream end (${options.end}) must not be more than the length of the file (${doc.length})`); + } + if (options.start == null || options.start < 0) { + throw new error_1.MongoInvalidArgumentError(`Stream end (${options.end}) must not be negative`); + } + const 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; + } + throw new error_1.MongoInvalidArgumentError('End option must be defined'); +} +//# sourceMappingURL=download.js.map + +/***/ }), + +/***/ 5000: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GridFSBucket = void 0; +const error_1 = __nccwpck_require__(9386); +const download_1 = __nccwpck_require__(8385); +const upload_1 = __nccwpck_require__(1770); +const utils_1 = __nccwpck_require__(1371); +const write_concern_1 = __nccwpck_require__(2481); +const mongo_types_1 = __nccwpck_require__(696); +const DEFAULT_GRIDFS_BUCKET_OPTIONS = { + bucketName: 'fs', + chunkSizeBytes: 255 * 1024 +}; +/** + * Constructor for a streaming GridFS interface + * @public + */ +class GridFSBucket extends mongo_types_1.TypedEventEmitter { + constructor(db, options) { + super(); + this.setMaxListeners(0); + const privateOptions = { + ...DEFAULT_GRIDFS_BUCKET_OPTIONS, + ...options, + writeConcern: write_concern_1.WriteConcern.fromOptions(options) + }; + this.s = { + db, + options: privateOptions, + _chunksCollection: db.collection(privateOptions.bucketName + '.chunks'), + _filesCollection: db.collection(privateOptions.bucketName + '.files'), + checkedIndexes: false, + calledOpenUploadStream: false + }; + } + /** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + openUploadStream(filename, options) { + return new upload_1.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. + */ + openUploadStreamWithId(id, filename, options) { + return new upload_1.GridFSBucketWriteStream(this, filename, { ...options, id }); + } + /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */ + openDownloadStream(id, options) { + return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { _id: id }, options); + } + delete(id, callback) { + return (0, utils_1.executeLegacyOperation)((0, utils_1.getTopology)(this.s.db), _delete, [this, id, callback], { + skipSessions: true + }); + } + /** Convenience wrapper around find on the files collection */ + find(filter, options) { + filter !== null && filter !== void 0 ? filter : (filter = {}); + options = options !== null && options !== void 0 ? options : {}; + return this.s._filesCollection.find(filter, options); + } + /** + * 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. + */ + openDownloadStreamByName(filename, options) { + let sort = { uploadDate: -1 }; + let skip = undefined; + if (options && options.revision != null) { + if (options.revision >= 0) { + sort = { uploadDate: 1 }; + skip = options.revision; } - - // Add to candidate list - if (found) { - filteredServers.push(servers[i]); + else { + skip = -options.revision - 1; } - } } - - // 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" - ); + return new download_1.GridFSBucketReadStream(this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, { filename }, { ...options, sort, skip }); + } + rename(id, filename, callback) { + return (0, utils_1.executeLegacyOperation)((0, utils_1.getTopology)(this.s.db), _rename, [this, id, filename, callback], { + skipSessions: true + }); + } + drop(callback) { + return (0, utils_1.executeLegacyOperation)((0, utils_1.getTopology)(this.s.db), _drop, [this, callback], { + skipSessions: true + }); + } + /** Get the Db scoped logger. */ + getLogger() { + return this.s.db.s.logger; + } +} +exports.GridFSBucket = GridFSBucket; +/** + * 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 = 'index'; +function _delete(bucket, id, callback) { + return bucket.s._filesCollection.deleteOne({ _id: id }, (error, res) => { + if (error) { + return callback(error); } - - // Add primary to list if not a secondary read preference - if ( - self.primary && - readPreference.preference !== "secondary" && - readPreference.preference !== "secondaryPreferred" - ) { - servers.push(self.primary); + return bucket.s._chunksCollection.deleteMany({ files_id: id }, error => { + if (error) { + return callback(error); + } + // Delete orphaned chunks before returning FileNotFound + if (!(res === null || res === void 0 ? void 0 : res.deletedCount)) { + // TODO(NODE-3483): Replace with more appropriate error + // Consider creating new error MongoGridFSFileNotFoundError + return callback(new error_1.MongoRuntimeError(`File not found for id ${id}`)); + } + return callback(); + }); + }); +} +function _rename(bucket, id, filename, callback) { + const filter = { _id: id }; + const update = { $set: { filename } }; + return bucket.s._filesCollection.updateOne(filter, update, (error, res) => { + if (error) { + return callback(error); } - - // Add all the secondaries - for (var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); + if (!(res === null || res === void 0 ? void 0 : res.matchedCount)) { + return callback(new error_1.MongoRuntimeError(`File with id ${id} not found`)); } - - // 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); + return callback(); + }); +} +function _drop(bucket, callback) { + return bucket.s._filesCollection.drop((error) => { + if (error) { + return callback(error); } - - // 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; + return bucket.s._chunksCollection.drop((error) => { + if (error) { + return callback(error); + } + return callback(); }); + }); +} +//# sourceMappingURL=index.js.map - // 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; - } +/***/ 1770: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - function pickNearest(self, readPreference) { - // Only get primary and secondaries as seeds - var servers = []; +"use strict"; - // Add primary to list if not a secondary read preference - if ( - self.primary && - readPreference.preference !== "secondary" && - readPreference.preference !== "secondaryPreferred" - ) { - servers.push(self.primary); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GridFSBucketWriteStream = void 0; +const stream_1 = __nccwpck_require__(2413); +const bson_1 = __nccwpck_require__(5578); +const error_1 = __nccwpck_require__(9386); +const utils_1 = __nccwpck_require__(1371); +const write_concern_1 = __nccwpck_require__(2481); +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * @public + */ +class GridFSBucketWriteStream extends stream_1.Writable { + /** @internal + * @param bucket - Handle for this stream's corresponding bucket + * @param filename - The value of the 'filename' key in the files doc + * @param options - Optional settings. + */ + constructor(bucket, filename, options) { + super(); + options = options !== null && options !== void 0 ? options : {}; + this.bucket = bucket; + this.chunks = bucket.s._chunksCollection; + this.filename = filename; + this.files = bucket.s._filesCollection; + this.options = options; + this.writeConcern = write_concern_1.WriteConcern.fromOptions(options) || bucket.s.options.writeConcern; + // Signals the write is all done + this.done = false; + this.id = options.id ? options.id : new bson_1.ObjectId(); + // properly inherit the default chunksize from parent + this.chunkSizeBytes = options.chunkSizeBytes || this.bucket.s.options.chunkSizeBytes; + this.bufToStore = Buffer.alloc(this.chunkSizeBytes); + this.length = 0; + this.n = 0; + this.pos = 0; + this.state = { + streamEnd: false, + outstandingRequests: 0, + errored: false, + aborted: false + }; + if (!this.bucket.s.calledOpenUploadStream) { + this.bucket.s.calledOpenUploadStream = true; + checkIndexes(this, () => { + this.bucket.s.checkedIndexes = true; + this.bucket.emit('index'); + }); } - - // Add all the secondaries - for (var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); + } + write(chunk, encodingOrCallback, callback) { + const encoding = typeof encodingOrCallback === 'function' ? undefined : encodingOrCallback; + callback = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback; + return waitForIndexes(this, () => doWrite(this, chunk, encoding, callback)); + } + abort(callback) { + return (0, utils_1.maybePromise)(callback, callback => { + if (this.state.streamEnd) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + return callback(new error_1.MongoAPIError('Cannot abort a stream that has already completed')); + } + if (this.state.aborted) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + return callback(new error_1.MongoAPIError('Cannot call abort() on a stream twice')); + } + this.state.aborted = true; + this.chunks.deleteMany({ files_id: this.id }, error => callback(error)); + }); + } + end(chunkOrCallback, encodingOrCallback, callback) { + const chunk = typeof chunkOrCallback === 'function' ? undefined : chunkOrCallback; + const encoding = typeof encodingOrCallback === 'function' ? undefined : encodingOrCallback; + callback = + typeof chunkOrCallback === 'function' + ? chunkOrCallback + : typeof encodingOrCallback === 'function' + ? encodingOrCallback + : callback; + if (checkAborted(this, callback)) + return; + this.state.streamEnd = true; + if (callback) { + this.once(GridFSBucketWriteStream.FINISH, (result) => { + if (callback) + callback(undefined, result); + }); } - - // 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); + if (!chunk) { + waitForIndexes(this, () => !!writeRemnant(this)); + return; } - - // 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; + this.write(chunk, encoding, () => { + writeRemnant(this); }); - - // No servers, default to primary - if (servers.length === 0) { - return null; + } +} +exports.GridFSBucketWriteStream = GridFSBucketWriteStream; +/** @event */ +GridFSBucketWriteStream.CLOSE = 'close'; +/** @event */ +GridFSBucketWriteStream.ERROR = 'error'; +/** + * `end()` was called and the write stream successfully wrote the file metadata and all the chunks to MongoDB. + * @event + */ +GridFSBucketWriteStream.FINISH = 'finish'; +function __handleError(stream, error, callback) { + if (stream.state.errored) { + return; + } + stream.state.errored = true; + if (callback) { + return callback(error); + } + stream.emit(GridFSBucketWriteStream.ERROR, error); +} +function createChunkDoc(filesId, n, data) { + return { + _id: new bson_1.ObjectId(), + files_id: filesId, + n, + data + }; +} +function checkChunksIndex(stream, callback) { + stream.chunks.listIndexes().toArray((error, indexes) => { + let index; + if (error) { + // Collection doesn't exist so create index + if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + index = { files_id: 1, n: 1 }; + stream.chunks.createIndex(index, { background: false, unique: true }, error => { + if (error) { + return callback(error); + } + callback(); + }); + return; + } + return callback(error); } - - // 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; + let hasChunksIndex = false; + if (indexes) { + indexes.forEach((index) => { + if (index.key) { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + hasChunksIndex = 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 (hasChunksIndex) { + callback(); } - - if (typeof Buffer.compare === "function") { - return Buffer.compare(a, b); + else { + index = { files_id: 1, n: 1 }; + const writeConcernOptions = getWriteOptions(stream); + stream.chunks.createIndex(index, { + ...writeConcernOptions, + background: true, + unique: true + }, callback); } - - 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; - } + }); +} +function checkDone(stream, callback) { + if (stream.done) + return true; + if (stream.state.streamEnd && stream.state.outstandingRequests === 0 && !stream.state.errored) { + // Set done so we do not trigger duplicate createFilesDoc + stream.done = true; + // Create a new files doc + const filesDoc = createFilesDoc(stream.id, stream.length, stream.chunkSizeBytes, stream.filename, stream.options.contentType, stream.options.aliases, stream.options.metadata); + if (checkAborted(stream, callback)) { + return false; } - - if (i !== len) { - x = a[i]; - y = b[i]; + stream.files.insertOne(filesDoc, getWriteOptions(stream), (error) => { + if (error) { + return __handleError(stream, error, callback); + } + stream.emit(GridFSBucketWriteStream.FINISH, filesDoc); + stream.emit(GridFSBucketWriteStream.CLOSE); + }); + return true; + } + return false; +} +function checkIndexes(stream, callback) { + stream.files.findOne({}, { projection: { _id: 1 } }, (error, doc) => { + if (error) { + return callback(error); } - - 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; - } + if (doc) { + return callback(); } - + stream.files.listIndexes().toArray((error, indexes) => { + let index; + if (error) { + // Collection doesn't exist so create index + if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + index = { filename: 1, uploadDate: 1 }; + stream.files.createIndex(index, { background: false }, (error) => { + if (error) { + return callback(error); + } + checkChunksIndex(stream, callback); + }); + return; + } + return callback(error); + } + let hasFileIndex = false; + if (indexes) { + indexes.forEach((index) => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + hasFileIndex = true; + } + }); + } + if (hasFileIndex) { + checkChunksIndex(stream, callback); + } + else { + index = { filename: 1, uploadDate: 1 }; + const writeConcernOptions = getWriteOptions(stream); + stream.files.createIndex(index, { + ...writeConcernOptions, + background: false + }, (error) => { + if (error) { + return callback(error); + } + checkChunksIndex(stream, callback); + }); + } + }); + }); +} +function createFilesDoc(_id, length, chunkSize, filename, contentType, aliases, metadata) { + const ret = { + _id, + length, + chunkSize, + uploadDate: new Date(), + filename + }; + if (contentType) { + ret.contentType = contentType; + } + if (aliases) { + ret.aliases = aliases; + } + if (metadata) { + ret.metadata = metadata; + } + return ret; +} +function doWrite(stream, chunk, encoding, callback) { + if (checkAborted(stream, callback)) { 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; + } + const inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); + stream.length += inputBuf.length; + // Input is small enough to fit in our buffer + if (stream.pos + inputBuf.length < stream.chunkSizeBytes) { + inputBuf.copy(stream.bufToStore, stream.pos); + stream.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. + let inputBufRemaining = inputBuf.length; + let spaceRemaining = stream.chunkSizeBytes - stream.pos; + let numToCopy = Math.min(spaceRemaining, inputBuf.length); + let outstandingRequests = 0; + while (inputBufRemaining > 0) { + const inputBufPos = inputBuf.length - inputBufRemaining; + inputBuf.copy(stream.bufToStore, stream.pos, inputBufPos, inputBufPos + numToCopy); + stream.pos += numToCopy; + spaceRemaining -= numToCopy; + let doc; + if (spaceRemaining === 0) { + doc = createChunkDoc(stream.id, stream.n, Buffer.from(stream.bufToStore)); + ++stream.state.outstandingRequests; + ++outstandingRequests; + if (checkAborted(stream, callback)) { + return false; + } + stream.chunks.insertOne(doc, getWriteOptions(stream), (error) => { + if (error) { + return __handleError(stream, error); + } + --stream.state.outstandingRequests; + --outstandingRequests; + if (!outstandingRequests) { + stream.emit('drain', doc); + callback && callback(); + checkDone(stream); + } + }); + spaceRemaining = stream.chunkSizeBytes; + stream.pos = 0; + ++stream.n; } - } - - module.exports = ReplSetState; - - /***/ - }, - - /***/ 6495: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - var inherits = __nccwpck_require__(1669).inherits, - f = __nccwpck_require__(1669).format, - EventEmitter = __nccwpck_require__(8614).EventEmitter, - ReadPreference = __nccwpck_require__(4485), - Logger = __nccwpck_require__(104), - debugOptions = __nccwpck_require__(7746).debugOptions, - retrieveBSON = __nccwpck_require__(7746).retrieveBSON, - Pool = __nccwpck_require__(5500), - MongoError = __nccwpck_require__(3111).MongoError, - MongoNetworkError = __nccwpck_require__(3111).MongoNetworkError, - wireProtocol = __nccwpck_require__(9206), - CoreCursor = __nccwpck_require__(4847).CoreCursor, - sdam = __nccwpck_require__(2306), - createCompressionInfo = __nccwpck_require__(2306).createCompressionInfo, - resolveClusterTime = __nccwpck_require__(2306).resolveClusterTime, - SessionMixins = __nccwpck_require__(2306).SessionMixins, - extractCommand = __nccwpck_require__(7703).extractCommand, - relayEvents = __nccwpck_require__(1178).relayEvents; - - const collationNotSupported = - __nccwpck_require__(1178).collationNotSupported; - const makeClientMetadata = __nccwpck_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", - "bsonRegExp", - "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=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 {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 {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @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, + 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; +} +function getWriteOptions(stream) { + const obj = {}; + if (stream.writeConcern) { + obj.writeConcern = { + w: stream.writeConcern.w, + wtimeout: stream.writeConcern.wtimeout, + j: stream.writeConcern.j }; - - // 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; + } + return obj; +} +function waitForIndexes(stream, callback) { + if (stream.bucket.s.checkedIndexes) { + return callback(false); + } + stream.bucket.once('index', () => { + callback(true); + }); + return true; +} +function writeRemnant(stream, callback) { + // Buffer is empty, so don't bother to insert + if (stream.pos === 0) { + return checkDone(stream, callback); + } + ++stream.state.outstandingRequests; + // Create a new buffer to make sure the buffer isn't bigger than it needs + // to be. + const remnant = Buffer.alloc(stream.pos); + stream.bufToStore.copy(remnant, 0, 0, stream.pos); + const doc = createChunkDoc(stream.id, stream.n, remnant); + // If the stream was aborted, do not write remnant + if (checkAborted(stream, callback)) { + return false; + } + stream.chunks.insertOne(doc, getWriteOptions(stream), (error) => { + if (error) { + return __handleError(stream, error); + } + --stream.state.outstandingRequests; + checkDone(stream); + }); + return true; +} +function checkAborted(stream, callback) { + if (stream.state.aborted) { + if (typeof callback === 'function') { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosedError + callback(new error_1.MongoAPIError('Stream has been aborted')); + } + return true; + } + return false; +} +//# sourceMappingURL=upload.js.map + +/***/ }), + +/***/ 8821: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Logger = exports.Collection = exports.Db = exports.MongoClient = exports.Admin = exports.Promise = exports.MongoBulkWriteError = exports.MongoTopologyClosedError = exports.MongoServerClosedError = exports.MongoKerberosError = exports.MongoTransactionError = exports.MongoExpiredSessionError = exports.MongoNotConnectedError = exports.MongoCursorInUseError = exports.MongoCursorExhaustedError = exports.MongoBatchReExecutionError = exports.MongoDecompressionError = exports.MongoGridFSChunkError = exports.MongoGridFSStreamError = exports.MongoChangeStreamError = exports.MongoRuntimeError = exports.MongoWriteConcernError = exports.MongoParseError = exports.MongoServerSelectionError = exports.MongoSystemError = exports.MongoNetworkTimeoutError = exports.MongoNetworkError = exports.MongoMissingDependencyError = exports.MongoMissingCredentialsError = exports.MongoInvalidArgumentError = exports.MongoCompatibilityError = exports.MongoAPIError = exports.MongoDriverError = exports.MongoServerError = exports.MongoError = exports.ObjectID = exports.Map = exports.BSONSymbol = exports.BSONRegExp = exports.Decimal128 = exports.Timestamp = exports.ObjectId = exports.MaxKey = exports.MinKey = exports.Long = exports.Int32 = exports.Double = exports.DBRef = exports.Code = exports.Binary = void 0; +exports.SrvPollingEvent = exports.TopologyOpeningEvent = exports.TopologyDescriptionChangedEvent = exports.TopologyClosedEvent = exports.ServerOpeningEvent = exports.ServerDescriptionChangedEvent = exports.ServerClosedEvent = exports.ServerHeartbeatFailedEvent = exports.ServerHeartbeatSucceededEvent = exports.ServerHeartbeatStartedEvent = exports.ConnectionReadyEvent = exports.ConnectionPoolMonitoringEvent = exports.ConnectionPoolCreatedEvent = exports.ConnectionPoolClosedEvent = exports.ConnectionPoolClearedEvent = exports.ConnectionCreatedEvent = exports.ConnectionClosedEvent = exports.ConnectionCheckedOutEvent = exports.ConnectionCheckedInEvent = exports.ConnectionCheckOutStartedEvent = exports.ConnectionCheckOutFailedEvent = exports.CommandFailedEvent = exports.CommandSucceededEvent = exports.CommandStartedEvent = exports.ReadPreference = exports.ReadConcern = exports.WriteConcern = exports.BSONType = exports.ServerApiVersion = exports.ReadPreferenceMode = exports.ReadConcernLevel = exports.ExplainVerbosity = exports.ReturnDocument = exports.Compressor = exports.CURSOR_FLAGS = exports.AuthMechanism = exports.BatchType = exports.AutoEncryptionLoggerLevel = exports.LoggerLevel = exports.TopologyType = exports.ServerType = exports.ProfilingLevel = exports.CancellationToken = exports.GridFSBucket = exports.ListCollectionsCursor = exports.ListIndexesCursor = exports.FindCursor = exports.AggregationCursor = exports.AbstractCursor = void 0; +const abstract_cursor_1 = __nccwpck_require__(7349); +Object.defineProperty(exports, "AbstractCursor", ({ enumerable: true, get: function () { return abstract_cursor_1.AbstractCursor; } })); +const aggregation_cursor_1 = __nccwpck_require__(3363); +Object.defineProperty(exports, "AggregationCursor", ({ enumerable: true, get: function () { return aggregation_cursor_1.AggregationCursor; } })); +const find_cursor_1 = __nccwpck_require__(3930); +Object.defineProperty(exports, "FindCursor", ({ enumerable: true, get: function () { return find_cursor_1.FindCursor; } })); +const indexes_1 = __nccwpck_require__(4218); +Object.defineProperty(exports, "ListIndexesCursor", ({ enumerable: true, get: function () { return indexes_1.ListIndexesCursor; } })); +const list_collections_1 = __nccwpck_require__(840); +Object.defineProperty(exports, "ListCollectionsCursor", ({ enumerable: true, get: function () { return list_collections_1.ListCollectionsCursor; } })); +const promise_provider_1 = __nccwpck_require__(2725); +Object.defineProperty(exports, "Promise", ({ enumerable: true, get: function () { return promise_provider_1.PromiseProvider; } })); +const admin_1 = __nccwpck_require__(3238); +Object.defineProperty(exports, "Admin", ({ enumerable: true, get: function () { return admin_1.Admin; } })); +const mongo_client_1 = __nccwpck_require__(1545); +Object.defineProperty(exports, "MongoClient", ({ enumerable: true, get: function () { return mongo_client_1.MongoClient; } })); +const db_1 = __nccwpck_require__(6662); +Object.defineProperty(exports, "Db", ({ enumerable: true, get: function () { return db_1.Db; } })); +const collection_1 = __nccwpck_require__(5193); +Object.defineProperty(exports, "Collection", ({ enumerable: true, get: function () { return collection_1.Collection; } })); +const logger_1 = __nccwpck_require__(8874); +Object.defineProperty(exports, "Logger", ({ enumerable: true, get: function () { return logger_1.Logger; } })); +const gridfs_1 = __nccwpck_require__(5000); +Object.defineProperty(exports, "GridFSBucket", ({ enumerable: true, get: function () { return gridfs_1.GridFSBucket; } })); +const mongo_types_1 = __nccwpck_require__(696); +Object.defineProperty(exports, "CancellationToken", ({ enumerable: true, get: function () { return mongo_types_1.CancellationToken; } })); +var bson_1 = __nccwpck_require__(5578); +Object.defineProperty(exports, "Binary", ({ enumerable: true, get: function () { return bson_1.Binary; } })); +Object.defineProperty(exports, "Code", ({ enumerable: true, get: function () { return bson_1.Code; } })); +Object.defineProperty(exports, "DBRef", ({ enumerable: true, get: function () { return bson_1.DBRef; } })); +Object.defineProperty(exports, "Double", ({ enumerable: true, get: function () { return bson_1.Double; } })); +Object.defineProperty(exports, "Int32", ({ enumerable: true, get: function () { return bson_1.Int32; } })); +Object.defineProperty(exports, "Long", ({ enumerable: true, get: function () { return bson_1.Long; } })); +Object.defineProperty(exports, "MinKey", ({ enumerable: true, get: function () { return bson_1.MinKey; } })); +Object.defineProperty(exports, "MaxKey", ({ enumerable: true, get: function () { return bson_1.MaxKey; } })); +Object.defineProperty(exports, "ObjectId", ({ enumerable: true, get: function () { return bson_1.ObjectId; } })); +Object.defineProperty(exports, "Timestamp", ({ enumerable: true, get: function () { return bson_1.Timestamp; } })); +Object.defineProperty(exports, "Decimal128", ({ enumerable: true, get: function () { return bson_1.Decimal128; } })); +Object.defineProperty(exports, "BSONRegExp", ({ enumerable: true, get: function () { return bson_1.BSONRegExp; } })); +Object.defineProperty(exports, "BSONSymbol", ({ enumerable: true, get: function () { return bson_1.BSONSymbol; } })); +Object.defineProperty(exports, "Map", ({ enumerable: true, get: function () { return bson_1.Map; } })); +const bson_2 = __nccwpck_require__(1960); +/** + * @public + * @deprecated Please use `ObjectId` + */ +exports.ObjectID = bson_2.ObjectId; +var error_1 = __nccwpck_require__(9386); +Object.defineProperty(exports, "MongoError", ({ enumerable: true, get: function () { return error_1.MongoError; } })); +Object.defineProperty(exports, "MongoServerError", ({ enumerable: true, get: function () { return error_1.MongoServerError; } })); +Object.defineProperty(exports, "MongoDriverError", ({ enumerable: true, get: function () { return error_1.MongoDriverError; } })); +Object.defineProperty(exports, "MongoAPIError", ({ enumerable: true, get: function () { return error_1.MongoAPIError; } })); +Object.defineProperty(exports, "MongoCompatibilityError", ({ enumerable: true, get: function () { return error_1.MongoCompatibilityError; } })); +Object.defineProperty(exports, "MongoInvalidArgumentError", ({ enumerable: true, get: function () { return error_1.MongoInvalidArgumentError; } })); +Object.defineProperty(exports, "MongoMissingCredentialsError", ({ enumerable: true, get: function () { return error_1.MongoMissingCredentialsError; } })); +Object.defineProperty(exports, "MongoMissingDependencyError", ({ enumerable: true, get: function () { return error_1.MongoMissingDependencyError; } })); +Object.defineProperty(exports, "MongoNetworkError", ({ enumerable: true, get: function () { return error_1.MongoNetworkError; } })); +Object.defineProperty(exports, "MongoNetworkTimeoutError", ({ enumerable: true, get: function () { return error_1.MongoNetworkTimeoutError; } })); +Object.defineProperty(exports, "MongoSystemError", ({ enumerable: true, get: function () { return error_1.MongoSystemError; } })); +Object.defineProperty(exports, "MongoServerSelectionError", ({ enumerable: true, get: function () { return error_1.MongoServerSelectionError; } })); +Object.defineProperty(exports, "MongoParseError", ({ enumerable: true, get: function () { return error_1.MongoParseError; } })); +Object.defineProperty(exports, "MongoWriteConcernError", ({ enumerable: true, get: function () { return error_1.MongoWriteConcernError; } })); +Object.defineProperty(exports, "MongoRuntimeError", ({ enumerable: true, get: function () { return error_1.MongoRuntimeError; } })); +Object.defineProperty(exports, "MongoChangeStreamError", ({ enumerable: true, get: function () { return error_1.MongoChangeStreamError; } })); +Object.defineProperty(exports, "MongoGridFSStreamError", ({ enumerable: true, get: function () { return error_1.MongoGridFSStreamError; } })); +Object.defineProperty(exports, "MongoGridFSChunkError", ({ enumerable: true, get: function () { return error_1.MongoGridFSChunkError; } })); +Object.defineProperty(exports, "MongoDecompressionError", ({ enumerable: true, get: function () { return error_1.MongoDecompressionError; } })); +Object.defineProperty(exports, "MongoBatchReExecutionError", ({ enumerable: true, get: function () { return error_1.MongoBatchReExecutionError; } })); +Object.defineProperty(exports, "MongoCursorExhaustedError", ({ enumerable: true, get: function () { return error_1.MongoCursorExhaustedError; } })); +Object.defineProperty(exports, "MongoCursorInUseError", ({ enumerable: true, get: function () { return error_1.MongoCursorInUseError; } })); +Object.defineProperty(exports, "MongoNotConnectedError", ({ enumerable: true, get: function () { return error_1.MongoNotConnectedError; } })); +Object.defineProperty(exports, "MongoExpiredSessionError", ({ enumerable: true, get: function () { return error_1.MongoExpiredSessionError; } })); +Object.defineProperty(exports, "MongoTransactionError", ({ enumerable: true, get: function () { return error_1.MongoTransactionError; } })); +Object.defineProperty(exports, "MongoKerberosError", ({ enumerable: true, get: function () { return error_1.MongoKerberosError; } })); +Object.defineProperty(exports, "MongoServerClosedError", ({ enumerable: true, get: function () { return error_1.MongoServerClosedError; } })); +Object.defineProperty(exports, "MongoTopologyClosedError", ({ enumerable: true, get: function () { return error_1.MongoTopologyClosedError; } })); +var common_1 = __nccwpck_require__(4239); +Object.defineProperty(exports, "MongoBulkWriteError", ({ enumerable: true, get: function () { return common_1.MongoBulkWriteError; } })); +// enums +var set_profiling_level_1 = __nccwpck_require__(6301); +Object.defineProperty(exports, "ProfilingLevel", ({ enumerable: true, get: function () { return set_profiling_level_1.ProfilingLevel; } })); +var common_2 = __nccwpck_require__(472); +Object.defineProperty(exports, "ServerType", ({ enumerable: true, get: function () { return common_2.ServerType; } })); +Object.defineProperty(exports, "TopologyType", ({ enumerable: true, get: function () { return common_2.TopologyType; } })); +var logger_2 = __nccwpck_require__(8874); +Object.defineProperty(exports, "LoggerLevel", ({ enumerable: true, get: function () { return logger_2.LoggerLevel; } })); +var deps_1 = __nccwpck_require__(6763); +Object.defineProperty(exports, "AutoEncryptionLoggerLevel", ({ enumerable: true, get: function () { return deps_1.AutoEncryptionLoggerLevel; } })); +var common_3 = __nccwpck_require__(4239); +Object.defineProperty(exports, "BatchType", ({ enumerable: true, get: function () { return common_3.BatchType; } })); +var defaultAuthProviders_1 = __nccwpck_require__(7162); +Object.defineProperty(exports, "AuthMechanism", ({ enumerable: true, get: function () { return defaultAuthProviders_1.AuthMechanism; } })); +var abstract_cursor_2 = __nccwpck_require__(7349); +Object.defineProperty(exports, "CURSOR_FLAGS", ({ enumerable: true, get: function () { return abstract_cursor_2.CURSOR_FLAGS; } })); +var compression_1 = __nccwpck_require__(807); +Object.defineProperty(exports, "Compressor", ({ enumerable: true, get: function () { return compression_1.Compressor; } })); +var find_and_modify_1 = __nccwpck_require__(711); +Object.defineProperty(exports, "ReturnDocument", ({ enumerable: true, get: function () { return find_and_modify_1.ReturnDocument; } })); +var explain_1 = __nccwpck_require__(5293); +Object.defineProperty(exports, "ExplainVerbosity", ({ enumerable: true, get: function () { return explain_1.ExplainVerbosity; } })); +var read_concern_1 = __nccwpck_require__(7289); +Object.defineProperty(exports, "ReadConcernLevel", ({ enumerable: true, get: function () { return read_concern_1.ReadConcernLevel; } })); +var read_preference_1 = __nccwpck_require__(9802); +Object.defineProperty(exports, "ReadPreferenceMode", ({ enumerable: true, get: function () { return read_preference_1.ReadPreferenceMode; } })); +var mongo_client_2 = __nccwpck_require__(1545); +Object.defineProperty(exports, "ServerApiVersion", ({ enumerable: true, get: function () { return mongo_client_2.ServerApiVersion; } })); +var mongo_types_2 = __nccwpck_require__(696); +Object.defineProperty(exports, "BSONType", ({ enumerable: true, get: function () { return mongo_types_2.BSONType; } })); +// Helper classes +var write_concern_1 = __nccwpck_require__(2481); +Object.defineProperty(exports, "WriteConcern", ({ enumerable: true, get: function () { return write_concern_1.WriteConcern; } })); +var read_concern_2 = __nccwpck_require__(7289); +Object.defineProperty(exports, "ReadConcern", ({ enumerable: true, get: function () { return read_concern_2.ReadConcern; } })); +var read_preference_2 = __nccwpck_require__(9802); +Object.defineProperty(exports, "ReadPreference", ({ enumerable: true, get: function () { return read_preference_2.ReadPreference; } })); +// events +var command_monitoring_events_1 = __nccwpck_require__(5975); +Object.defineProperty(exports, "CommandStartedEvent", ({ enumerable: true, get: function () { return command_monitoring_events_1.CommandStartedEvent; } })); +Object.defineProperty(exports, "CommandSucceededEvent", ({ enumerable: true, get: function () { return command_monitoring_events_1.CommandSucceededEvent; } })); +Object.defineProperty(exports, "CommandFailedEvent", ({ enumerable: true, get: function () { return command_monitoring_events_1.CommandFailedEvent; } })); +var connection_pool_events_1 = __nccwpck_require__(8191); +Object.defineProperty(exports, "ConnectionCheckOutFailedEvent", ({ enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckOutFailedEvent; } })); +Object.defineProperty(exports, "ConnectionCheckOutStartedEvent", ({ enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckOutStartedEvent; } })); +Object.defineProperty(exports, "ConnectionCheckedInEvent", ({ enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckedInEvent; } })); +Object.defineProperty(exports, "ConnectionCheckedOutEvent", ({ enumerable: true, get: function () { return connection_pool_events_1.ConnectionCheckedOutEvent; } })); +Object.defineProperty(exports, "ConnectionClosedEvent", ({ enumerable: true, get: function () { return connection_pool_events_1.ConnectionClosedEvent; } })); +Object.defineProperty(exports, "ConnectionCreatedEvent", ({ enumerable: true, get: function () { return connection_pool_events_1.ConnectionCreatedEvent; } })); +Object.defineProperty(exports, "ConnectionPoolClearedEvent", ({ enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolClearedEvent; } })); +Object.defineProperty(exports, "ConnectionPoolClosedEvent", ({ enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolClosedEvent; } })); +Object.defineProperty(exports, "ConnectionPoolCreatedEvent", ({ enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolCreatedEvent; } })); +Object.defineProperty(exports, "ConnectionPoolMonitoringEvent", ({ enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolMonitoringEvent; } })); +Object.defineProperty(exports, "ConnectionReadyEvent", ({ enumerable: true, get: function () { return connection_pool_events_1.ConnectionReadyEvent; } })); +var events_1 = __nccwpck_require__(2464); +Object.defineProperty(exports, "ServerHeartbeatStartedEvent", ({ enumerable: true, get: function () { return events_1.ServerHeartbeatStartedEvent; } })); +Object.defineProperty(exports, "ServerHeartbeatSucceededEvent", ({ enumerable: true, get: function () { return events_1.ServerHeartbeatSucceededEvent; } })); +Object.defineProperty(exports, "ServerHeartbeatFailedEvent", ({ enumerable: true, get: function () { return events_1.ServerHeartbeatFailedEvent; } })); +Object.defineProperty(exports, "ServerClosedEvent", ({ enumerable: true, get: function () { return events_1.ServerClosedEvent; } })); +Object.defineProperty(exports, "ServerDescriptionChangedEvent", ({ enumerable: true, get: function () { return events_1.ServerDescriptionChangedEvent; } })); +Object.defineProperty(exports, "ServerOpeningEvent", ({ enumerable: true, get: function () { return events_1.ServerOpeningEvent; } })); +Object.defineProperty(exports, "TopologyClosedEvent", ({ enumerable: true, get: function () { return events_1.TopologyClosedEvent; } })); +Object.defineProperty(exports, "TopologyDescriptionChangedEvent", ({ enumerable: true, get: function () { return events_1.TopologyDescriptionChangedEvent; } })); +Object.defineProperty(exports, "TopologyOpeningEvent", ({ enumerable: true, get: function () { return events_1.TopologyOpeningEvent; } })); +var srv_polling_1 = __nccwpck_require__(3819); +Object.defineProperty(exports, "SrvPollingEvent", ({ enumerable: true, get: function () { return srv_polling_1.SrvPollingEvent; } })); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 8874: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Logger = exports.LoggerLevel = void 0; +const util_1 = __nccwpck_require__(1669); +const utils_1 = __nccwpck_require__(1371); +const error_1 = __nccwpck_require__(9386); +// Filters for classes +const classFilters = {}; +let filteredClasses = {}; +let level; +// Save the process id +const pid = process.pid; +// current logger +// eslint-disable-next-line no-console +let currentLogger = console.warn; +/** @public */ +exports.LoggerLevel = Object.freeze({ + ERROR: 'error', + WARN: 'warn', + INFO: 'info', + DEBUG: 'debug', + error: 'error', + warn: 'warn', + info: 'info', + debug: 'debug' +}); +/** + * @public + */ +class Logger { + /** + * Creates a new Logger instance + * + * @param className - The Class name associated with the logging instance + * @param options - Optional logging settings + */ + constructor(className, options) { + options = options !== null && options !== void 0 ? options : {}; + // Current reference + this.className = className; + // Current logger + if (!(options.logger instanceof Logger) && typeof options.logger === 'function') { + currentLogger = options.logger; } - - // 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, + // Set level of logging, default is error + if (options.loggerLevel) { + level = options.loggerLevel || exports.LoggerLevel.ERROR; + } + // Add all class names + if (filteredClasses[this.className] == null) { + classFilters[this.className] = true; + } + } + /** + * Log a message at the debug level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + debug(message, object) { + if (this.isDebug() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))) { + const dateTime = new Date().getTime(); + const msg = (0, util_1.format)('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); + const state = { + type: exports.LoggerLevel.DEBUG, + message, + className: this.className, + pid, + date: dateTime + }; + if (object) + state.meta = object; + currentLogger(msg, state); + } + } + /** + * Log a message at the warn level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + warn(message, object) { + if (this.isWarn() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))) { + const dateTime = new Date().getTime(); + const msg = (0, util_1.format)('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); + const state = { + type: exports.LoggerLevel.WARN, + message, + className: this.className, + pid, + date: dateTime + }; + if (object) + state.meta = object; + currentLogger(msg, state); + } + } + /** + * Log a message at the info level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + info(message, object) { + if (this.isInfo() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))) { + const dateTime = new Date().getTime(); + const msg = (0, util_1.format)('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); + const state = { + type: exports.LoggerLevel.INFO, + message, + className: this.className, + pid, + date: dateTime + }; + if (object) + state.meta = object; + currentLogger(msg, state); + } + } + /** + * Log a message at the error level + * + * @param message - The message to log + * @param object - Additional meta data to log + */ + error(message, object) { + if (this.isError() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className]))) { + const dateTime = new Date().getTime(); + const msg = (0, util_1.format)('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); + const state = { + type: exports.LoggerLevel.ERROR, + message, + className: this.className, + pid, + date: dateTime + }; + if (object) + state.meta = object; + currentLogger(msg, state); + } + } + /** Is the logger set at info level */ + isInfo() { + return level === exports.LoggerLevel.INFO || level === exports.LoggerLevel.DEBUG; + } + /** Is the logger set at error level */ + isError() { + return level === exports.LoggerLevel.ERROR || level === exports.LoggerLevel.INFO || level === exports.LoggerLevel.DEBUG; + } + /** Is the logger set at error level */ + isWarn() { + return (level === exports.LoggerLevel.ERROR || + level === exports.LoggerLevel.WARN || + level === exports.LoggerLevel.INFO || + level === exports.LoggerLevel.DEBUG); + } + /** Is the logger set at debug level */ + isDebug() { + return level === exports.LoggerLevel.DEBUG; + } + /** Resets the logger to default settings, error and no filtered classes */ + static reset() { + level = exports.LoggerLevel.ERROR; + filteredClasses = {}; + } + /** Get the current logger function */ + static currentLogger() { + return currentLogger; + } + /** + * Set the current logger function + * + * @param logger - Custom logging function + */ + static setCurrentLogger(logger) { + if (typeof logger !== 'function') { + throw new error_1.MongoInvalidArgumentError('Current logger must be a function'); + } + currentLogger = logger; + } + /** + * Filter log messages for a particular class + * + * @param type - The type of filter (currently only class) + * @param values - The filters to apply + */ + static filter(type, values) { + if (type === 'class' && Array.isArray(values)) { + filteredClasses = {}; + values.forEach(x => (filteredClasses[x] = true)); + } + } + /** + * Set the current log level + * + * @param newLevel - Set current log level (debug, warn, info, error) + */ + static setLevel(newLevel) { + if (newLevel !== exports.LoggerLevel.INFO && + newLevel !== exports.LoggerLevel.ERROR && + newLevel !== exports.LoggerLevel.DEBUG && + newLevel !== exports.LoggerLevel.WARN) { + throw new error_1.MongoInvalidArgumentError(`Argument "newLevel" should be one of ${(0, utils_1.enumToString)(exports.LoggerLevel)}`); + } + level = newLevel; + } +} +exports.Logger = Logger; +//# sourceMappingURL=logger.js.map + +/***/ }), + +/***/ 1545: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MongoClient = exports.ServerApiVersion = void 0; +const db_1 = __nccwpck_require__(6662); +const change_stream_1 = __nccwpck_require__(1117); +const error_1 = __nccwpck_require__(9386); +const utils_1 = __nccwpck_require__(1371); +const connect_1 = __nccwpck_require__(5210); +const promise_provider_1 = __nccwpck_require__(2725); +const bson_1 = __nccwpck_require__(5578); +const connection_string_1 = __nccwpck_require__(5341); +const mongo_types_1 = __nccwpck_require__(696); +/** @public */ +exports.ServerApiVersion = Object.freeze({ + v1: '1' +}); +/** @internal */ +const kOptions = Symbol('options'); +/** + * The **MongoClient** class is a class that allows for making Connections to MongoDB. + * @public + * + * @remarks + * The programmatically provided options take precedent over the URI options. + * + * @example + * ```js + * // 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 + * ```js + * // 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(); + * }); + * ``` + */ +class MongoClient extends mongo_types_1.TypedEventEmitter { + constructor(url, options) { + super(); + this[kOptions] = (0, connection_string_1.parseOptions)(url, this, options); + // eslint-disable-next-line @typescript-eslint/no-this-alias + const client = this; + // The internal state + this.s = { + url, + sessions: new Set(), + bsonOptions: (0, bson_1.resolveBSONOptions)(this[kOptions]), + namespace: (0, utils_1.ns)('admin'), + get options() { + return client[kOptions]; }, - (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 - ); + get readConcern() { + return client[kOptions].readConcern; + }, + get writeConcern() { + return client[kOptions].writeConcern; + }, + get readPreference() { + return client[kOptions].readPreference; + }, + get logger() { + return client[kOptions].logger; } - ); }; - } - - 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), + } + get options() { + return Object.freeze({ ...this[kOptions] }); + } + get serverApi() { + return this[kOptions].serverApi && Object.freeze({ ...this[kOptions].serverApi }); + } + /** + * Intended for APM use only + * @internal + */ + get monitorCommands() { + return this[kOptions].monitorCommands; + } + set monitorCommands(value) { + this[kOptions].monitorCommands = value; + } + get autoEncrypter() { + return this[kOptions].autoEncrypter; + } + get readConcern() { + return this.s.readConcern; + } + get writeConcern() { + return this.s.writeConcern; + } + get readPreference() { + return this.s.readPreference; + } + get bsonOptions() { + return this.s.bsonOptions; + } + get logger() { + return this.s.logger; + } + connect(callback) { + if (callback && typeof callback !== 'function') { + throw new error_1.MongoInvalidArgumentError('Method `connect` only accepts a callback'); + } + return (0, utils_1.maybePromise)(callback, cb => { + (0, connect_1.connect)(this, this[kOptions], err => { + if (err) + return cb(err); + cb(undefined, this); }); - - 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" || - event === "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 - ) - ) - ); + }); + } + close(forceOrCallback, callback) { + if (typeof forceOrCallback === 'function') { + callback = forceOrCallback; + } + const force = typeof forceOrCallback === 'boolean' ? forceOrCallback : false; + return (0, utils_1.maybePromise)(callback, callback => { + if (this.topology == null) { + return callback(); + } + // clear out references to old topology + const topology = this.topology; + this.topology = undefined; + topology.close({ force }, error => { + if (error) + return callback(error); + const { encrypter } = this[kOptions]; + if (encrypter) { + return encrypter.close(this, force, error => { + callback(error); + }); + } + callback(); + }); + }); + } + /** + * Create a new Db instance sharing the current socket connections. + * + * @param dbName - The name of the database we want to use. If not provided, use database name from connection string. + * @param options - Optional settings for Db construction + */ + db(dbName, options) { + options = options !== null && options !== void 0 ? options : {}; + // Default to db from connection string if not provided + if (!dbName) { + dbName = this.options.dbName; + } + // Copy the options and add out internal override of the not shared flag + const finalOptions = Object.assign({}, this[kOptions], options); + // Return the db object + const db = new db_1.Db(this, dbName, finalOptions); + // Return the database + return db; + } + static connect(url, options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = options !== null && options !== void 0 ? options : {}; + try { + // Create client + const mongoClient = new MongoClient(url, options); + // Execute the connect method + if (callback) { + return mongoClient.connect(callback); } - - // 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); + else { + return mongoClient.connect(); } - - // 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) }); + catch (error) { + if (callback) + return callback(error); + else + return promise_provider_1.PromiseProvider.get().reject(error); } - - // Emit opening server event - self.emit("serverOpening", { - topologyId: topologyId(self), - address: self.name, + } + startSession(options) { + options = Object.assign({ explicit: true }, options); + if (!this.topology) { + throw new error_1.MongoNotConnectedError('MongoClient must be connected to start a session'); + } + return this.topology.startSession(options, this.s.options); + } + withSession(optionsOrOperation, callback) { + let options = optionsOrOperation; + if (typeof optionsOrOperation === 'function') { + callback = optionsOrOperation; + options = { owner: Symbol() }; + } + if (callback == null) { + throw new error_1.MongoInvalidArgumentError('Missing required callback parameter'); + } + const session = this.startSession(options); + const Promise = promise_provider_1.PromiseProvider.get(); + let cleanupHandler = ((err, result, opts) => { + // prevent multiple calls to cleanupHandler + cleanupHandler = () => { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('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); + } }); - - 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" - ); + try { + const result = callback(session); + return Promise.resolve(result).then(result => cleanupHandler(undefined, result, undefined), err => cleanupHandler(err, null, { throw: true })); } - } - - /** - * 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 || {}); + catch (err) { + return cleanupHandler(err, null, { throw: false }); } - - 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()) { - const extractedCommand = extractCommand(cmd); - self.s.logger.debug( - f( - "executing command [%s] against %s", - JSON.stringify({ - ns: ns, - cmd: extractedCommand.shouldRedact - ? `${extractedCommand.name} details REDACTED` - : cmd, - options: debugOptions(debugFields, options), - }), - self.name - ) - ); + } + /** + * 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. + * + * @param 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 options - Optional settings for the command + */ + watch(pipeline = [], options = {}) { + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; } - - // 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`) - ); + return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options)); + } + /** Return the mongo client logger */ + getLogger() { + return this.s.logger; + } +} +exports.MongoClient = MongoClient; +//# sourceMappingURL=mongo_client.js.map + +/***/ }), + +/***/ 696: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CancellationToken = exports.TypedEventEmitter = exports.BSONType = void 0; +const events_1 = __nccwpck_require__(8614); +/** @public */ +exports.BSONType = Object.freeze({ + double: 1, + string: 2, + object: 3, + array: 4, + binData: 5, + undefined: 6, + objectId: 7, + bool: 8, + date: 9, + null: 10, + regex: 11, + dbPointer: 12, + javascript: 13, + symbol: 14, + javascriptWithScope: 15, + int: 16, + timestamp: 17, + long: 18, + decimal: 19, + minKey: -1, + maxKey: 127 +}); +/** + * Typescript type safe event emitter + * @public + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class TypedEventEmitter extends events_1.EventEmitter { +} +exports.TypedEventEmitter = TypedEventEmitter; +/** @public */ +class CancellationToken extends TypedEventEmitter { +} +exports.CancellationToken = CancellationToken; +//# sourceMappingURL=mongo_types.js.map + +/***/ }), + +/***/ 7057: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AddUserOperation = void 0; +const crypto = __nccwpck_require__(6417); +const operation_1 = __nccwpck_require__(1018); +const command_1 = __nccwpck_require__(499); +const error_1 = __nccwpck_require__(9386); +const utils_1 = __nccwpck_require__(1371); +/** @internal */ +class AddUserOperation extends command_1.CommandOperation { + constructor(db, username, password, options) { + super(db, options); + this.db = db; + this.username = username; + this.password = password; + this.options = options !== null && options !== void 0 ? options : {}; + } + execute(server, session, callback) { + const db = this.db; + const username = this.username; + const password = this.password; + const options = this.options; + // Error out if digestPassword set + if (options.digestPassword != null) { + return callback(new error_1.MongoInvalidArgumentError('Option "digestPassword" not supported via addUser, use db.command(...) instead')); } - - 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`) - ); + let roles; + if (!options.roles || (Array.isArray(options.roles) && options.roles.length === 0)) { + (0, utils_1.emitWarningOnce)('Creating a user without roles is deprecated. Defaults to "root" if db is "admin" or "dbOwner" otherwise'); + if (db.databaseName.toLowerCase() === 'admin') { + roles = ['root']; + } + else { + roles = ['dbOwner']; + } } - - // 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`) - ); + else { + roles = Array.isArray(options.roles) ? options.roles : [options.roles]; } - - // 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; + const digestPassword = (0, utils_1.getTopology)(db).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; } - - if (typeof options === "function") { - callback = options; - options = {}; + super.executeCommand(server, session, command, callback); + } +} +exports.AddUserOperation = AddUserOperation; +(0, operation_1.defineAspects)(AddUserOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=add_user.js.map + +/***/ }), + +/***/ 1554: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AggregateOperation = exports.DB_AGGREGATE_COLLECTION = void 0; +const command_1 = __nccwpck_require__(499); +const error_1 = __nccwpck_require__(9386); +const utils_1 = __nccwpck_require__(1371); +const operation_1 = __nccwpck_require__(1018); +/** @internal */ +exports.DB_AGGREGATE_COLLECTION = 1; +const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8; +/** @internal */ +class AggregateOperation extends command_1.CommandOperation { + constructor(ns, pipeline, options) { + super(undefined, { ...options, dbName: ns.db }); + this.options = options !== null && options !== void 0 ? options : {}; + // Covers when ns.collection is null, undefined or the empty string, use DB_AGGREGATE_COLLECTION + this.target = ns.collection || exports.DB_AGGREGATE_COLLECTION; + this.pipeline = pipeline; + // determine if we have a write stage, override read preference if so + this.hasWriteStage = false; + if (typeof (options === null || options === void 0 ? void 0 : options.out) === 'string') { + this.pipeline = this.pipeline.concat({ $out: options.out }); + this.hasWriteStage = true; } - - 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); + else if (pipeline.length > 0) { + const finalStage = pipeline[pipeline.length - 1]; + if (finalStage.$out || finalStage.$merge) { + this.hasWriteStage = true; + } } - - // No pool, return - if (!self.s.pool || this._destroyed) { - this._destroyed = true; - if (typeof callback === "function") callback(null, null); - return; + if (this.hasWriteStage) { + this.trySecondaryWrite = true; } - - this._destroyed = true; - - // Emit close event - if (options.emitClose) { - self.emit("close", self); + if (this.explain && this.writeConcern) { + throw new error_1.MongoInvalidArgumentError('Option "explain" cannot be used on an aggregate call with writeConcern'); } - - // Emit destroy event - if (options.emitDestroy) { - self.emit("destroy", self); + if ((options === null || options === void 0 ? void 0 : options.cursor) != null && typeof options.cursor !== 'object') { + throw new error_1.MongoInvalidArgumentError('Cursor options must be an object'); } - - // 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) }); + } + get canRetryRead() { + return !this.hasWriteStage; + } + addToPipeline(stage) { + this.pipeline.push(stage); + } + execute(server, session, callback) { + const options = this.options; + const serverWireVersion = (0, utils_1.maxWireVersion)(server); + const command = { aggregate: this.target, pipeline: this.pipeline }; + if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { + this.readConcern = undefined; } - - if (self.s.logger.isDebug()) { - self.s.logger.debug(f("destroy called on server %s", self.name)); + if (serverWireVersion >= 5) { + if (this.hasWriteStage && this.writeConcern) { + Object.assign(command, { writeConcern: this.writeConcern }); + } } - - // Destroy the pool - this.s.pool.destroy(options.force, callback); - }; - - /** - * 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, - __nccwpck_require__ - ) => { - "use strict"; - - const ReadPreference = __nccwpck_require__(4485); - const TopologyType = __nccwpck_require__(2291).TopologyType; - const MongoError = __nccwpck_require__(3111).MongoError; - const isRetryableWriteError = - __nccwpck_require__(3111).isRetryableWriteError; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const MongoNetworkError = __nccwpck_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", - }; + if (options.bypassDocumentValidation === true) { + command.bypassDocumentValidation = options.bypassDocumentValidation; } - - 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; + if (typeof options.allowDiskUse === 'boolean') { + command.allowDiskUse = options.allowDiskUse; } - }; - - var getPreviousTopologyDescription = function (self) { - if (!self.s.topologyDescription) { - self.s.topologyDescription = { - topologyType: "Unknown", - servers: [ - { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: "Unknown", - }, - ], - }; + if (options.hint) { + command.hint = options.hint; } - - 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; + if (options.let) { + command.let = options.let; } - }; - - 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; + command.cursor = options.cursor || {}; + if (options.batchSize && !this.hasWriteStage) { + command.cursor.batchSize = options.batchSize; } - - 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 - ); + super.executeCommand(server, session, command, callback); + } +} +exports.AggregateOperation = AggregateOperation; +(0, operation_1.defineAspects)(AggregateOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=aggregate.js.map + +/***/ }), + +/***/ 6976: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BulkWriteOperation = void 0; +const operation_1 = __nccwpck_require__(1018); +/** @internal */ +class BulkWriteOperation extends operation_1.AbstractOperation { + constructor(collection, operations, options) { + super(options); + this.options = options; + this.collection = collection; + this.operations = operations; + } + execute(server, session, callback) { + const coll = this.collection; + const operations = this.operations; + const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference }; + // Create the bulk operation + const bulk = options.ordered === false + ? coll.initializeUnorderedBulkOp(options) + : coll.initializeOrderedBulkOp(options); + // for each op go through and add to the bulk + try { + for (let i = 0; i < operations.length; i++) { + bulk.raw(operations[i]); } - ); - }; - }; - - // - // 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: [] }; + catch (err) { + return callback(err); } - - // 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; + // Execute the bulk + bulk.execute({ ...options, session }, (err, r) => { + // We have connection level error + if (!r && err) { + return callback(err); } - } - - if (!found) { - // Add to the diff - diff.servers.push({ - address: previous.servers[i].address, - from: previous.servers[i].type, - to: "Unknown", - }); - } + // Return the results + callback(undefined, r); + }); + } +} +exports.BulkWriteOperation = BulkWriteOperation; +(0, operation_1.defineAspects)(BulkWriteOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=bulk_write.js.map + +/***/ }), + +/***/ 286: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CollectionsOperation = void 0; +const operation_1 = __nccwpck_require__(1018); +const collection_1 = __nccwpck_require__(5193); +/** @internal */ +class CollectionsOperation extends operation_1.AbstractOperation { + constructor(db, options) { + super(options); + this.options = options; + this.db = db; + } + execute(server, session, callback) { + const db = this.db; + // Let's get the collection names + db.listCollections({}, { ...this.options, nameOnly: true, readPreference: this.readPreference, session }).toArray((err, documents) => { + if (err || !documents) + return callback(err); + // Filter collections removing any illegal ones + documents = documents.filter(doc => doc.name.indexOf('$') === -1); + // Return the collection objects + callback(undefined, documents.map(d => { + return new collection_1.Collection(db, d.name, db.s.options); + })); + }); + } +} +exports.CollectionsOperation = CollectionsOperation; +//# sourceMappingURL=collections.js.map + +/***/ }), + +/***/ 499: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CommandOperation = void 0; +const operation_1 = __nccwpck_require__(1018); +const read_concern_1 = __nccwpck_require__(7289); +const write_concern_1 = __nccwpck_require__(2481); +const utils_1 = __nccwpck_require__(1371); +const sessions_1 = __nccwpck_require__(5259); +const error_1 = __nccwpck_require__(9386); +const explain_1 = __nccwpck_require__(5293); +const server_selection_1 = __nccwpck_require__(2081); +const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; +/** @internal */ +class CommandOperation extends operation_1.AbstractOperation { + constructor(parent, options) { + super(options); + this.options = options !== null && options !== void 0 ? options : {}; + // NOTE: this was explicitly added for the add/remove user operations, it's likely + // something we'd want to reconsider. Perhaps those commands can use `Admin` + // as a parent? + const dbNameOverride = (options === null || options === void 0 ? void 0 : options.dbName) || (options === null || options === void 0 ? void 0 : options.authdb); + if (dbNameOverride) { + this.ns = new utils_1.MongoDBNamespace(dbNameOverride, '$cmd'); } - - // 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, - }); - } + else { + this.ns = parent + ? parent.s.namespace.withCollection('$cmd') + : new utils_1.MongoDBNamespace('admin', '$cmd'); } - - // 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, - }); - } - } - } + this.readConcern = read_concern_1.ReadConcern.fromOptions(options); + this.writeConcern = write_concern_1.WriteConcern.fromOptions(options); + // TODO(NODE-2056): make logger another "inheritable" property + if (parent && parent.logger) { + this.logger = parent.logger; } - - // 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; - } + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { + this.explain = explain_1.Explain.fromOptions(options); } - } - - // 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: - // 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(); + else if ((options === null || options === void 0 ? void 0 : options.explain) != null) { + throw new error_1.MongoInvalidArgumentError(`Option "explain" is not supported on this command`); + } + } + get canRetryWrite() { + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { + return this.explain == null; + } + return true; + } + executeCommand(server, session, cmd, callback) { + // TODO: consider making this a non-enumerable property + this.server = server; + const options = { + ...this.options, + ...this.bsonOptions, + readPreference: this.readPreference, + session + }; + const serverWireVersion = (0, utils_1.maxWireVersion)(server); + const inTransaction = this.session && this.session.inTransaction(); + if (this.readConcern && (0, sessions_1.commandSupportsReadConcern)(cmd) && !inTransaction) { + Object.assign(cmd, { readConcern: this.readConcern }); + } + if (this.trySecondaryWrite && serverWireVersion < server_selection_1.MIN_SECONDARY_WRITE_WIRE_VERSION) { + options.omitReadPreference = true; + } + if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation`)); + return; + } + if (this.writeConcern && this.hasAspect(operation_1.Aspect.WRITE_OPERATION) && !inTransaction) { + Object.assign(cmd, { writeConcern: this.writeConcern }); + } + if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + if (options.collation && + typeof options.collation === 'object' && + !this.hasAspect(operation_1.Aspect.SKIP_COLLATION)) { + Object.assign(cmd, { collation: options.collation }); } - ); - }, - }; - - 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; + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; } - - 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 (typeof options.comment === 'string') { + cmd.comment = options.comment; } - - if (!topology.logicalSessionTimeoutMinutes) { - return false; + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE) && this.explain) { + if (serverWireVersion < 6 && cmd.aggregate) { + // Prior to 3.6, with aggregate, verbosity is ignored, and we must pass in "explain: true" + cmd.explain = true; + } + else { + cmd = (0, utils_1.decorateWithExplain)(cmd, this.explain); + } } - - if (topologyType(topology) === TopologyType.Single) { - return false; + server.command(this.ns, cmd, options, callback); + } +} +exports.CommandOperation = CommandOperation; +//# sourceMappingURL=command.js.map + +/***/ }), + +/***/ 2296: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.prepareDocs = exports.indexInformation = void 0; +const error_1 = __nccwpck_require__(9386); +const utils_1 = __nccwpck_require__(1371); +function indexInformation(db, name, _optionsOrCallback, _callback) { + let options = _optionsOrCallback; + let callback = _callback; + if ('function' === typeof _optionsOrCallback) { + callback = _optionsOrCallback; + options = {}; + } + // If we specified full information + const full = options.full == null ? false : options.full; + // Did the user destroy the topology + if ((0, utils_1.getTopology)(db).isDestroyed()) + return callback(new error_1.MongoTopologyClosedError()); + // Process all the results from the index command and collection + function processResults(indexes) { + // Contains all the information + const 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 (const name in index.key) { + info[index.name].push([name, index.key[name]]); + } } - - 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; + return info; + } + // Get the list of indexes of the specified collection + db.collection(name) + .listIndexes(options) + .toArray((err, indexes) => { + if (err) + return callback(err); + if (!Array.isArray(indexes)) + return callback(undefined, []); + if (full) + return callback(undefined, indexes); + callback(undefined, processResults(indexes)); + }); +} +exports.indexInformation = indexInformation; +function prepareDocs(coll, docs, options) { + var _a; + const forceServerObjectId = typeof options.forceServerObjectId === 'boolean' + ? options.forceServerObjectId + : (_a = coll.s.db.options) === null || _a === void 0 ? void 0 : _a.forceServerObjectId; + // no need to modify the docs if server sets the ObjectId + if (forceServerObjectId === true) { + return docs; + } + return docs.map(doc => { + if (doc._id == null) { + doc._id = coll.s.pkFactory.createPk(); } - - // 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; + return doc; + }); +} +exports.prepareDocs = prepareDocs; +//# sourceMappingURL=common_functions.js.map + +/***/ }), + +/***/ 5210: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.connect = exports.MONGO_CLIENT_EVENTS = void 0; +const error_1 = __nccwpck_require__(9386); +const topology_1 = __nccwpck_require__(8827); +const connection_string_1 = __nccwpck_require__(5341); +const connection_pool_1 = __nccwpck_require__(2529); +const connection_1 = __nccwpck_require__(9820); +const server_1 = __nccwpck_require__(165); +/** @public */ +exports.MONGO_CLIENT_EVENTS = [ + ...connection_pool_1.CMAP_EVENTS, + ...connection_1.APM_EVENTS, + ...topology_1.TOPOLOGY_EVENTS, + ...server_1.HEARTBEAT_EVENTS +]; +function connect(mongoClient, options, callback) { + if (!callback) { + throw new error_1.MongoInvalidArgumentError('Callback function must be provided'); + } + // If a connection already been established, we can terminate early + if (mongoClient.topology && mongoClient.topology.isConnected()) { + return callback(undefined, mongoClient); + } + const logger = mongoClient.logger; + const connectCallback = err => { + 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 + // TODO(NODE-3483) + return callback(new error_1.MongoRuntimeError(warningMessage)); } - - // 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, - __nccwpck_require__ - ) => { - "use strict"; - - const MongoError = __nccwpck_require__(3111).MongoError; - const ReadPreference = __nccwpck_require__(4485); - const ReadConcern = __nccwpck_require__(7289); - const WriteConcern = __nccwpck_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" - ); + callback(err, mongoClient); + }; + if (typeof options.srvHost === 'string') { + return (0, connection_string_1.resolveSRVRecord)(options, (err, hosts) => { + if (err || !hosts) + return callback(err); + for (const [index, host] of hosts.entries()) { + options.hosts[index] = host; + } + return createTopology(mongoClient, options, connectCallback); + }); + } + return createTopology(mongoClient, options, connectCallback); +} +exports.connect = connect; +function createTopology(mongoClient, options, callback) { + // Create the topology + const topology = new topology_1.Topology(options.hosts, options); + // Events can be emitted before initialization is complete so we have to + // save the reference to the topology on the client ASAP if the event handlers need to access it + mongoClient.topology = topology; + topology.once(topology_1.Topology.OPEN, () => mongoClient.emit('open', mongoClient)); + for (const event of exports.MONGO_CLIENT_EVENTS) { + topology.on(event, (...args) => mongoClient.emit(event, ...args)); + } + // initialize CSFLE if requested + if (mongoClient.autoEncrypter) { + mongoClient.autoEncrypter.init(err => { + if (err) { + return callback(err); } + topology.connect(options, err => { + if (err) { + topology.close({ force: true }); + return callback(err); + } + options.encrypter.connectInternalClient(error => { + if (error) + return callback(error); + callback(undefined, topology); + }); + }); + }); + return; + } + // otherwise connect normally + topology.connect(options, err => { + if (err) { + topology.close({ force: true }); + return callback(err); + } + callback(undefined, topology); + return; + }); +} +//# sourceMappingURL=connect.js.map - this.options.writeConcern = writeConcern; - } - - if (options.readConcern) { - this.options.readConcern = ReadConcern.fromOptions(options); - } +/***/ }), - if (options.readPreference) { - this.options.readPreference = ReadPreference.fromOptions(options); - } +/***/ 7885: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (options.maxCommitTimeMS) { - this.options.maxTimeMS = options.maxCommitTimeMS; - } +"use strict"; - // TODO: This isn't technically necessary - this._pinnedServer = undefined; - this._recoveryToken = undefined; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CountOperation = void 0; +const operation_1 = __nccwpck_require__(1018); +const command_1 = __nccwpck_require__(499); +/** @internal */ +class CountOperation extends command_1.CommandOperation { + constructor(namespace, filter, options) { + super({ s: { namespace: namespace } }, options); + this.options = options; + this.collectionName = namespace.collection; + this.query = filter; + } + execute(server, session, callback) { + const options = this.options; + const cmd = { + count: this.collectionName, + query: this.query + }; + if (typeof options.limit === 'number') { + cmd.limit = options.limit; } - - get server() { - return this._pinnedServer; + if (typeof options.skip === 'number') { + cmd.skip = options.skip; } - - get recoveryToken() { - return this._recoveryToken; + if (options.hint != null) { + cmd.hint = options.hint; } - - get isPinned() { - return !!this.server; + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; } - - /** - * @ignore - * @return Whether this session is presently in a transaction - */ - get isActive() { - return ( - [ - TxnState.STARTING_TRANSACTION, - TxnState.TRANSACTION_IN_PROGRESS, - ].indexOf(this.state) !== -1 - ); + super.executeCommand(server, session, cmd, (err, result) => { + callback(err, result ? result.n : 0); + }); + } +} +exports.CountOperation = CountOperation; +(0, operation_1.defineAspects)(CountOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE]); +//# sourceMappingURL=count.js.map + +/***/ }), + +/***/ 5131: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CountDocumentsOperation = void 0; +const aggregate_1 = __nccwpck_require__(1554); +/** @internal */ +class CountDocumentsOperation extends aggregate_1.AggregateOperation { + constructor(collection, query, options) { + const pipeline = []; + pipeline.push({ $match: query }); + if (typeof options.skip === 'number') { + pipeline.push({ $skip: options.skip }); } - - /** - * 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(); + if (typeof options.limit === 'number') { + pipeline.push({ $limit: options.limit }); + } + pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); + super(collection.s.namespace, pipeline, options); + } + execute(server, session, callback) { + super.execute(server, session, (err, result) => { + if (err || !result) { + callback(err); + return; + } + // NOTE: We're avoiding creating a cursor here to reduce the callstack. + const response = result; + if (response.cursor == null || response.cursor.firstBatch == null) { + callback(undefined, 0); + return; + } + const docs = response.cursor.firstBatch; + callback(undefined, docs.length ? docs[0].n : 0); + }); + } +} +exports.CountDocumentsOperation = CountDocumentsOperation; +//# sourceMappingURL=count_documents.js.map + +/***/ }), + +/***/ 5561: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CreateCollectionOperation = void 0; +const command_1 = __nccwpck_require__(499); +const operation_1 = __nccwpck_require__(1018); +const collection_1 = __nccwpck_require__(5193); +const ILLEGAL_COMMAND_FIELDS = new Set([ + 'w', + 'wtimeout', + 'j', + 'fsync', + 'autoIndexId', + 'pkFactory', + 'raw', + 'readPreference', + 'session', + 'readConcern', + 'writeConcern', + 'raw', + 'fieldsAsRaw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bsonRegExp', + 'serializeFunctions', + 'ignoreUndefined' +]); +/** @internal */ +class CreateCollectionOperation extends command_1.CommandOperation { + constructor(db, name, options = {}) { + super(db, options); + this.options = options; + this.db = db; + this.name = name; + } + execute(server, session, callback) { + const db = this.db; + const name = this.name; + const options = this.options; + const done = err => { + if (err) { + return callback(err); + } + callback(undefined, new collection_1.Collection(db, name, options)); + }; + const cmd = { create: name }; + for (const n in options) { + if (options[n] != null && + typeof options[n] !== 'function' && + !ILLEGAL_COMMAND_FIELDS.has(n)) { + cmd[n] = options[n]; } - return; - } - - throw new MongoError( - `Attempted illegal state transition from [${this.state}] to [${nextState}]` - ); } - - pinServer(server) { - if (this.isActive) { - this._pinnedServer = server; - } + // otherwise just execute the command + super.executeCommand(server, session, cmd, done); + } +} +exports.CreateCollectionOperation = CreateCollectionOperation; +(0, operation_1.defineAspects)(CreateCollectionOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=create_collection.js.map + +/***/ }), + +/***/ 5831: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.makeDeleteStatement = exports.DeleteManyOperation = exports.DeleteOneOperation = exports.DeleteOperation = void 0; +const operation_1 = __nccwpck_require__(1018); +const command_1 = __nccwpck_require__(499); +const utils_1 = __nccwpck_require__(1371); +const error_1 = __nccwpck_require__(9386); +/** @internal */ +class DeleteOperation extends command_1.CommandOperation { + constructor(ns, statements, options) { + super(undefined, options); + this.options = options; + this.ns = ns; + this.statements = statements; + } + get canRetryWrite() { + if (super.canRetryWrite === false) { + return false; } - - unpinServer() { - this._pinnedServer = undefined; + return this.statements.every(op => (op.limit != null ? op.limit > 0 : true)); + } + execute(server, session, callback) { + var _a; + const options = (_a = this.options) !== null && _a !== void 0 ? _a : {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command = { + delete: this.ns.collection, + deletes: this.statements, + ordered + }; + if (options.let) { + command.let = options.let; + } + if (options.explain != null && (0, utils_1.maxWireVersion)(server) < 3) { + return callback + ? callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support explain on delete`)) + : undefined; + } + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite || (0, utils_1.maxWireVersion)(server) < 5) { + if (this.statements.find((o) => o.hint)) { + callback(new error_1.MongoCompatibilityError(`Servers < 3.4 do not support hint on delete`)); + return; + } } - } - - function isTransactionCommand(command) { - return !!(command.commitTransaction || command.abortTransaction); - } - - module.exports = { TxnState, Transaction, isTransactionCommand }; - - /***/ - }, - - /***/ 8767: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const URL = __nccwpck_require__(8835); - const qs = __nccwpck_require__(1191); - const dns = __nccwpck_require__(881); - const MongoParseError = __nccwpck_require__(3111).MongoParseError; - const ReadPreference = __nccwpck_require__(4485); - const emitWarningOnce = __nccwpck_require__(1371).emitWarningOnce; - - /** - * 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|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/; - - // Options that reference file paths should not be parsed - const FILE_PATH_OPTIONS = new Set( - [ - "sslCA", - "sslCert", - "sslKey", - "tlsCAFile", - "tlsCertificateKeyFile", - ].map((key) => key.toLowerCase()) - ); - - /** - * 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") - ); + const statementWithCollation = this.statements.find(statement => !!statement.collation); + if (statementWithCollation && (0, utils_1.collationNotSupported)(server, statementWithCollation)) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support collation`)); + return; } - - if (result.hostname.split(".").length < 3) { - return callback( - new MongoParseError( - "URI does not have hostname, domain name and tld" - ) - ); + super.executeCommand(server, session, command, callback); + } +} +exports.DeleteOperation = DeleteOperation; +class DeleteOneOperation extends DeleteOperation { + constructor(collection, filter, options) { + super(collection.s.namespace, [makeDeleteStatement(filter, { ...options, limit: 1 })], options); + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || res == null) + return callback(err); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) + return callback(new error_1.MongoServerError(res.writeErrors[0])); + if (this.explain) + return callback(undefined, res); + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + deletedCount: res.n + }); + }); + } +} +exports.DeleteOneOperation = DeleteOneOperation; +class DeleteManyOperation extends DeleteOperation { + constructor(collection, filter, options) { + super(collection.s.namespace, [makeDeleteStatement(filter, options)], options); + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || res == null) + return callback(err); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) + return callback(new error_1.MongoServerError(res.writeErrors[0])); + if (this.explain) + return callback(undefined, res); + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + deletedCount: res.n + }); + }); + } +} +exports.DeleteManyOperation = DeleteManyOperation; +function makeDeleteStatement(filter, options) { + const op = { + q: filter, + limit: typeof options.limit === 'number' ? options.limit : 0 + }; + if (options.single === true) { + op.limit = 1; + } + if (options.collation) { + op.collation = options.collation; + } + if (options.hint) { + op.hint = options.hint; + } + if (options.comment) { + op.comment = options.comment; + } + return op; +} +exports.makeDeleteStatement = makeDeleteStatement; +(0, operation_1.defineAspects)(DeleteOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(DeleteOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +(0, operation_1.defineAspects)(DeleteManyOperation, [ + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +//# sourceMappingURL=delete.js.map + +/***/ }), + +/***/ 6469: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DistinctOperation = void 0; +const operation_1 = __nccwpck_require__(1018); +const command_1 = __nccwpck_require__(499); +const utils_1 = __nccwpck_require__(1371); +const error_1 = __nccwpck_require__(9386); +/** + * Return a list of distinct values for the given key across a collection. + * @internal + */ +class DistinctOperation extends command_1.CommandOperation { + /** + * Construct a Distinct operation. + * + * @param collection - Collection instance. + * @param key - Field of the document to find distinct values for. + * @param query - The query for filtering the set of documents to which we apply the distinct filter. + * @param options - Optional settings. See Collection.prototype.distinct for a list of options. + */ + constructor(collection, key, query, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collection = collection; + this.key = key; + this.query = query; + } + execute(server, session, 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; } - - result.domainLength = result.hostname.split(".").length; - - const hostname = uri.substring("mongodb+srv://".length).split("/")[0]; - if (hostname.match(",")) { - return callback( - new MongoParseError( - "Invalid URI, cannot contain multiple hostnames" - ) - ); + // Do we have a readConcern specified + (0, utils_1.decorateWithReadConcern)(cmd, coll, options); + // Have we specified collation + try { + (0, utils_1.decorateWithCollation)(cmd, coll, options); } - - if (result.port) { - return callback( - new MongoParseError( - `Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs` - ) - ); + catch (err) { + return callback(err); } - - // 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 (this.explain && (0, utils_1.maxWireVersion)(server) < 4) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support explain on distinct`)); + return; + } + super.executeCommand(server, session, cmd, (err, result) => { if (err) { - if (err.code !== "ENODATA" && err.code !== "ENOTFOUND") { - return callback(err); - } - record = null; + callback(err); + return; } - - 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); + callback(undefined, this.explain ? result : result.values); + }); + } +} +exports.DistinctOperation = DistinctOperation; +(0, operation_1.defineAspects)(DistinctOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE, operation_1.Aspect.EXPLAINABLE]); +//# sourceMappingURL=distinct.js.map + +/***/ }), + +/***/ 2360: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DropDatabaseOperation = exports.DropCollectionOperation = void 0; +const operation_1 = __nccwpck_require__(1018); +const command_1 = __nccwpck_require__(499); +/** @internal */ +class DropCollectionOperation extends command_1.CommandOperation { + constructor(db, name, options) { + super(db, options); + this.options = options; + this.name = name; + } + execute(server, session, callback) { + super.executeCommand(server, session, { drop: this.name }, (err, result) => { + if (err) + return callback(err); + if (result.ok) + return callback(undefined, true); + callback(undefined, false); + }); + } +} +exports.DropCollectionOperation = DropCollectionOperation; +/** @internal */ +class DropDatabaseOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options; + } + execute(server, session, callback) { + super.executeCommand(server, session, { dropDatabase: 1 }, (err, result) => { + if (err) + return callback(err); + if (result.ok) + return callback(undefined, true); + callback(undefined, false); + }); + } +} +exports.DropDatabaseOperation = DropDatabaseOperation; +(0, operation_1.defineAspects)(DropCollectionOperation, [operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(DropDatabaseOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=drop.js.map + +/***/ }), + +/***/ 4451: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.EstimatedDocumentCountOperation = void 0; +const operation_1 = __nccwpck_require__(1018); +const command_1 = __nccwpck_require__(499); +const utils_1 = __nccwpck_require__(1371); +/** @internal */ +class EstimatedDocumentCountOperation extends command_1.CommandOperation { + constructor(collection, options = {}) { + super(collection, options); + this.options = options; + this.collectionName = collection.collectionName; + } + execute(server, session, callback) { + if ((0, utils_1.maxWireVersion)(server) < 12) { + return this.executeLegacy(server, session, callback); + } + const pipeline = [{ $collStats: { count: {} } }, { $group: { _id: 1, n: { $sum: '$count' } } }]; + const cmd = { aggregate: this.collectionName, pipeline, cursor: {} }; + if (typeof this.options.maxTimeMS === 'number') { + cmd.maxTimeMS = this.options.maxTimeMS; + } + super.executeCommand(server, session, cmd, (err, response) => { + var _a, _b; + if (err && err.code !== 26) { + callback(err); + return; } - - // 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(undefined, ((_b = (_a = response === null || response === void 0 ? void 0 : response.cursor) === null || _a === void 0 ? void 0 : _a.firstBatch[0]) === null || _b === void 0 ? void 0 : _b.n) || 0); + }); + } + executeLegacy(server, session, callback) { + const cmd = { count: this.collectionName }; + if (typeof this.options.maxTimeMS === 'number') { + cmd.maxTimeMS = this.options.maxTimeMS; + } + super.executeCommand(server, session, cmd, (err, response) => { + if (err) { callback(err); return; - } - - callback( - null, - Object.assign({}, ret, { srvHost: lookupAddress }) - ); - }); - }); + } + callback(undefined, response.n || 0); }); - } - - /** - * 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); - } + } +} +exports.EstimatedDocumentCountOperation = EstimatedDocumentCountOperation; +(0, operation_1.defineAspects)(EstimatedDocumentCountOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=estimated_document_count.js.map + +/***/ }), + +/***/ 2548: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.executeOperation = void 0; +const read_preference_1 = __nccwpck_require__(9802); +const error_1 = __nccwpck_require__(9386); +const operation_1 = __nccwpck_require__(1018); +const utils_1 = __nccwpck_require__(1371); +const utils_2 = __nccwpck_require__(1371); +const server_selection_1 = __nccwpck_require__(2081); +const MMAPv1_RETRY_WRITES_ERROR_CODE = error_1.MONGODB_ERROR_CODES.IllegalOperation; +const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.'; +function executeOperation(topology, operation, callback) { + if (!(operation instanceof operation_1.AbstractOperation)) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('This method requires a valid operation instance'); + } + return (0, utils_1.maybePromise)(callback, cb => { + if (topology.shouldCheckForSessionSupport()) { + return topology.selectServer(read_preference_1.ReadPreference.primaryPreferred, err => { + if (err) + return cb(err); + executeOperation(topology, operation, cb); + }); } - - 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`" - ); - } + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session = operation.session; + let owner; + if (topology.hasSessionSupport()) { + if (session == null) { + owner = Symbol(); + session = topology.startSession({ owner, explicit: false }); + } + else if (session.hasEnded) { + return cb(new error_1.MongoExpiredSessionError('Use of expired sessions is not permitted')); + } + else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) { + return cb(new error_1.MongoCompatibilityError('Snapshot reads require MongoDB 5.0 or later')); + } } - - if (key === "authmechanism" && !AUTH_MECHANISMS.has(value)) { - throw new MongoParseError( - `Value for authMechanism must be one of: ${Array.from( - AUTH_MECHANISMS - ).join(", ")}, found: ${value}` - ); + else if (session) { + // If the user passed an explicit session and we are still, after server selection, + // trying to run against a topology that doesn't support sessions we error out. + return cb(new error_1.MongoCompatibilityError('Current topology does not support sessions')); } - - if (key === "readpreference" && !ReadPreference.isValid(value)) { - throw new MongoParseError( - "Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`" - ); + try { + executeWithServerSelection(topology, session, operation, (err, result) => { + if (session && session.owner && session.owner === owner) { + return session.endSession(err2 => cb(err2 || err, result)); + } + cb(err, result); + }); } - - if (key === "zlibcompressionlevel" && (value < -1 || value > 9)) { - throw new MongoParseError( - "zlibCompressionLevel must be an integer between -1 and 9" - ); + catch (e) { + if (session && session.owner && session.owner === owner) { + session.endSession(); + } + throw e; } - - // special cases - if (key === "compressors" || key === "zlibcompressionlevel") { - obj.compression = obj.compression || {}; - obj = obj.compression; + }); +} +exports.executeOperation = executeOperation; +function supportsRetryableReads(server) { + return (0, utils_1.maxWireVersion)(server) >= 6; +} +function executeWithServerSelection(topology, session, operation, callback) { + var _a; + const readPreference = operation.readPreference || read_preference_1.ReadPreference.primary; + const inTransaction = session && session.inTransaction(); + if (inTransaction && !readPreference.equals(read_preference_1.ReadPreference.primary)) { + callback(new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`)); + return; + } + if (session && + session.isPinned && + session.transaction.isCommitted && + !operation.bypassPinningCheck) { + session.unpin(); + } + let selector; + if (operation.hasAspect(operation_1.Aspect.CURSOR_ITERATING)) { + // Get more operations must always select the same server, but run through + // server selection to potentially force monitor checks if the server is + // in an unknown state. + selector = (0, server_selection_1.sameServerSelector)((_a = operation.server) === null || _a === void 0 ? void 0 : _a.description); + } + else if (operation.trySecondaryWrite) { + // If operation should try to write to secondary use the custom server selector + // otherwise provide the read preference. + selector = (0, server_selection_1.secondaryWritableServerSelector)(topology.commonWireVersion, readPreference); + } + else { + selector = readPreference; + } + const serverSelectionOptions = { session }; + function callbackWithRetry(err, result) { + if (err == null) { + return callback(undefined, result); } - - 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; - } + const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION); + const hasWriteAspect = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION); + const itShouldRetryWrite = shouldRetryWrite(err); + if ((hasReadAspect && !(0, error_1.isRetryableError)(err)) || (hasWriteAspect && !itShouldRetryWrite)) { + return callback(err); } - - if (key === "readpreferencetags") { - value = Array.isArray(value) - ? splitArrayOfMultipleReadPreferenceTags(value) - : [value]; + if (hasWriteAspect && + itShouldRetryWrite && + err.code === MMAPv1_RETRY_WRITES_ERROR_CODE && + err.errmsg.match(/Transaction numbers/)) { + callback(new error_1.MongoServerError({ + message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + originalError: err + })); + return; } - - // set the actual value - if (options.caseTranslate && CASE_TRANSLATION[key]) { - obj[CASE_TRANSLATION[key]] = value; - return; + // select a new server, and attempt to retry the operation + topology.selectServer(selector, serverSelectionOptions, (e, server) => { + if (e || + (operation.hasAspect(operation_1.Aspect.READ_OPERATION) && !supportsRetryableReads(server)) || + (operation.hasAspect(operation_1.Aspect.WRITE_OPERATION) && !(0, utils_2.supportsRetryableWrites)(server))) { + callback(e); + return; + } + // If we have a cursor and the initial command fails with a network error, + // we can retry it on another connection. So we need to check it back in, clear the + // pool for the service id, and retry again. + if (err && + err instanceof error_1.MongoNetworkError && + server.loadBalanced && + session && + session.isPinned && + !session.inTransaction() && + operation.hasAspect(operation_1.Aspect.CURSOR_CREATING)) { + session.unpin({ force: true, forceClear: true }); + } + operation.execute(server, session, callback); + }); + } + if (readPreference && + !readPreference.equals(read_preference_1.ReadPreference.primary) && + session && + session.inTransaction()) { + callback(new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`)); + return; + } + // select a server, and execute the operation against it + topology.selectServer(selector, serverSelectionOptions, (err, server) => { + if (err) { + callback(err); + 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]; - }); + if (session && operation.hasAspect(operation_1.Aspect.RETRYABLE)) { + const willRetryRead = topology.s.options.retryReads !== false && + !inTransaction && + supportsRetryableReads(server) && + operation.canRetryRead; + const willRetryWrite = topology.s.options.retryWrites === true && + !inTransaction && + (0, utils_2.supportsRetryableWrites)(server) && + operation.canRetryWrite; + const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION); + const hasWriteAspect = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION); + if ((hasReadAspect && willRetryRead) || (hasWriteAspect && willRetryWrite)) { + if (hasWriteAspect && willRetryWrite) { + operation.options.willRetryWrite = true; + session.incrementTransactionNumber(); + } + operation.execute(server, session, callbackWithRetry); + return; + } + } + operation.execute(server, session, callback); + }); +} +function shouldRetryWrite(err) { + return err instanceof error_1.MongoError && err.hasErrorLabel('RetryableWriteError'); +} +//# sourceMappingURL=execute_operation.js.map + +/***/ }), + +/***/ 9961: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FindOperation = void 0; +const operation_1 = __nccwpck_require__(1018); +const utils_1 = __nccwpck_require__(1371); +const error_1 = __nccwpck_require__(9386); +const command_1 = __nccwpck_require__(499); +const sort_1 = __nccwpck_require__(8370); +const shared_1 = __nccwpck_require__(1580); +const read_concern_1 = __nccwpck_require__(7289); +const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; +/** @internal */ +class FindOperation extends command_1.CommandOperation { + constructor(collection, ns, filter = {}, options = {}) { + super(collection, options); + this.options = options; + this.ns = ns; + if (typeof filter !== 'object' || Array.isArray(filter)) { + throw new error_1.MongoInvalidArgumentError('Query filter must be a plain object or ObjectId'); + } + // If the filter is a buffer, validate that is a valid BSON document + if (Buffer.isBuffer(filter)) { + const objectSize = filter[0] | (filter[1] << 8) | (filter[2] << 16) | (filter[3] << 24); + if (objectSize !== filter.length) { + throw new error_1.MongoInvalidArgumentError(`Query filter raw message size does not match message header size [${filter.length}] != [${objectSize}]`); + } } - - 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; + // special case passing in an ObjectId as a filter + this.filter = filter != null && filter._bsontype === 'ObjectID' ? { _id: filter } : filter; + } + execute(server, session, callback) { + this.server = server; + const serverWireVersion = (0, utils_1.maxWireVersion)(server); + const options = this.options; + if (options.allowDiskUse != null && serverWireVersion < 4) { + callback(new error_1.MongoCompatibilityError('Option "allowDiskUse" is not supported on MongoDB < 3.2')); + return; } - - const options = parsed.options; - const authSource = options.authsource || options.authSource; - if (authSource != null) { - parsed.auth = Object.assign({}, parsed.auth, { db: authSource }); + if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation`)); + return; } - - 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.` - ); + if (serverWireVersion < 4) { + if (this.readConcern && this.readConcern.level !== 'local') { + callback(new error_1.MongoCompatibilityError(`Server find command does not support a readConcern level of ${this.readConcern.level}`)); + return; } - - 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" }); + const findCommand = makeLegacyFindCommand(this.ns, this.filter, options); + if ((0, shared_1.isSharded)(server) && this.readPreference) { + findCommand.$readPreference = this.readPreference.toJSON(); } - } - } - - // default to `admin` if nothing else was resolved - if (parsed.auth && parsed.auth.db == null) { - parsed.auth = Object.assign({}, parsed.auth, { db: "admin" }); + server.query(this.ns, findCommand, { + ...this.options, + ...this.bsonOptions, + documentsReturnedIn: 'firstBatch', + readPreference: this.readPreference + }, callback); + return; } - - 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 = FILE_PATH_OPTIONS.has(normalizedKey) - ? value - : parseQueryStringItemValue(normalizedKey, value); - applyConnectionStringOption( - result, - normalizedKey, - parsedValue, - options - ); + let findCommand = makeFindCommand(this.ns, this.filter, options); + if (this.explain) { + findCommand = (0, utils_1.decorateWithExplain)(findCommand, this.explain); } - - // special cases for known deprecated options - if (result.wtimeout && result.wtimeoutms) { - delete result.wtimeout; - emitWarningOnce("Unsupported option `wtimeout` specified"); + server.command(this.ns, findCommand, { + ...this.options, + ...this.bsonOptions, + documentsReturnedIn: 'firstBatch', + session + }, callback); + } +} +exports.FindOperation = FindOperation; +function makeFindCommand(ns, filter, options) { + const findCommand = { + find: ns.collection, + filter + }; + if (options.sort) { + findCommand.sort = (0, sort_1.formatSort)(options.sort); + } + if (options.projection) { + let projection = options.projection; + if (projection && Array.isArray(projection)) { + projection = projection.length + ? projection.reduce((result, field) => { + result[field] = 1; + return result; + }, {}) + : { _id: 1 }; } - - 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; + findCommand.projection = projection; + } + if (options.hint) { + findCommand.hint = (0, utils_1.normalizeHintField)(options.hint); + } + if (typeof options.skip === 'number') { + findCommand.skip = options.skip; + } + if (typeof options.limit === 'number') { + if (options.limit < 0) { + findCommand.limit = -options.limit; + findCommand.singleBatch = true; } - - if (queryString.tlsInsecure) { - queryString.checkServerIdentity = false; - queryString.sslValidate = false; - } else { - Object.assign(queryString, { - checkServerIdentity: queryString.tlsAllowInvalidHostnames - ? false - : true, - sslValidate: queryString.tlsAllowInvalidCertificates ? false : true, - }); + else { + findCommand.limit = options.limit; } - - if (queryString.tlsCAFile) { - queryString.ssl = true; - queryString.sslCA = queryString.tlsCAFile; + } + if (typeof options.batchSize === 'number') { + if (options.batchSize < 0) { + if (options.limit && + options.limit !== 0 && + Math.abs(options.batchSize) < Math.abs(options.limit)) { + findCommand.limit = -options.batchSize; + } + findCommand.singleBatch = true; } - - 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; - } + else { + findCommand.batchSize = options.batchSize; } - - if (queryString.tlsCertificateKeyFilePassword) { - queryString.ssl = true; - queryString.sslPass = queryString.tlsCertificateKeyFilePassword; + } + if (typeof options.singleBatch === 'boolean') { + findCommand.singleBatch = options.singleBatch; + } + if (options.comment) { + findCommand.comment = options.comment; + } + if (typeof options.maxTimeMS === 'number') { + findCommand.maxTimeMS = options.maxTimeMS; + } + const readConcern = read_concern_1.ReadConcern.fromOptions(options); + if (readConcern) { + findCommand.readConcern = readConcern.toJSON(); + } + if (options.max) { + findCommand.max = options.max; + } + if (options.min) { + findCommand.min = options.min; + } + if (typeof options.returnKey === 'boolean') { + findCommand.returnKey = options.returnKey; + } + if (typeof options.showRecordId === 'boolean') { + findCommand.showRecordId = options.showRecordId; + } + if (typeof options.tailable === 'boolean') { + findCommand.tailable = options.tailable; + } + if (typeof options.timeout === 'boolean') { + findCommand.noCursorTimeout = !options.timeout; + } + else if (typeof options.noCursorTimeout === 'boolean') { + findCommand.noCursorTimeout = options.noCursorTimeout; + } + if (typeof options.awaitData === 'boolean') { + findCommand.awaitData = options.awaitData; + } + if (typeof options.allowPartialResults === 'boolean') { + findCommand.allowPartialResults = options.allowPartialResults; + } + if (options.collation) { + findCommand.collation = options.collation; + } + if (typeof options.allowDiskUse === 'boolean') { + findCommand.allowDiskUse = options.allowDiskUse; + } + if (options.let) { + findCommand.let = options.let; + } + return findCommand; +} +function makeLegacyFindCommand(ns, filter, options) { + const findCommand = { + $query: filter + }; + if (options.sort) { + findCommand.$orderby = (0, sort_1.formatSort)(options.sort); + } + if (options.hint) { + findCommand.$hint = (0, utils_1.normalizeHintField)(options.hint); + } + if (typeof options.returnKey === 'boolean') { + findCommand.$returnKey = options.returnKey; + } + if (options.max) { + findCommand.$max = options.max; + } + if (options.min) { + findCommand.$min = options.min; + } + if (typeof options.showRecordId === 'boolean') { + findCommand.$showDiskLoc = options.showRecordId; + } + if (options.comment) { + findCommand.$comment = options.comment; + } + if (typeof options.maxTimeMS === 'number') { + findCommand.$maxTimeMS = options.maxTimeMS; + } + if (options.explain != null) { + findCommand.$explain = true; + } + return findCommand; +} +(0, operation_1.defineAspects)(FindOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=find.js.map + +/***/ }), + +/***/ 711: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FindOneAndUpdateOperation = exports.FindOneAndReplaceOperation = exports.FindOneAndDeleteOperation = exports.ReturnDocument = void 0; +const read_preference_1 = __nccwpck_require__(9802); +const utils_1 = __nccwpck_require__(1371); +const error_1 = __nccwpck_require__(9386); +const command_1 = __nccwpck_require__(499); +const operation_1 = __nccwpck_require__(1018); +const sort_1 = __nccwpck_require__(8370); +/** @public */ +exports.ReturnDocument = Object.freeze({ + BEFORE: 'before', + AFTER: 'after' +}); +function configureFindAndModifyCmdBaseUpdateOpts(cmdBase, options) { + cmdBase.new = options.returnDocument === exports.ReturnDocument.AFTER; + cmdBase.upsert = options.upsert === true; + if (options.bypassDocumentValidation === true) { + cmdBase.bypassDocumentValidation = options.bypassDocumentValidation; + } + return cmdBase; +} +/** @internal */ +class FindAndModifyOperation extends command_1.CommandOperation { + constructor(collection, query, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.cmdBase = { + remove: false, + new: false, + upsert: false + }; + const sort = (0, sort_1.formatSort)(options.sort); + if (sort) { + this.cmdBase.sort = sort; } - - 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`." - ); + if (options.projection) { + this.cmdBase.fields = options.projection; } - - 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." - ); - } + if (options.maxTimeMS) { + this.cmdBase.maxTimeMS = options.maxTimeMS; } - } - - /** - * 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]; + // Decorate the findAndModify command with the write Concern + if (options.writeConcern) { + this.cmdBase.writeConcern = options.writeConcern; } - - 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.` - ); - } - }); - } + if (options.let) { + this.cmdBase.let = options.let; } - - 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 + // force primary read preference + this.readPreference = read_preference_1.ReadPreference.primary; + this.collection = collection; + this.query = query; + } + execute(server, session, callback) { + var _a; + const coll = this.collection; + const query = this.query; + const options = { ...this.options, ...this.bsonOptions }; + // Create findAndModify command object + const cmd = { + findAndModify: coll.collectionName, + query: query, + ...this.cmdBase + }; + // Have we specified collation try { - URL.parse(uri); - } catch (e) { - return callback( - new MongoParseError("URI malformed, cannot be parsed") - ); + (0, utils_1.decorateWithCollation)(cmd, coll, options); } - - const cap = uri.match(HOSTS_RX); - if (!cap) { - return callback(new MongoParseError("Invalid connection string")); + catch (err) { + return callback(err); } - - const protocol = cap[1]; - if (SUPPORTED_PROTOCOLS.indexOf(protocol) === -1) { - return callback(new MongoParseError("Invalid protocol provided")); + if (options.hint) { + // TODO: once this method becomes a CommandOperation we will have the server + // in place to check. + const unacknowledgedWrite = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) === 0; + if (unacknowledgedWrite || (0, utils_1.maxWireVersion)(server) < 8) { + callback(new error_1.MongoCompatibilityError('The current topology does not support a hint on findAndModify commands')); + return; + } + cmd.hint = options.hint; } - - 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); + if (this.explain && (0, utils_1.maxWireVersion)(server) < 4) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support explain on findAndModify`)); + return; } - - parsedOptions = Object.assign({}, parsedOptions, options); - - if (protocol === PROTOCOL_MONGODB_SRV) { - return parseSrvConnectionString(uri, parsedOptions, callback); + // Execute the command + super.executeCommand(server, session, cmd, (err, result) => { + if (err) + return callback(err); + return callback(undefined, result); + }); + } +} +/** @internal */ +class FindOneAndDeleteOperation extends FindAndModifyOperation { + constructor(collection, filter, options) { + // Basic validation + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object'); + } + super(collection, filter, options); + this.cmdBase.remove = true; + } +} +exports.FindOneAndDeleteOperation = FindOneAndDeleteOperation; +/** @internal */ +class FindOneAndReplaceOperation extends FindAndModifyOperation { + constructor(collection, filter, replacement, options) { + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object'); + } + if (replacement == null || typeof replacement !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "replacement" must be an object'); + } + if ((0, utils_1.hasAtomicOperators)(replacement)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not contain atomic operators'); + } + super(collection, filter, options); + this.cmdBase.update = replacement; + configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); + } +} +exports.FindOneAndReplaceOperation = FindOneAndReplaceOperation; +/** @internal */ +class FindOneAndUpdateOperation extends FindAndModifyOperation { + constructor(collection, filter, update, options) { + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "filter" must be an object'); + } + if (update == null || typeof update !== 'object') { + throw new error_1.MongoInvalidArgumentError('Argument "update" must be an object'); + } + if (!(0, utils_1.hasAtomicOperators)(update)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + super(collection, filter, options); + this.cmdBase.update = update; + configureFindAndModifyCmdBaseUpdateOpts(this.cmdBase, options); + if (options.arrayFilters) { + this.cmdBase.arrayFilters = options.arrayFilters; } - - 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; + } +} +exports.FindOneAndUpdateOperation = FindOneAndUpdateOperation; +(0, operation_1.defineAspects)(FindAndModifyOperation, [ + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.EXPLAINABLE +]); +//# sourceMappingURL=find_and_modify.js.map + +/***/ }), + +/***/ 6819: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GetMoreOperation = void 0; +const error_1 = __nccwpck_require__(9386); +const operation_1 = __nccwpck_require__(1018); +/** @internal */ +class GetMoreOperation extends operation_1.AbstractOperation { + constructor(ns, cursorId, server, options = {}) { + super(options); + this.options = options; + this.ns = ns; + this.cursorId = cursorId; + this.server = server; + } + /** + * Although there is a server already associated with the get more operation, the signature + * for execute passes a server so we will just use that one. + */ + execute(server, session, callback) { + if (server !== this.server) { + return callback(new error_1.MongoRuntimeError('Getmore must run on the same server operation began on')); + } + server.getMore(this.ns, this.cursorId, this.options, callback); + } +} +exports.GetMoreOperation = GetMoreOperation; +(0, operation_1.defineAspects)(GetMoreOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.CURSOR_ITERATING]); +//# sourceMappingURL=get_more.js.map + +/***/ }), + +/***/ 4218: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.IndexInformationOperation = exports.IndexExistsOperation = exports.ListIndexesCursor = exports.ListIndexesOperation = exports.DropIndexesOperation = exports.DropIndexOperation = exports.EnsureIndexOperation = exports.CreateIndexOperation = exports.CreateIndexesOperation = exports.IndexesOperation = void 0; +const common_functions_1 = __nccwpck_require__(2296); +const operation_1 = __nccwpck_require__(1018); +const error_1 = __nccwpck_require__(9386); +const utils_1 = __nccwpck_require__(1371); +const command_1 = __nccwpck_require__(499); +const read_preference_1 = __nccwpck_require__(9802); +const abstract_cursor_1 = __nccwpck_require__(7349); +const execute_operation_1 = __nccwpck_require__(2548); +const LIST_INDEXES_WIRE_VERSION = 3; +const VALID_INDEX_OPTIONS = new Set([ + 'background', + 'unique', + 'name', + 'partialFilterExpression', + 'sparse', + 'hidden', + 'expireAfterSeconds', + 'storageEngine', + 'collation', + 'version', + // text indexes + 'weights', + 'default_language', + 'language_override', + 'textIndexVersion', + // 2d-sphere indexes + '2dsphereIndexVersion', + // 2d indexes + 'bits', + 'min', + 'max', + // geoHaystack Indexes + 'bucketSize', + // wildcard indexes + 'wildcardProjection' +]); +function makeIndexSpec(indexSpec, options) { + const indexParameters = (0, utils_1.parseIndexOptions)(indexSpec); + // Generate the index name + const name = typeof options.name === 'string' ? options.name : indexParameters.name; + // Set up the index + const finalIndexSpec = { name, key: indexParameters.fieldHash }; + // merge valid index options into the index spec + for (const optionName in options) { + if (VALID_INDEX_OPTIONS.has(optionName)) { + finalIndexSpec[optionName] = options[optionName]; } - - if (cap[4].split("?")[0].indexOf("@") !== -1) { - return callback( - new MongoParseError("Unescaped slash in userinfo section") - ); + } + return finalIndexSpec; +} +/** @internal */ +class IndexesOperation extends operation_1.AbstractOperation { + constructor(collection, options) { + super(options); + this.options = options; + this.collection = collection; + } + execute(server, session, callback) { + const coll = this.collection; + const options = this.options; + (0, common_functions_1.indexInformation)(coll.s.db, coll.collectionName, { full: true, ...options, readPreference: this.readPreference, session }, callback); + } +} +exports.IndexesOperation = IndexesOperation; +/** @internal */ +class CreateIndexesOperation extends command_1.CommandOperation { + constructor(parent, collectionName, indexes, options) { + super(parent, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collectionName = collectionName; + this.indexes = indexes; + } + execute(server, session, callback) { + const options = this.options; + const indexes = this.indexes; + const serverWireVersion = (0, utils_1.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 error_1.MongoCompatibilityError(`Server ${server.name}, which reports wire version ${serverWireVersion}, ` + + 'does not support collation')); + return; + } + if (indexes[i].name == null) { + const keys = []; + for (const name in indexes[i].key) { + keys.push(`${name}_${indexes[i].key[name]}`); + } + // Set the name + indexes[i].name = keys.join('_'); + } } - - const authorityParts = cap[3].split("@"); - if (authorityParts.length > 2) { - return callback( - new MongoParseError("Unescaped at-sign in authority section") - ); + const cmd = { createIndexes: this.collectionName, indexes }; + if (options.commitQuorum != null) { + if (serverWireVersion < 9) { + callback(new error_1.MongoCompatibilityError('Option `commitQuorum` for `createIndexes` not supported on servers < 4.4')); + return; + } + cmd.commitQuorum = options.commitQuorum; } - - if (authorityParts[0] == null || authorityParts[0] === "") { - return callback( - new MongoParseError("No username provided in authority section") - ); + // collation is set on each index, it should not be defined at the root + this.options.collation = undefined; + super.executeCommand(server, session, cmd, err => { + if (err) { + callback(err); + return; + } + const indexNames = indexes.map(index => index.name || ''); + callback(undefined, indexNames); + }); + } +} +exports.CreateIndexesOperation = CreateIndexesOperation; +/** @internal */ +class CreateIndexOperation extends CreateIndexesOperation { + constructor(parent, collectionName, indexSpec, options) { + // 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 + super(parent, collectionName, [makeIndexSpec(indexSpec, options)], options); + } + execute(server, session, callback) { + super.execute(server, session, (err, indexNames) => { + if (err || !indexNames) + return callback(err); + return callback(undefined, indexNames[0]); + }); + } +} +exports.CreateIndexOperation = CreateIndexOperation; +/** @internal */ +class EnsureIndexOperation extends CreateIndexOperation { + constructor(db, collectionName, indexSpec, options) { + super(db, collectionName, indexSpec, options); + this.readPreference = read_preference_1.ReadPreference.primary; + this.db = db; + this.collectionName = collectionName; + } + execute(server, session, callback) { + const indexName = this.indexes[0].name; + const cursor = this.db.collection(this.collectionName).listIndexes({ session }); + cursor.toArray((err, indexes) => { + /// ignore "NamespaceNotFound" errors + if (err && err.code !== error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + return callback(err); + } + if (indexes) { + indexes = Array.isArray(indexes) ? indexes : [indexes]; + if (indexes.some(index => index.name === indexName)) { + callback(undefined, indexName); + return; + } + } + super.execute(server, session, callback); + }); + } +} +exports.EnsureIndexOperation = EnsureIndexOperation; +/** @internal */ +class DropIndexOperation extends command_1.CommandOperation { + constructor(collection, indexName, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collection = collection; + this.indexName = indexName; + } + execute(server, session, callback) { + const cmd = { dropIndexes: this.collection.collectionName, index: this.indexName }; + super.executeCommand(server, session, cmd, callback); + } +} +exports.DropIndexOperation = DropIndexOperation; +/** @internal */ +class DropIndexesOperation extends DropIndexOperation { + constructor(collection, options) { + super(collection, '*', options); + } + execute(server, session, callback) { + super.execute(server, session, err => { + if (err) + return callback(err, false); + callback(undefined, true); + }); + } +} +exports.DropIndexesOperation = DropIndexesOperation; +/** @internal */ +class ListIndexesOperation extends command_1.CommandOperation { + constructor(collection, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collectionNamespace = collection.s.namespace; + } + execute(server, session, callback) { + const serverWireVersion = (0, utils_1.maxWireVersion)(server); + if (serverWireVersion < LIST_INDEXES_WIRE_VERSION) { + const systemIndexesNS = this.collectionNamespace.withCollection('system.indexes'); + const collectionNS = this.collectionNamespace.toString(); + server.query(systemIndexesNS, { query: { ns: collectionNS } }, { ...this.options, readPreference: this.readPreference }, callback); + return; } - - 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; + const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; + super.executeCommand(server, session, { listIndexes: this.collectionNamespace.collection, cursor }, callback); + } +} +exports.ListIndexesOperation = ListIndexesOperation; +/** @public */ +class ListIndexesCursor extends abstract_cursor_1.AbstractCursor { + constructor(collection, options) { + super((0, utils_1.getTopology)(collection), collection.s.namespace, options); + this.parent = collection; + this.options = options; + } + clone() { + return new ListIndexesCursor(this.parent, { + ...this.options, + ...this.cursorOptions + }); + } + /** @internal */ + _initialize(session, callback) { + const operation = new ListIndexesOperation(this.parent, { + ...this.cursorOptions, + ...this.options, + session + }); + (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this.parent), operation, (err, response) => { + if (err || response == null) + return callback(err); + // TODO: NODE-2882 + callback(undefined, { server: operation.server, session, response }); + }); + } +} +exports.ListIndexesCursor = ListIndexesCursor; +/** @internal */ +class IndexExistsOperation extends operation_1.AbstractOperation { + constructor(collection, indexes, options) { + super(options); + this.options = options; + this.collection = collection; + this.indexes = indexes; + } + execute(server, session, callback) { + const coll = this.collection; + const indexes = this.indexes; + (0, common_functions_1.indexInformation)(coll.s.db, coll.collectionName, { ...this.options, readPreference: this.readPreference, session }, (err, indexInformation) => { + // If we have an error return + if (err != null) + return callback(err); + // Let's check for the index names + if (!Array.isArray(indexes)) + return callback(undefined, indexInformation[indexes] != null); + // Check in list of indexes + for (let i = 0; i < indexes.length; i++) { + if (indexInformation[indexes[i]] == null) { + return callback(undefined, false); + } + } + // All keys found return true + return callback(undefined, true); + }); + } +} +exports.IndexExistsOperation = IndexExistsOperation; +/** @internal */ +class IndexInformationOperation extends operation_1.AbstractOperation { + constructor(db, name, options) { + super(options); + this.options = options !== null && options !== void 0 ? options : {}; + this.db = db; + this.name = name; + } + execute(server, session, callback) { + const db = this.db; + const name = this.name; + (0, common_functions_1.indexInformation)(db, name, { ...this.options, readPreference: this.readPreference, session }, callback); + } +} +exports.IndexInformationOperation = IndexInformationOperation; +(0, operation_1.defineAspects)(ListIndexesOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.CURSOR_CREATING +]); +(0, operation_1.defineAspects)(CreateIndexesOperation, [operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(CreateIndexOperation, [operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(EnsureIndexOperation, [operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(DropIndexOperation, [operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(DropIndexesOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=indexes.js.map + +/***/ }), + +/***/ 4179: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.InsertManyOperation = exports.InsertOneOperation = exports.InsertOperation = void 0; +const error_1 = __nccwpck_require__(9386); +const operation_1 = __nccwpck_require__(1018); +const command_1 = __nccwpck_require__(499); +const common_functions_1 = __nccwpck_require__(2296); +const write_concern_1 = __nccwpck_require__(2481); +const bulk_write_1 = __nccwpck_require__(6976); +/** @internal */ +class InsertOperation extends command_1.CommandOperation { + constructor(ns, documents, options) { + var _a; + super(undefined, options); + this.options = { ...options, checkKeys: (_a = options.checkKeys) !== null && _a !== void 0 ? _a : false }; + this.ns = ns; + this.documents = documents; + } + execute(server, session, callback) { + var _a; + const options = (_a = this.options) !== null && _a !== void 0 ? _a : {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command = { + insert: this.ns.collection, + documents: this.documents, + ordered + }; + if (typeof options.bypassDocumentValidation === 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + if (options.comment != null) { + command.comment = options.comment; + } + super.executeCommand(server, session, command, callback); + } +} +exports.InsertOperation = InsertOperation; +class InsertOneOperation extends InsertOperation { + constructor(collection, doc, options) { + super(collection.s.namespace, (0, common_functions_1.prepareDocs)(collection, [doc], options), options); + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || res == null) + return callback(err); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) { + // This should be a WriteError but we can't change it now because of error hierarchy + return callback(new error_1.MongoServerError(res.writeErrors[0])); + } + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + insertedId: this.documents[0]._id + }); + }); + } +} +exports.InsertOneOperation = InsertOneOperation; +/** @internal */ +class InsertManyOperation extends operation_1.AbstractOperation { + constructor(collection, docs, options) { + super(options); + if (!Array.isArray(docs)) { + throw new error_1.MongoInvalidArgumentError('Argument "docs" must be an array of documents'); } - - 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; + this.options = options; + this.collection = collection; + this.docs = docs; + } + execute(server, session, callback) { + const coll = this.collection; + const options = { ...this.options, ...this.bsonOptions, readPreference: this.readPreference }; + const writeConcern = write_concern_1.WriteConcern.fromOptions(options); + const bulkWriteOperation = new bulk_write_1.BulkWriteOperation(coll, (0, common_functions_1.prepareDocs)(coll, this.docs, options).map(document => ({ insertOne: { document } })), options); + bulkWriteOperation.execute(server, session, (err, res) => { + var _a; + if (err || res == null) + return callback(err); + callback(undefined, { + acknowledged: (_a = (writeConcern === null || writeConcern === void 0 ? void 0 : writeConcern.w) !== 0) !== null && _a !== void 0 ? _a : true, + insertedCount: res.insertedCount, + insertedIds: res.insertedIds + }); + }); + } +} +exports.InsertManyOperation = InsertManyOperation; +(0, operation_1.defineAspects)(InsertOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(InsertOneOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION]); +(0, operation_1.defineAspects)(InsertManyOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=insert.js.map + +/***/ }), + +/***/ 4956: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.IsCappedOperation = void 0; +const operation_1 = __nccwpck_require__(1018); +const error_1 = __nccwpck_require__(9386); +/** @internal */ +class IsCappedOperation extends operation_1.AbstractOperation { + constructor(collection, options) { + super(options); + this.options = options; + this.collection = collection; + } + execute(server, session, callback) { + const coll = this.collection; + coll.s.db + .listCollections({ name: coll.collectionName }, { ...this.options, nameOnly: false, readPreference: this.readPreference, session }) + .toArray((err, collections) => { + if (err || !collections) + return callback(err); + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new error_1.MongoAPIError(`collection ${coll.namespace} not found`)); } - - if (Number.isNaN(parsedHost.port)) { - hostParsingError = new MongoParseError( - "Invalid port (non-numeric string)" - ); - return; + const collOptions = collections[0].options; + callback(undefined, !!(collOptions && collOptions.capped)); + }); + } +} +exports.IsCappedOperation = IsCappedOperation; +//# sourceMappingURL=is_capped.js.map + +/***/ }), + +/***/ 840: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ListCollectionsCursor = exports.ListCollectionsOperation = void 0; +const command_1 = __nccwpck_require__(499); +const operation_1 = __nccwpck_require__(1018); +const utils_1 = __nccwpck_require__(1371); +const CONSTANTS = __nccwpck_require__(147); +const abstract_cursor_1 = __nccwpck_require__(7349); +const execute_operation_1 = __nccwpck_require__(2548); +const LIST_COLLECTIONS_WIRE_VERSION = 3; +/** @internal */ +class ListCollectionsOperation extends command_1.CommandOperation { + constructor(db, filter, options) { + super(db, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.db = db; + this.filter = filter; + this.nameOnly = !!this.options.nameOnly; + this.authorizedCollections = !!this.options.authorizedCollections; + if (typeof this.options.batchSize === 'number') { + this.batchSize = this.options.batchSize; + } + } + execute(server, session, callback) { + if ((0, utils_1.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(); } - - 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; + // No filter, filter by current database + if (filter == null) { + filter = { name: `/${databaseName}/` }; } - - if (result.port > 65535) { - hostParsingError = new MongoParseError( - "Invalid port (larger than 65535) with hostname" - ); - return; + // Rewrite the filter to use $and to filter out indexes + if (filter.name) { + filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] }; } - - if (result.port < 0) { - hostParsingError = new MongoParseError( - "Invalid port (negative number)" - ); - return; + else { + filter = { name: /^((?!\$).)*$/ }; } - - 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 documentTransform = (doc) => { + const matching = `${databaseName}.`; + 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; + }; + server.query(new utils_1.MongoDBNamespace(databaseName, CONSTANTS.SYSTEM_NAMESPACE_COLLECTION), { query: filter }, { batchSize: this.batchSize || 1000, readPreference: this.readPreference }, (err, result) => { + if (result && result.documents && Array.isArray(result.documents)) { + result.documents = result.documents.map(documentTransform); + } + callback(err, result); + }); + return; } - - const result = { - hosts: hosts, - auth: auth.db || auth.username ? auth : null, - options: Object.keys(parsedOptions).length ? parsedOptions : null, + return super.executeCommand(server, session, this.generateCommand(), callback); + } + /* This is here for the purpose of unit testing the final command that gets sent. */ + generateCommand() { + return { + listCollections: 1, + filter: this.filter, + cursor: this.batchSize ? { batchSize: this.batchSize } : {}, + nameOnly: this.nameOnly, + authorizedCollections: this.authorizedCollections }; - - if (result.auth && result.auth.db) { - result.defaultDatabase = result.auth.db; - } else { - result.defaultDatabase = "test"; + } +} +exports.ListCollectionsOperation = ListCollectionsOperation; +/** @public */ +class ListCollectionsCursor extends abstract_cursor_1.AbstractCursor { + constructor(db, filter, options) { + super((0, utils_1.getTopology)(db), db.s.namespace, options); + this.parent = db; + this.filter = filter; + this.options = options; + } + clone() { + return new ListCollectionsCursor(this.parent, this.filter, { + ...this.options, + ...this.cursorOptions + }); + } + /** @internal */ + _initialize(session, callback) { + const operation = new ListCollectionsOperation(this.parent, this.filter, { + ...this.cursorOptions, + ...this.options, + session + }); + (0, execute_operation_1.executeOperation)((0, utils_1.getTopology)(this.parent), operation, (err, response) => { + if (err || response == null) + return callback(err); + // TODO: NODE-2882 + callback(undefined, { server: operation.server, session, response }); + }); + } +} +exports.ListCollectionsCursor = ListCollectionsCursor; +(0, operation_1.defineAspects)(ListCollectionsOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.CURSOR_CREATING +]); +//# sourceMappingURL=list_collections.js.map + +/***/ }), + +/***/ 9929: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ListDatabasesOperation = void 0; +const command_1 = __nccwpck_require__(499); +const operation_1 = __nccwpck_require__(1018); +const utils_1 = __nccwpck_require__(1371); +/** @internal */ +class ListDatabasesOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.ns = new utils_1.MongoDBNamespace('admin', '$cmd'); + } + execute(server, session, callback) { + const cmd = { listDatabases: 1 }; + if (this.options.nameOnly) { + cmd.nameOnly = Number(cmd.nameOnly); } - - // support modern `tls` variants to SSL options - result.options = translateTLSOptions(result.options); - - try { - applyAuthExpectations(result); - } catch (authError) { - return callback(authError); + if (this.options.filter) { + cmd.filter = this.options.filter; } - - callback(null, result); - } - - module.exports = parseConnectionString; - - /***/ - }, - - /***/ 1178: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const os = __nccwpck_require__(2087); - const crypto = __nccwpck_require__(6417); - const requireOptional = __nccwpck_require__(3182)(require); - - /** - * 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 { - // Ensure you always wrap an optional require in the try block NODE-3199 - 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; + if (typeof this.options.authorizedDatabases === 'boolean') { + cmd.authorizedDatabases = this.options.authorizedDatabases; } - - 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 = requireOptional("mongodb-extjson"); - if (!EJSON) { - EJSON = { - parse: noEJSONError, - deserialize: noEJSONError, - serialize: noEJSONError, - stringify: noEJSONError, - setBSONModule: noEJSONError, - BSON: noEJSONError, - }; + super.executeCommand(server, session, cmd, callback); + } +} +exports.ListDatabasesOperation = ListDatabasesOperation; +(0, operation_1.defineAspects)(ListDatabasesOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE]); +//# sourceMappingURL=list_databases.js.map + +/***/ }), + +/***/ 2779: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MapReduceOperation = void 0; +const bson_1 = __nccwpck_require__(5578); +const utils_1 = __nccwpck_require__(1371); +const read_preference_1 = __nccwpck_require__(9802); +const command_1 = __nccwpck_require__(499); +const error_1 = __nccwpck_require__(9386); +const operation_1 = __nccwpck_require__(1018); +const db_1 = __nccwpck_require__(6662); +const exclusionList = [ + 'explain', + 'readPreference', + 'readConcern', + 'session', + 'bypassDocumentValidation', + 'writeConcern', + 'raw', + 'fieldsAsRaw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bsonRegExp', + 'serializeFunctions', + 'ignoreUndefined', + 'scope' // this option is reformatted thus exclude the original +]; +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * @internal + */ +class MapReduceOperation extends command_1.CommandOperation { + /** + * Constructs a MapReduce operation. + * + * @param collection - Collection instance. + * @param map - The mapping function. + * @param reduce - The reduce function. + * @param options - Optional settings. See Collection.prototype.mapReduce for a list of options. + */ + constructor(collection, map, reduce, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collection = collection; + this.map = map; + this.reduce = reduce; + } + execute(server, session, 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 + }; + if (options.scope) { + mapCommandHash.scope = processScope(options.scope); } - - 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; + // Add any other options passed in + for (const n in options) { + // Only include if not in exclusion list + if (exclusionList.indexOf(n) === -1) { + mapCommandHash[n] = options[n]; } - } - - 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); + options = Object.assign({}, options); + // If we have a read preference and inline is not set as output fail hard + if (this.readPreference.mode === read_preference_1.ReadPreferenceMode.primary && + options.out && + options.out.inline !== 1 && + options.out !== 'inline') { + // Force readPreference to primary + options.readPreference = read_preference_1.ReadPreference.primary; + // Decorate command with writeConcern if supported + (0, utils_1.applyWriteConcern)(mapCommandHash, { db: coll.s.db, collection: coll }, options); } - - if (awaiting === 0) { - callback(); - return; + else { + (0, utils_1.decorateWithReadConcern)(mapCommandHash, coll, options); } - - function eachCallback(err) { - awaiting--; - if (err) { - callback(err); - return; - } - - if (idx === arr.length && awaiting <= 0) { - callback(); - } + // Is bypassDocumentValidation specified + if (options.bypassDocumentValidation === true) { + mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; } - } - - function eachAsyncSeries(arr, eachFn, callback) { - arr = arr || []; - - let idx = 0; - let awaiting = arr.length; - if (awaiting === 0) { - callback(); - return; + // Have we specified collation + try { + (0, utils_1.decorateWithCollation)(mapCommandHash, coll, options); } - - function eachCallback(err) { - idx++; - awaiting--; - if (err) { - callback(err); - return; - } - - if (idx === arr.length && awaiting <= 0) { - callback(); + catch (err) { + return callback(err); + } + if (this.explain && (0, utils_1.maxWireVersion)(server) < 9) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support explain on mapReduce`)); 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; + // Execute command + super.executeCommand(server, session, mapCommandHash, (err, result) => { + if (err) + return callback(err); + // Check if we have an error + if (1 !== result.ok || result.err || result.errmsg) { + return callback(new error_1.MongoServerError(result)); + } + // If an explain option was executed, don't process the server results + if (this.explain) + return callback(undefined, 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 callback(undefined, result.results); + } + return callback(undefined, { 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 + collection = new db_1.Db(coll.s.db.s.client, doc.db, 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 callback(err, collection); + } + // Return stats as third set of values + callback(err, { collection, stats }); + }); + } +} +exports.MapReduceOperation = MapReduceOperation; +/** Functions that are passed as scope args must be converted to Code instances. */ +function processScope(scope) { + if (!(0, utils_1.isObject)(scope) || scope._bsontype === 'ObjectID') { + return scope; + } + const newScope = {}; + for (const key of Object.keys(scope)) { + if ('function' === typeof scope[key]) { + newScope[key] = new bson_1.Code(String(scope[key])); } - - 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; + else if (scope[key]._bsontype === 'Code') { + newScope[key] = scope[key]; } - - if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) { - return false; + else { + newScope[key] = processScope(scope[key]); } - - if (lhs.constructor.name !== rhs.constructor.name) { - return false; + } + return newScope; +} +(0, operation_1.defineAspects)(MapReduceOperation, [operation_1.Aspect.EXPLAINABLE]); +//# sourceMappingURL=map_reduce.js.map + +/***/ }), + +/***/ 1018: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defineAspects = exports.AbstractOperation = exports.Aspect = void 0; +const read_preference_1 = __nccwpck_require__(9802); +const bson_1 = __nccwpck_require__(5578); +exports.Aspect = { + READ_OPERATION: Symbol('READ_OPERATION'), + WRITE_OPERATION: Symbol('WRITE_OPERATION'), + RETRYABLE: Symbol('RETRYABLE'), + EXPLAINABLE: Symbol('EXPLAINABLE'), + SKIP_COLLATION: Symbol('SKIP_COLLATION'), + CURSOR_CREATING: Symbol('CURSOR_CREATING'), + CURSOR_ITERATING: Symbol('CURSOR_ITERATING') +}; +/** @internal */ +const kSession = Symbol('session'); +/** + * 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. + * @internal + */ +class AbstractOperation { + constructor(options = {}) { + var _a; + this.readPreference = this.hasAspect(exports.Aspect.WRITE_OPERATION) + ? read_preference_1.ReadPreference.primary + : (_a = read_preference_1.ReadPreference.fromOptions(options)) !== null && _a !== void 0 ? _a : read_preference_1.ReadPreference.primary; + // Pull the BSON serialize options from the already-resolved options + this.bsonOptions = (0, bson_1.resolveBSONOptions)(options); + if (options.session) { + this[kSession] = options.session; } - - if (lhs.message !== rhs.message) { - return false; + this.options = options; + this.bypassPinningCheck = !!options.bypassPinningCheck; + this.trySecondaryWrite = false; + } + hasAspect(aspect) { + const ctor = this.constructor; + if (ctor.aspects == null) { + return false; } - + return ctor.aspects.has(aspect); + } + get session() { + return this[kSession]; + } + get canRetryRead() { 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: __nccwpck_require__(306).version, - }, - 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}`; - } + } + get canRetryWrite() { + return true; + } +} +exports.AbstractOperation = AbstractOperation; +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; +} +exports.defineAspects = defineAspects; +//# sourceMappingURL=operation.js.map + +/***/ }), + +/***/ 43: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.OptionsOperation = void 0; +const operation_1 = __nccwpck_require__(1018); +const error_1 = __nccwpck_require__(9386); +/** @internal */ +class OptionsOperation extends operation_1.AbstractOperation { + constructor(collection, options) { + super(options); + this.options = options; + this.collection = collection; + } + execute(server, session, callback) { + const coll = this.collection; + coll.s.db + .listCollections({ name: coll.collectionName }, { ...this.options, nameOnly: false, readPreference: this.readPreference, session }) + .toArray((err, collections) => { + if (err || !collections) + return callback(err); + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new error_1.MongoAPIError(`collection ${coll.namespace} not found`)); + } + callback(err, collections[0].options); + }); + } +} +exports.OptionsOperation = OptionsOperation; +//# sourceMappingURL=options_operation.js.map - 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, - }; - } +/***/ 3969: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return metadata; - } - - const noop = () => {}; - - module.exports = { - uuidV4, - relayEvents, - collationNotSupported, - retrieveEJSON, - retrieveKerberos, - maxWireVersion, - isPromiseLike, - eachAsync, - eachAsyncSeries, - isUnifiedTopology, - arrayStrictEqual, - tagsStrictEqual, - errorStrictEqual, - makeStateMachine, - makeClientMetadata, - noop, - }; +"use strict"; - /***/ - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ProfilingLevelOperation = void 0; +const command_1 = __nccwpck_require__(499); +const error_1 = __nccwpck_require__(9386); +/** @internal */ +class ProfilingLevelOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options; + } + execute(server, session, callback) { + super.executeCommand(server, session, { profile: -1 }, (err, doc) => { + if (err == null && doc.ok === 1) { + const was = doc.was; + if (was === 0) + return callback(undefined, 'off'); + if (was === 1) + return callback(undefined, 'slow_only'); + if (was === 2) + return callback(undefined, 'all'); + // TODO(NODE-3483) + return callback(new error_1.MongoRuntimeError(`Illegal profiling level value ${was}`)); + } + else { + // TODO(NODE-3483): Consider MongoUnexpectedServerResponseError + err != null ? callback(err) : callback(new error_1.MongoRuntimeError('Error with profile command')); + } + }); + } +} +exports.ProfilingLevelOperation = ProfilingLevelOperation; +//# sourceMappingURL=profiling_level.js.map - /***/ 7276: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Query = __nccwpck_require__(9814).Query; - const Msg = __nccwpck_require__(8988).Msg; - const MongoError = __nccwpck_require__(3111).MongoError; - const getReadPreference = __nccwpck_require__(7272).getReadPreference; - const isSharded = __nccwpck_require__(7272).isSharded; - const databaseNamespace = __nccwpck_require__(7272).databaseNamespace; - const isTransactionCommand = - __nccwpck_require__(1707).isTransactionCommand; - const applySession = __nccwpck_require__(5474).applySession; - const MongoNetworkError = __nccwpck_require__(3111).MongoNetworkError; - const maxWireVersion = __nccwpck_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` - ) - ); - } +/***/ 1969: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!isClientEncryptionEnabled(server)) { - _command(server, ns, cmd, options, callback); - return; - } +"use strict"; - const wireVersion = maxWireVersion(server); - if (typeof wireVersion !== "number" || wireVersion < 8) { - callback( - new MongoError( - "Auto-encryption requires a minimum MongoDB version of 4.2" - ) - ); - return; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RemoveUserOperation = void 0; +const operation_1 = __nccwpck_require__(1018); +const command_1 = __nccwpck_require__(499); +/** @internal */ +class RemoveUserOperation extends command_1.CommandOperation { + constructor(db, username, options) { + super(db, options); + this.options = options; + this.username = username; + } + execute(server, session, callback) { + super.executeCommand(server, session, { dropUser: this.username }, err => { + callback(err, err ? false : true); + }); + } +} +exports.RemoveUserOperation = RemoveUserOperation; +(0, operation_1.defineAspects)(RemoveUserOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=remove_user.js.map + +/***/ }), + +/***/ 2808: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RenameOperation = void 0; +const utils_1 = __nccwpck_require__(1371); +const run_command_1 = __nccwpck_require__(1363); +const operation_1 = __nccwpck_require__(1018); +const collection_1 = __nccwpck_require__(5193); +const error_1 = __nccwpck_require__(9386); +/** @internal */ +class RenameOperation extends run_command_1.RunAdminCommandOperation { + constructor(collection, newName, options) { + // Check the collection name + (0, utils_1.checkCollectionName)(newName); + // Build the command + const renameCollection = collection.namespace; + const toCollection = collection.s.namespace.withCollection(newName).toString(); + const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; + const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; + super(collection, cmd, options); + this.options = options; + this.collection = collection; + this.newName = newName; + } + execute(server, session, callback) { + const coll = this.collection; + super.execute(server, session, (err, doc) => { + if (err) + return callback(err); + // We have an error + if (doc.errmsg) { + return callback(new error_1.MongoServerError(doc)); + } + let newColl; + try { + newColl = new collection_1.Collection(coll.s.db, this.newName, coll.s.options); + } + catch (err) { + return callback(err); + } + return callback(undefined, newColl); + }); + } +} +exports.RenameOperation = RenameOperation; +(0, operation_1.defineAspects)(RenameOperation, [operation_1.Aspect.WRITE_OPERATION]); +//# sourceMappingURL=rename.js.map + +/***/ }), + +/***/ 1363: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RunAdminCommandOperation = exports.RunCommandOperation = void 0; +const command_1 = __nccwpck_require__(499); +const utils_1 = __nccwpck_require__(1371); +/** @internal */ +class RunCommandOperation extends command_1.CommandOperation { + constructor(parent, command, options) { + super(parent, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.command = command; + } + execute(server, session, callback) { + const command = this.command; + this.executeCommand(server, session, command, callback); + } +} +exports.RunCommandOperation = RunCommandOperation; +class RunAdminCommandOperation extends RunCommandOperation { + constructor(parent, command, options) { + super(parent, command, options); + this.ns = new utils_1.MongoDBNamespace('admin'); + } +} +exports.RunAdminCommandOperation = RunAdminCommandOperation; +//# sourceMappingURL=run_command.js.map + +/***/ }), + +/***/ 6301: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SetProfilingLevelOperation = exports.ProfilingLevel = void 0; +const command_1 = __nccwpck_require__(499); +const utils_1 = __nccwpck_require__(1371); +const error_1 = __nccwpck_require__(9386); +const levelValues = new Set(['off', 'slow_only', 'all']); +/** @public */ +exports.ProfilingLevel = Object.freeze({ + off: 'off', + slowOnly: 'slow_only', + all: 'all' +}); +/** @internal */ +class SetProfilingLevelOperation extends command_1.CommandOperation { + constructor(db, level, options) { + super(db, options); + this.options = options; + switch (level) { + case exports.ProfilingLevel.off: + this.profile = 0; + break; + case exports.ProfilingLevel.slowOnly: + this.profile = 1; + break; + case exports.ProfilingLevel.all: + this.profile = 2; + break; + default: + this.profile = 0; + break; } + this.level = level; + } + execute(server, session, callback) { + const level = this.level; + if (!levelValues.has(level)) { + return callback(new error_1.MongoInvalidArgumentError(`Profiling level must be one of "${(0, utils_1.enumToString)(exports.ProfilingLevel)}"`)); + } + // TODO(NODE-3483): Determine error to put here + super.executeCommand(server, session, { profile: this.profile }, (err, doc) => { + if (err == null && doc.ok === 1) + return callback(undefined, level); + return err != null + ? callback(err) + : callback(new error_1.MongoRuntimeError('Error with profile command')); + }); + } +} +exports.SetProfilingLevelOperation = SetProfilingLevelOperation; +//# sourceMappingURL=set_profiling_level.js.map - _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; +/***/ }), - const serverClusterTime = server.clusterTime; - let clusterTime = serverClusterTime; - let finalCmd = Object.assign({}, cmd); - if (hasSessionSupport(server) && session) { - const sessionClusterTime = session.clusterTime; - if ( - serverClusterTime && - serverClusterTime.clusterTime && - sessionClusterTime && - sessionClusterTime.clusterTime && - sessionClusterTime.clusterTime.greaterThan( - serverClusterTime.clusterTime - ) - ) { - clusterTime = sessionClusterTime; - } +/***/ 968: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const err = applySession(session, finalCmd, options); - if (err) { - return callback(err); - } - } +"use strict"; - if (clusterTime) { - // if we have a known cluster time, gossip it - finalCmd.$clusterTime = clusterTime; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DbStatsOperation = exports.CollStatsOperation = void 0; +const operation_1 = __nccwpck_require__(1018); +const command_1 = __nccwpck_require__(499); +/** + * Get all the collection statistics. + * @internal + */ +class CollStatsOperation extends command_1.CommandOperation { + /** + * Construct a Stats operation. + * + * @param collection - Collection instance + * @param options - Optional settings. See Collection.prototype.stats for a list of options. + */ + constructor(collection, options) { + super(collection, options); + this.options = options !== null && options !== void 0 ? options : {}; + this.collectionName = collection.collectionName; + } + execute(server, session, callback) { + const command = { collStats: this.collectionName }; + if (this.options.scale != null) { + command.scale = this.options.scale; } - - if ( - isSharded(server) && - !shouldUseOpMsg && - readPreference && - readPreference.mode !== "primary" - ) { - finalCmd = { - $query: finalCmd, - $readPreference: readPreference.toJSON(), - }; + super.executeCommand(server, session, command, callback); + } +} +exports.CollStatsOperation = CollStatsOperation; +/** @internal */ +class DbStatsOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.options = options; + } + execute(server, session, callback) { + const command = { dbStats: true }; + if (this.options.scale != null) { + command.scale = this.options.scale; } - - 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); + super.executeCommand(server, session, command, callback); + } +} +exports.DbStatsOperation = DbStatsOperation; +(0, operation_1.defineAspects)(CollStatsOperation, [operation_1.Aspect.READ_OPERATION]); +(0, operation_1.defineAspects)(DbStatsOperation, [operation_1.Aspect.READ_OPERATION]); +//# sourceMappingURL=stats.js.map + +/***/ }), + +/***/ 1134: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.makeUpdateStatement = exports.ReplaceOneOperation = exports.UpdateManyOperation = exports.UpdateOneOperation = exports.UpdateOperation = void 0; +const operation_1 = __nccwpck_require__(1018); +const utils_1 = __nccwpck_require__(1371); +const command_1 = __nccwpck_require__(499); +const error_1 = __nccwpck_require__(9386); +/** @internal */ +class UpdateOperation extends command_1.CommandOperation { + constructor(ns, statements, options) { + super(undefined, options); + this.options = options; + this.ns = ns; + this.statements = statements; + } + get canRetryWrite() { + if (super.canRetryWrite === false) { + return false; } - } - - function hasSessionSupport(topology) { - if (topology == null) return false; - if (topology.description) { - return topology.description.maxWireVersion >= 6; + return this.statements.every(op => op.multi == null || op.multi === false); + } + execute(server, session, callback) { + var _a; + const options = (_a = this.options) !== null && _a !== void 0 ? _a : {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const command = { + update: this.ns.collection, + updates: this.statements, + ordered + }; + if (typeof options.bypassDocumentValidation === 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; } - - 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; + if (options.let) { + command.let = options.let; } - - 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); + const statementWithCollation = this.statements.find(statement => !!statement.collation); + if ((0, utils_1.collationNotSupported)(server, options) || + (statementWithCollation && (0, utils_1.collationNotSupported)(server, statementWithCollation))) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support collation`)); return; - } - - autoEncrypter.decrypt(response.result, options, (err, decrypted) => { - if (err) { - callback(err, null); - return; + } + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite || (0, utils_1.maxWireVersion)(server) < 5) { + if (this.statements.find((o) => o.hint)) { + callback(new error_1.MongoCompatibilityError(`Servers < 3.4 do not support hint on update`)); + return; } - - response.result = decrypted; - response.message.documents = [decrypted]; - callback(null, response); - }); } - - autoEncrypter.encrypt(ns, cmd, options, (err, encrypted) => { - if (err) { - callback(err, null); + if (this.explain && (0, utils_1.maxWireVersion)(server) < 3) { + callback(new error_1.MongoCompatibilityError(`Server ${server.name} does not support explain on update`)); return; - } - - _command(server, ns, encrypted, options, commandResponseHandler); + } + if (this.statements.some(statement => !!statement.arrayFilters) && (0, utils_1.maxWireVersion)(server) < 6) { + callback(new error_1.MongoCompatibilityError('Option "arrayFilters" is only supported on MongoDB 3.6+')); + return; + } + super.executeCommand(server, session, command, callback); + } +} +exports.UpdateOperation = UpdateOperation; +/** @internal */ +class UpdateOneOperation extends UpdateOperation { + constructor(collection, filter, update, options) { + super(collection.s.namespace, [makeUpdateStatement(filter, update, { ...options, multi: false })], options); + if (!(0, utils_1.hasAtomicOperators)(update)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || !res) + return callback(err); + if (this.explain != null) + return callback(undefined, res); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) + return callback(new error_1.MongoServerError(res.writeErrors[0])); + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + modifiedCount: res.nModified != null ? res.nModified : res.n, + upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }); }); - } - - module.exports = command; - - /***/ - }, - - /***/ 7793: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Snappy = __nccwpck_require__(7746).retrieveSnappy(); - const zlib = __nccwpck_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; + } +} +exports.UpdateOneOperation = UpdateOneOperation; +/** @internal */ +class UpdateManyOperation extends UpdateOperation { + constructor(collection, filter, update, options) { + super(collection.s.namespace, [makeUpdateStatement(filter, update, { ...options, multi: true })], options); + if (!(0, utils_1.hasAtomicOperators)(update)) { + throw new error_1.MongoInvalidArgumentError('Update document requires atomic operators'); + } + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || !res) + return callback(err); + if (this.explain != null) + return callback(undefined, res); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) + return callback(new error_1.MongoServerError(res.writeErrors[0])); + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + modifiedCount: res.nModified != null ? res.nModified : res.n, + upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }); + }); + } +} +exports.UpdateManyOperation = UpdateManyOperation; +/** @internal */ +class ReplaceOneOperation extends UpdateOperation { + constructor(collection, filter, replacement, options) { + super(collection.s.namespace, [makeUpdateStatement(filter, replacement, { ...options, multi: false })], options); + if ((0, utils_1.hasAtomicOperators)(replacement)) { + throw new error_1.MongoInvalidArgumentError('Replacement document must not contain atomic operators'); + } + } + execute(server, session, callback) { + super.execute(server, session, (err, res) => { + var _a, _b; + if (err || !res) + return callback(err); + if (this.explain != null) + return callback(undefined, res); + if (res.code) + return callback(new error_1.MongoServerError(res)); + if (res.writeErrors) + return callback(new error_1.MongoServerError(res.writeErrors[0])); + callback(undefined, { + acknowledged: (_b = ((_a = this.writeConcern) === null || _a === void 0 ? void 0 : _a.w) !== 0) !== null && _b !== void 0 ? _b : true, + modifiedCount: res.nModified != null ? res.nModified : res.n, + upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }); + }); + } +} +exports.ReplaceOneOperation = ReplaceOneOperation; +function makeUpdateStatement(filter, update, options) { + if (filter == null || typeof filter !== 'object') { + throw new error_1.MongoInvalidArgumentError('Selector must be a valid JavaScript object'); + } + if (update == null || typeof update !== 'object') { + throw new error_1.MongoInvalidArgumentError('Document must be a valid JavaScript object'); + } + const op = { q: filter, u: update }; + if (typeof options.upsert === 'boolean') { + op.upsert = options.upsert; + } + if (options.multi) { + op.multi = options.multi; + } + if (options.hint) { + op.hint = options.hint; + } + if (options.arrayFilters) { + op.arrayFilters = options.arrayFilters; + } + if (options.collation) { + op.collation = options.collation; + } + return op; +} +exports.makeUpdateStatement = makeUpdateStatement; +(0, operation_1.defineAspects)(UpdateOperation, [operation_1.Aspect.RETRYABLE, operation_1.Aspect.WRITE_OPERATION, operation_1.Aspect.SKIP_COLLATION]); +(0, operation_1.defineAspects)(UpdateOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +(0, operation_1.defineAspects)(UpdateManyOperation, [ + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION +]); +(0, operation_1.defineAspects)(ReplaceOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.SKIP_COLLATION +]); +//# sourceMappingURL=update.js.map + +/***/ }), + +/***/ 9263: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ValidateCollectionOperation = void 0; +const command_1 = __nccwpck_require__(499); +const error_1 = __nccwpck_require__(9386); +/** @internal */ +class ValidateCollectionOperation extends command_1.CommandOperation { + constructor(admin, collectionName, options) { + // Decorate command with extra options + const command = { validate: collectionName }; + const keys = Object.keys(options); + for (let i = 0; i < keys.length; i++) { + if (Object.prototype.hasOwnProperty.call(options, keys[i]) && keys[i] !== 'session') { + command[keys[i]] = options[keys[i]]; } - 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 + - ")" - ); + super(admin.s.db, options); + this.options = options; + this.command = command; + this.collectionName = collectionName; + } + execute(server, session, callback) { + const collectionName = this.collectionName; + super.executeCommand(server, session, this.command, (err, doc) => { + if (err != null) + return callback(err); + // TODO(NODE-3483): Replace these with MongoUnexpectedServerResponseError + if (doc.ok === 0) + return callback(new error_1.MongoRuntimeError('Error with validate command')); + if (doc.result != null && typeof doc.result !== 'string') + return callback(new error_1.MongoRuntimeError('Error with validation data')); + if (doc.result != null && doc.result.match(/exception|corrupt/) != null) + return callback(new error_1.MongoRuntimeError(`Invalid collection ${collectionName}`)); + if (doc.valid != null && !doc.valid) + return callback(new error_1.MongoRuntimeError(`Invalid collection ${collectionName}`)); + return callback(undefined, doc); + }); + } +} +exports.ValidateCollectionOperation = ValidateCollectionOperation; +//# sourceMappingURL=validate_collection.js.map + +/***/ }), + +/***/ 2725: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PromiseProvider = void 0; +const error_1 = __nccwpck_require__(9386); +/** @internal */ +const kPromise = Symbol('promise'); +const store = { + [kPromise]: undefined +}; +/** + * Global promise store allowing user-provided promises + * @public + */ +class PromiseProvider { + /** Validates the passed in promise library */ + static validate(lib) { + if (typeof lib !== 'function') + throw new error_1.MongoInvalidArgumentError(`Promise must be a function, got ${lib}`); + return !!lib; + } + /** Sets the promise library */ + static set(lib) { + if (!PromiseProvider.validate(lib)) { + // validate + return; } - switch (compressorID) { - case compressorIDs.snappy: - Snappy.uncompress(compressedData, callback); - break; - case compressorIDs.zlib: - zlib.inflate(compressedData, callback); - break; - default: - callback(null, compressedData); + store[kPromise] = lib; + } + /** Get the stored promise library, or resolves passed in */ + static get() { + return store[kPromise]; + } +} +exports.PromiseProvider = PromiseProvider; +PromiseProvider.set(global.Promise); +//# sourceMappingURL=promise_provider.js.map + +/***/ }), + +/***/ 7289: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ReadConcern = exports.ReadConcernLevel = void 0; +/** @public */ +exports.ReadConcernLevel = Object.freeze({ + local: 'local', + majority: 'majority', + linearizable: 'linearizable', + available: 'available', + snapshot: 'snapshot' +}); +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @public + * + * @see https://docs.mongodb.com/manual/reference/read-concern/index.html + */ +class ReadConcern { + /** Constructs a ReadConcern from the read concern level.*/ + constructor(level) { + var _a; + /** + * A spec test exists that allows level to be any string. + * "invalid readConcern with out stage" + * @see ./test/spec/crud/v2/aggregate-out-readConcern.json + * @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#unknown-levels-and-additional-options-for-string-based-readconcerns + */ + this.level = (_a = exports.ReadConcernLevel[level]) !== null && _a !== void 0 ? _a : level; + } + /** + * Construct a ReadConcern given an options object. + * + * @param options - The options object from which to extract the write concern. + */ + static fromOptions(options) { + if (options == null) { + return; } - } - - module.exports = { - compressorIDs, - uncompressibleCommands, - compress, - decompress, - }; - - /***/ - }, - - /***/ 7161: /***/ (module) => { - "use strict"; - - const MIN_SUPPORTED_SERVER_VERSION = "2.6"; - const MAX_SUPPORTED_SERVER_VERSION = "5.0"; - const MIN_SUPPORTED_WIRE_VERSION = 2; - const MAX_SUPPORTED_WIRE_VERSION = 13; - - module.exports = { - MIN_SUPPORTED_SERVER_VERSION, - MAX_SUPPORTED_SERVER_VERSION, - MIN_SUPPORTED_WIRE_VERSION, - MAX_SUPPORTED_WIRE_VERSION, - }; - - /***/ - }, - - /***/ 1971: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const GetMore = __nccwpck_require__(9814).GetMore; - const retrieveBSON = __nccwpck_require__(7746).retrieveBSON; - const MongoError = __nccwpck_require__(3111).MongoError; - const MongoNetworkError = __nccwpck_require__(3111).MongoNetworkError; - const BSON = retrieveBSON(); - const Long = BSON.Long; - const collectionNamespace = __nccwpck_require__(7272).collectionNamespace; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const applyCommonQueryOptions = - __nccwpck_require__(7272).applyCommonQueryOptions; - const command = __nccwpck_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); + if (options.readConcern) { + const { readConcern } = options; + if (readConcern instanceof ReadConcern) { + return readConcern; + } + else if (typeof readConcern === 'string') { + return new ReadConcern(readConcern); + } + else if ('level' in readConcern && readConcern.level) { + return new ReadConcern(readConcern.level); + } + } + if (options.level) { + return new ReadConcern(options.level); + } + } + static get MAJORITY() { + return exports.ReadConcernLevel.majority; + } + static get AVAILABLE() { + return exports.ReadConcernLevel.available; + } + static get LINEARIZABLE() { + return exports.ReadConcernLevel.linearizable; + } + static get SNAPSHOT() { + return exports.ReadConcernLevel.snapshot; + } + toJSON() { + return { level: this.level }; + } +} +exports.ReadConcern = ReadConcern; +//# sourceMappingURL=read_concern.js.map + +/***/ }), + +/***/ 9802: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ReadPreference = exports.ReadPreferenceMode = void 0; +const error_1 = __nccwpck_require__(9386); +/** @public */ +exports.ReadPreferenceMode = Object.freeze({ + primary: 'primary', + primaryPreferred: 'primaryPreferred', + secondary: 'secondary', + secondaryPreferred: 'secondaryPreferred', + nearest: 'nearest' +}); +/** + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * @public + * + * @see https://docs.mongodb.com/manual/core/read-preference/ + */ +class ReadPreference { + /** + * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param tags - A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary. + * @param options - Additional read preference options + */ + constructor(mode, tags, options) { + if (!ReadPreference.isValid(mode)) { + throw new error_1.MongoInvalidArgumentError(`Invalid read preference mode ${JSON.stringify(mode)}`); + } + if (options == null && typeof tags === 'object' && !Array.isArray(tags)) { + options = tags; + tags = undefined; + } + else if (tags && !Array.isArray(tags)) { + throw new error_1.MongoInvalidArgumentError('ReadPreference tags must be an array'); + } + this.mode = mode; + this.tags = tags; + this.hedge = options === null || options === void 0 ? void 0 : options.hedge; + this.maxStalenessSeconds = undefined; + this.minWireVersion = undefined; + options = options !== null && options !== void 0 ? options : {}; + if (options.maxStalenessSeconds != null) { + if (options.maxStalenessSeconds <= 0) { + throw new error_1.MongoInvalidArgumentError('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 error_1.MongoInvalidArgumentError('Primary read preference cannot be combined with tags'); + } + if (this.maxStalenessSeconds) { + throw new error_1.MongoInvalidArgumentError('Primary read preference cannot be combined with maxStalenessSeconds'); + } + if (this.hedge) { + throw new error_1.MongoInvalidArgumentError('Primary read preference cannot be combined with hedge'); + } + } + } + // Support the deprecated `preference` property introduced in the porcelain layer + get preference() { + return this.mode; + } + static fromString(mode) { + return new ReadPreference(mode); + } + /** + * Construct a ReadPreference given an options object. + * + * @param options - The options object from which to extract the read preference. + */ + static fromOptions(options) { + var _a, _b, _c; + if (!options) + return; + const readPreference = (_a = options.readPreference) !== null && _a !== void 0 ? _a : (_b = options.session) === null || _b === void 0 ? void 0 : _b.transaction.options.readPreference; + const readPreferenceTags = options.readPreferenceTags; + if (readPreference == null) { 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; + if (typeof readPreference === 'string') { + return new ReadPreference(readPreference, readPreferenceTags, { + maxStalenessSeconds: options.maxStalenessSeconds, + hedge: options.hedge + }); } - - 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; + else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') { + const mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode === 'string') { + return new ReadPreference(mode, (_c = readPreference.tags) !== null && _c !== void 0 ? _c : readPreferenceTags, { + maxStalenessSeconds: readPreference.maxStalenessSeconds, + hedge: options.hedge + }); + } } - - const commandOptions = Object.assign( - { - returnFieldSelector: null, - documentsReturnedIn: "nextBatch", - }, - options - ); - - if (cursorState.session) { - commandOptions.session = cursorState.session; + if (readPreferenceTags) { + readPreference.tags = readPreferenceTags; } - - command(server, ns, getMoreCmd, commandOptions, queryCallback); - } - - module.exports = getMore; - - /***/ - }, - - /***/ 9206: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const writeCommand = __nccwpck_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: __nccwpck_require__(6044), - getMore: __nccwpck_require__(1971), - query: __nccwpck_require__(1820), - command: __nccwpck_require__(7276), - }; - - /***/ - }, - - /***/ 6044: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const KillCursor = __nccwpck_require__(9814).KillCursor; - const MongoError = __nccwpck_require__(3111).MongoError; - const MongoNetworkError = __nccwpck_require__(3111).MongoNetworkError; - const collectionNamespace = __nccwpck_require__(7272).collectionNamespace; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const emitWarning = __nccwpck_require__(1178).emitWarning; - const command = __nccwpck_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 { - emitWarning(err); - } + return readPreference; + } + /** + * Replaces options.readPreference with a ReadPreference instance + */ + static translate(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 + }); } - } - - 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, - __nccwpck_require__ - ) => { - "use strict"; - - const Query = __nccwpck_require__(9814).Query; - const MongoError = __nccwpck_require__(3111).MongoError; - const getReadPreference = __nccwpck_require__(7272).getReadPreference; - const collectionNamespace = __nccwpck_require__(7272).collectionNamespace; - const isSharded = __nccwpck_require__(7272).isSharded; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const applyCommonQueryOptions = - __nccwpck_require__(7272).applyCommonQueryOptions; - const command = __nccwpck_require__(7276); - const decorateWithExplain = __nccwpck_require__(1371).decorateWithExplain; - const Explain = __nccwpck_require__(5293).Explain; - - function query(server, ns, cmd, cursorState, options, callback) { - options = options || {}; - if (cursorState.cursorId != null) { - return callback(); + else if (!(r instanceof ReadPreference)) { + throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${r}`); } - - if (cmd == null) { - return callback( - new MongoError( - `command ${JSON.stringify(cmd)} does not return a cursor` - ) - ); + return options; + } + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + static isValid(mode) { + const VALID_MODES = new Set([ + ReadPreference.PRIMARY, + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST, + null + ]); + return VALID_MODES.has(mode); + } + /** + * Validate if a mode is legal + * + * @param mode - The string representing the read preference mode. + */ + isValid(mode) { + return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); + } + /** + * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire + * + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ + slaveOk() { + const NEEDS_SLAVEOK = new Set([ + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST + ]); + return NEEDS_SLAVEOK.has(this.mode); + } + /** + * Check if the two ReadPreferences are equivalent + * + * @param readPreference - The read preference with which to check equality + */ + equals(readPreference) { + return readPreference.mode === this.mode; + } + /** Return JSON representation */ + toJSON() { + 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; + } +} +exports.ReadPreference = ReadPreference; +ReadPreference.PRIMARY = exports.ReadPreferenceMode.primary; +ReadPreference.PRIMARY_PREFERRED = exports.ReadPreferenceMode.primaryPreferred; +ReadPreference.SECONDARY = exports.ReadPreferenceMode.secondary; +ReadPreference.SECONDARY_PREFERRED = exports.ReadPreferenceMode.secondaryPreferred; +ReadPreference.NEAREST = exports.ReadPreferenceMode.nearest; +ReadPreference.primary = new ReadPreference(exports.ReadPreferenceMode.primary); +ReadPreference.primaryPreferred = new ReadPreference(exports.ReadPreferenceMode.primaryPreferred); +ReadPreference.secondary = new ReadPreference(exports.ReadPreferenceMode.secondary); +ReadPreference.secondaryPreferred = new ReadPreference(exports.ReadPreferenceMode.secondaryPreferred); +ReadPreference.nearest = new ReadPreference(exports.ReadPreferenceMode.nearest); +//# sourceMappingURL=read_preference.js.map + +/***/ }), + +/***/ 472: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports._advanceClusterTime = exports.clearAndRemoveTimerFrom = exports.drainTimerQueue = exports.ServerType = exports.TopologyType = exports.STATE_CONNECTED = exports.STATE_CONNECTING = exports.STATE_CLOSED = exports.STATE_CLOSING = void 0; +// shared state names +exports.STATE_CLOSING = 'closing'; +exports.STATE_CLOSED = 'closed'; +exports.STATE_CONNECTING = 'connecting'; +exports.STATE_CONNECTED = 'connected'; +/** + * An enumeration of topology types we know about + * @public + */ +exports.TopologyType = Object.freeze({ + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown', + LoadBalanced: 'LoadBalanced' +}); +/** + * An enumeration of server types we know about + * @public + */ +exports.ServerType = Object.freeze({ + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown', + LoadBalancer: 'LoadBalancer' +}); +/** @internal */ +function drainTimerQueue(queue) { + queue.forEach(clearTimeout); + queue.clear(); +} +exports.drainTimerQueue = drainTimerQueue; +/** @internal */ +function clearAndRemoveTimerFrom(timer, timers) { + clearTimeout(timer); + return timers.delete(timer); +} +exports.clearAndRemoveTimerFrom = clearAndRemoveTimerFrom; +/** Shared function to determine clusterTime for a given topology or session */ +function _advanceClusterTime(entity, $clusterTime) { + if (entity.clusterTime == null) { + entity.clusterTime = $clusterTime; + } + else { + if ($clusterTime.clusterTime.greaterThan(entity.clusterTime.clusterTime)) { + entity.clusterTime = $clusterTime; } + } +} +exports._advanceClusterTime = _advanceClusterTime; +//# sourceMappingURL=common.js.map - 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; - } +/***/ 2464: +/***/ ((__unused_webpack_module, exports) => { - const readPreference = getReadPreference(cmd, options); - let findCmd = prepareFindCommand(server, ns, cmd, cursorState, options); +"use strict"; - // If we have explain, we need to rewrite the find command - // to wrap it in the explain command - const explain = Explain.fromOptions(options); - if (explain) { - findCmd = decorateWithExplain(findCmd, explain); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ServerHeartbeatFailedEvent = exports.ServerHeartbeatSucceededEvent = exports.ServerHeartbeatStartedEvent = exports.TopologyClosedEvent = exports.TopologyOpeningEvent = exports.TopologyDescriptionChangedEvent = exports.ServerClosedEvent = exports.ServerOpeningEvent = exports.ServerDescriptionChangedEvent = void 0; +/** + * Emitted when server description changes, but does NOT include changes to the RTT. + * @public + * @category Event + */ +class ServerDescriptionChangedEvent { + /** @internal */ + constructor(topologyId, address, previousDescription, newDescription) { + this.topologyId = topologyId; + this.address = address; + this.previousDescription = previousDescription; + this.newDescription = newDescription; + } +} +exports.ServerDescriptionChangedEvent = ServerDescriptionChangedEvent; +/** + * Emitted when server is initialized. + * @public + * @category Event + */ +class ServerOpeningEvent { + /** @internal */ + constructor(topologyId, address) { + this.topologyId = topologyId; + this.address = address; + } +} +exports.ServerOpeningEvent = ServerOpeningEvent; +/** + * Emitted when server is closed. + * @public + * @category Event + */ +class ServerClosedEvent { + /** @internal */ + constructor(topologyId, address) { + this.topologyId = topologyId; + this.address = address; + } +} +exports.ServerClosedEvent = ServerClosedEvent; +/** + * Emitted when topology description changes. + * @public + * @category Event + */ +class TopologyDescriptionChangedEvent { + /** @internal */ + constructor(topologyId, previousDescription, newDescription) { + this.topologyId = topologyId; + this.previousDescription = previousDescription; + this.newDescription = newDescription; + } +} +exports.TopologyDescriptionChangedEvent = TopologyDescriptionChangedEvent; +/** + * Emitted when topology is initialized. + * @public + * @category Event + */ +class TopologyOpeningEvent { + /** @internal */ + constructor(topologyId) { + this.topologyId = topologyId; + } +} +exports.TopologyOpeningEvent = TopologyOpeningEvent; +/** + * Emitted when topology is closed. + * @public + * @category Event + */ +class TopologyClosedEvent { + /** @internal */ + constructor(topologyId) { + this.topologyId = topologyId; + } +} +exports.TopologyClosedEvent = TopologyClosedEvent; +/** + * Emitted when the server monitor’s ismaster command is started - immediately before + * the ismaster command is serialized into raw BSON and written to the socket. + * + * @public + * @category Event + */ +class ServerHeartbeatStartedEvent { + /** @internal */ + constructor(connectionId) { + this.connectionId = connectionId; + } +} +exports.ServerHeartbeatStartedEvent = ServerHeartbeatStartedEvent; +/** + * Emitted when the server monitor’s ismaster succeeds. + * @public + * @category Event + */ +class ServerHeartbeatSucceededEvent { + /** @internal */ + constructor(connectionId, duration, reply) { + this.connectionId = connectionId; + this.duration = duration; + this.reply = reply; + } +} +exports.ServerHeartbeatSucceededEvent = ServerHeartbeatSucceededEvent; +/** + * Emitted when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. + * @public + * @category Event + */ +class ServerHeartbeatFailedEvent { + /** @internal */ + constructor(connectionId, duration, failure) { + this.connectionId = connectionId; + this.duration = duration; + this.failure = failure; + } +} +exports.ServerHeartbeatFailedEvent = ServerHeartbeatFailedEvent; +//# sourceMappingURL=events.js.map + +/***/ }), + +/***/ 1785: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RTTPinger = exports.Monitor = void 0; +const common_1 = __nccwpck_require__(472); +const utils_1 = __nccwpck_require__(1371); +const connect_1 = __nccwpck_require__(5579); +const connection_1 = __nccwpck_require__(9820); +const error_1 = __nccwpck_require__(9386); +const bson_1 = __nccwpck_require__(5578); +const events_1 = __nccwpck_require__(2464); +const server_1 = __nccwpck_require__(165); +const mongo_types_1 = __nccwpck_require__(696); +/** @internal */ +const kServer = Symbol('server'); +/** @internal */ +const kMonitorId = Symbol('monitorId'); +/** @internal */ +const kConnection = Symbol('connection'); +/** @internal */ +const kCancellationToken = Symbol('cancellationToken'); +/** @internal */ +const kRTTPinger = Symbol('rttPinger'); +/** @internal */ +const kRoundTripTime = Symbol('roundTripTime'); +const STATE_IDLE = 'idle'; +const STATE_MONITORING = 'monitoring'; +const stateTransition = (0, utils_1.makeStateMachine)({ + [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, STATE_IDLE, common_1.STATE_CLOSED], + [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, STATE_MONITORING], + [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, common_1.STATE_CLOSING], + [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, common_1.STATE_CLOSING] +}); +const INVALID_REQUEST_CHECK_STATES = new Set([common_1.STATE_CLOSING, common_1.STATE_CLOSED, STATE_MONITORING]); +function isInCloseState(monitor) { + return monitor.s.state === common_1.STATE_CLOSED || monitor.s.state === common_1.STATE_CLOSING; +} +/** @internal */ +class Monitor extends mongo_types_1.TypedEventEmitter { + constructor(server, options) { + var _a, _b, _c; + super(); + this[kServer] = server; + this[kConnection] = undefined; + this[kCancellationToken] = new mongo_types_1.CancellationToken(); + this[kCancellationToken].setMaxListeners(Infinity); + this[kMonitorId] = undefined; + this.s = { + state: common_1.STATE_CLOSED + }; + this.address = server.description.address; + this.options = Object.freeze({ + connectTimeoutMS: (_a = options.connectTimeoutMS) !== null && _a !== void 0 ? _a : 10000, + heartbeatFrequencyMS: (_b = options.heartbeatFrequencyMS) !== null && _b !== void 0 ? _b : 10000, + minHeartbeatFrequencyMS: (_c = options.minHeartbeatFrequencyMS) !== null && _c !== void 0 ? _c : 500 + }); + const cancellationToken = this[kCancellationToken]; + // TODO: refactor this to pull it directly from the pool, requires new ConnectionPool integration + const connectOptions = Object.assign({ + id: '', + generation: server.s.pool.generation, + connectionType: connection_1.Connection, + cancellationToken, + hostAddress: server.description.hostAddress + }, options, + // force BSON serialization options + { + raw: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: true + }); + // ensure no authentication is used for monitoring + delete connectOptions.credentials; + if (connectOptions.autoEncrypter) { + delete connectOptions.autoEncrypter; } - - // 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; + this.connectOptions = Object.freeze(connectOptions); + } + connect() { + if (this.s.state !== common_1.STATE_CLOSED) { + return; } - - if (cursorState.session) { - commandOptions.session = cursorState.session; + // start + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = (0, utils_1.makeInterruptibleAsyncInterval)(monitorServer(this), { + interval: heartbeatFrequencyMS, + minInterval: minHeartbeatFrequencyMS, + immediate: true + }); + } + requestCheck() { + var _a; + if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) { + return; } - - command(server, ns, findCmd, commandOptions, callback); - } - - function prepareFindCommand(server, ns, cmd, cursorState) { - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - const findCmd = { - find: collectionNamespace(ns), - }; - - if (cmd.query) { - if (cmd.query["$query"]) { - findCmd.filter = cmd.query["$query"]; - } else { - findCmd.filter = cmd.query; - } + (_a = this[kMonitorId]) === null || _a === void 0 ? void 0 : _a.wake(); + } + reset() { + const topologyVersion = this[kServer].description.topologyVersion; + if (isInCloseState(this) || topologyVersion == null) { + return; } - - 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; + stateTransition(this, common_1.STATE_CLOSING); + resetMonitorState(this); + // restart monitor + stateTransition(this, STATE_IDLE); + // restart monitoring + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = (0, utils_1.makeInterruptibleAsyncInterval)(monitorServer(this), { + interval: heartbeatFrequencyMS, + minInterval: minHeartbeatFrequencyMS + }); + } + close() { + if (isInCloseState(this)) { + return; + } + stateTransition(this, common_1.STATE_CLOSING); + resetMonitorState(this); + // close monitor + this.emit('close'); + stateTransition(this, common_1.STATE_CLOSED); + } +} +exports.Monitor = Monitor; +function resetMonitorState(monitor) { + var _a, _b, _c; + (_a = monitor[kMonitorId]) === null || _a === void 0 ? void 0 : _a.stop(); + monitor[kMonitorId] = undefined; + (_b = monitor[kRTTPinger]) === null || _b === void 0 ? void 0 : _b.close(); + monitor[kRTTPinger] = undefined; + monitor[kCancellationToken].emit('cancel'); + (_c = monitor[kConnection]) === null || _c === void 0 ? void 0 : _c.destroy({ force: true }); + monitor[kConnection] = undefined; +} +function checkServer(monitor, callback) { + let start = (0, utils_1.now)(); + monitor.emit(server_1.Server.SERVER_HEARTBEAT_STARTED, new events_1.ServerHeartbeatStartedEvent(monitor.address)); + function failureHandler(err) { + var _a; + (_a = monitor[kConnection]) === null || _a === void 0 ? void 0 : _a.destroy({ force: true }); + monitor[kConnection] = undefined; + monitor.emit(server_1.Server.SERVER_HEARTBEAT_FAILED, new events_1.ServerHeartbeatFailedEvent(monitor.address, (0, utils_1.calculateDurationInMs)(start), err)); + monitor.emit('resetServer', err); + monitor.emit('resetConnectionPool'); + callback(err); + } + const connection = monitor[kConnection]; + if (connection && !connection.closed) { + const { serverApi, helloOk } = connection; + const connectTimeoutMS = monitor.options.connectTimeoutMS; + const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS; + const topologyVersion = monitor[kServer].description.topologyVersion; + const isAwaitable = topologyVersion != null; + const cmd = { + [(serverApi === null || serverApi === void 0 ? void 0 : serverApi.version) || helloOk ? 'hello' : 'ismaster']: true, + ...(isAwaitable && topologyVersion + ? { maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) } + : {}) + }; + const options = isAwaitable + ? { + socketTimeoutMS: connectTimeoutMS ? connectTimeoutMS + maxAwaitTimeMS : 0, + exhaustAllowed: true + } + : { socketTimeoutMS: connectTimeoutMS }; + if (isAwaitable && monitor[kRTTPinger] == null) { + monitor[kRTTPinger] = new RTTPinger(monitor[kCancellationToken], Object.assign({ heartbeatFrequencyMS: monitor.options.heartbeatFrequencyMS }, monitor.connectOptions)); + } + connection.command((0, utils_1.ns)('admin.$cmd'), cmd, options, (err, isMaster) => { + var _a; + if (err) { + failureHandler(err); + return; } - - 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; + if ('isWritablePrimary' in isMaster) { + // Provide pre-hello-style response document. + isMaster.ismaster = isMaster.isWritablePrimary; + } + const rttPinger = monitor[kRTTPinger]; + const duration = isAwaitable && rttPinger ? rttPinger.roundTripTime : (0, utils_1.calculateDurationInMs)(start); + monitor.emit(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, new events_1.ServerHeartbeatSucceededEvent(monitor.address, duration, isMaster)); + // 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(server_1.Server.SERVER_HEARTBEAT_STARTED, new events_1.ServerHeartbeatStartedEvent(monitor.address)); + start = (0, utils_1.now)(); + } + else { + (_a = monitor[kRTTPinger]) === null || _a === void 0 ? void 0 : _a.close(); + monitor[kRTTPinger] = undefined; + callback(undefined, isMaster); } - } - - 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; + }); + return; + } + // connecting does an implicit `ismaster` + (0, connect_1.connect)(monitor.connectOptions, (err, conn) => { + if (err) { + monitor[kConnection] = undefined; + // we already reset the connection pool on network errors in all cases + if (!(err instanceof error_1.MongoNetworkError)) { + monitor.emit('resetConnectionPool'); + } + failureHandler(err); + return; } - - 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); + if (conn) { + if (isInCloseState(monitor)) { + conn.destroy({ force: true }); + return; } - - findCmd.singleBatch = true; - } - - findCmd.batchSize = Math.abs(cmd.batchSize); + monitor[kConnection] = conn; + monitor.emit(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, new events_1.ServerHeartbeatSucceededEvent(monitor.address, (0, utils_1.calculateDurationInMs)(start), conn.ismaster)); + callback(undefined, conn.ismaster); } - - 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; - - 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 (options.explain !== undefined) { - // 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}` - ); + }); +} +function monitorServer(monitor) { + return (callback) => { + stateTransition(monitor, STATE_MONITORING); + function done() { + if (!isInCloseState(monitor)) { + stateTransition(monitor, STATE_IDLE); + } + callback(); } - - 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, + checkServer(monitor, (err, isMaster) => { + if (err) { + // otherwise an error occurred on initial discovery, also bail + if (monitor[kServer].description.type === common_1.ServerType.Unknown) { + monitor.emit('resetServer', err); + return done(); + } + } + // if the check indicates streaming is supported, immediately reschedule monitoring + if (isMaster && isMaster.topologyVersion) { + setTimeout(() => { + var _a; + if (!isInCloseState(monitor)) { + (_a = monitor[kMonitorId]) === null || _a === void 0 ? void 0 : _a.wake(); + } + }, 0); + } + done(); }); - - 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, - __nccwpck_require__ - ) => { - "use strict"; - - const ReadPreference = __nccwpck_require__(4485); - const MongoError = __nccwpck_require__(3111).MongoError; - const ServerType = __nccwpck_require__(2291).ServerType; - const TopologyDescription = __nccwpck_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; + }; +} +function makeTopologyVersion(tv) { + return { + processId: tv.processId, + // tests mock counter as just number, but in a real situation counter should always be a Long + counter: bson_1.Long.isLong(tv.counter) ? tv.counter : bson_1.Long.fromNumber(tv.counter) + }; +} +/** @internal */ +class RTTPinger { + constructor(cancellationToken, options) { + this[kConnection] = undefined; + 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() { + var _a; + this.closed = true; + clearTimeout(this[kMonitorId]); + (_a = this[kConnection]) === null || _a === void 0 ? void 0 : _a.destroy({ force: true }); + this[kConnection] = undefined; + } +} +exports.RTTPinger = RTTPinger; +function measureRoundTripTime(rttPinger, options) { + const start = (0, utils_1.now)(); + options.cancellationToken = rttPinger[kCancellationToken]; + const heartbeatFrequencyMS = options.heartbeatFrequencyMS; + if (rttPinger.closed) { + return; + } + function measureAndReschedule(conn) { + if (rttPinger.closed) { + conn === null || conn === void 0 ? void 0 : conn.destroy({ force: true }); + return; } - - if (typeof readPreference === "string") { - readPreference = new ReadPreference(readPreference); + if (rttPinger[kConnection] == null) { + rttPinger[kConnection] = conn; } - - if (!(readPreference instanceof ReadPreference)) { - throw new MongoError( - "read preference must be a ReadPreference instance" - ); + rttPinger[kRoundTripTime] = (0, utils_1.calculateDurationInMs)(start); + rttPinger[kMonitorId] = setTimeout(() => measureRoundTripTime(rttPinger, options), heartbeatFrequencyMS); + } + const connection = rttPinger[kConnection]; + if (connection == null) { + (0, connect_1.connect)(options, (err, conn) => { + if (err) { + rttPinger[kConnection] = undefined; + rttPinger[kRoundTripTime] = 0; + return; + } + measureAndReschedule(conn); + }); + return; + } + connection.command((0, utils_1.ns)('admin.$cmd'), { ismaster: 1 }, undefined, err => { + if (err) { + rttPinger[kConnection] = undefined; + rttPinger[kRoundTripTime] = 0; + return; } - - 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), + measureAndReschedule(); + }); +} +//# sourceMappingURL=monitor.js.map + +/***/ }), + +/***/ 165: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.HEARTBEAT_EVENTS = exports.Server = void 0; +const logger_1 = __nccwpck_require__(8874); +const connection_pool_1 = __nccwpck_require__(2529); +const server_description_1 = __nccwpck_require__(9753); +const monitor_1 = __nccwpck_require__(1785); +const transactions_1 = __nccwpck_require__(8883); +const utils_1 = __nccwpck_require__(1371); +const common_1 = __nccwpck_require__(472); +const error_1 = __nccwpck_require__(9386); +const connection_1 = __nccwpck_require__(9820); +const mongo_types_1 = __nccwpck_require__(696); +const utils_2 = __nccwpck_require__(1371); +const stateTransition = (0, utils_1.makeStateMachine)({ + [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, common_1.STATE_CONNECTING], + [common_1.STATE_CONNECTING]: [common_1.STATE_CONNECTING, common_1.STATE_CLOSING, common_1.STATE_CONNECTED, common_1.STATE_CLOSED], + [common_1.STATE_CONNECTED]: [common_1.STATE_CONNECTED, common_1.STATE_CLOSING, common_1.STATE_CLOSED], + [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, common_1.STATE_CLOSED] +}); +/** @internal */ +const kMonitor = Symbol('monitor'); +/** @internal */ +class Server extends mongo_types_1.TypedEventEmitter { + /** + * Create a server + */ + constructor(topology, description, options) { + super(); + this.serverApi = options.serverApi; + const poolOptions = { hostAddress: description.hostAddress, ...options }; + this.s = { + description, + options, + logger: new logger_1.Logger('Server'), + state: common_1.STATE_CLOSED, + topology, + pool: new connection_pool_1.ConnectionPool(poolOptions) }; - }; - - 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, - bsonRegExp: - typeof options.bsonRegExp === "boolean" - ? options.bsonRegExp - : false, - monitoring: - typeof options.monitoring === "boolean" - ? options.monitoring - : false, - fullResult: - typeof options.fullResult === "boolean" - ? options.fullResult - : false, + for (const event of [...connection_pool_1.CMAP_EVENTS, ...connection_1.APM_EVENTS]) { + this.s.pool.on(event, (e) => this.emit(event, e)); + } + this.s.pool.on(connection_1.Connection.CLUSTER_TIME_RECEIVED, (clusterTime) => { + this.clusterTime = clusterTime; }); - - if (typeof options.socketTimeout === "number") { - queryOptions.socketTimeout = options.socketTimeout; + // monitoring is disabled in load balancing mode + if (this.loadBalanced) + return; + // create the monitor + this[kMonitor] = new monitor_1.Monitor(this, this.s.options); + for (const event of exports.HEARTBEAT_EVENTS) { + this[kMonitor].on(event, (e) => this.emit(event, e)); } - - if (options.session) { - queryOptions.session = options.session; + this[kMonitor].on('resetConnectionPool', () => { + this.s.pool.clear(); + }); + this[kMonitor].on('resetServer', (error) => markServerUnknown(this, error)); + this[kMonitor].on(Server.SERVER_HEARTBEAT_SUCCEEDED, (event) => { + this.emit(Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(this.description.hostAddress, event.reply, { + roundTripTime: calculateRoundTripTime(this.description.roundTripTime, event.duration) + })); + if (this.s.state === common_1.STATE_CONNECTING) { + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Server.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; } - - if (typeof options.documentsReturnedIn === "string") { - queryOptions.documentsReturnedIn = options.documentsReturnedIn; + } + get loadBalanced() { + return this.s.topology.description.type === common_1.TopologyType.LoadBalanced; + } + /** + * Initiate server connect + */ + connect() { + if (this.s.state !== common_1.STATE_CLOSED) { + return; } - - return queryOptions; - } - - function isSharded(topologyOrServer) { - if (topologyOrServer.type === "mongos") return true; - if ( - topologyOrServer.description && - topologyOrServer.description.type === ServerType.Mongos - ) { - return true; + stateTransition(this, common_1.STATE_CONNECTING); + // If in load balancer mode we automatically set the server to + // a load balancer. It never transitions out of this state and + // has no monitor. + if (!this.loadBalanced) { + this[kMonitor].connect(); } - - // 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); + else { + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Server.CONNECT, this); } - - 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, - __nccwpck_require__ - ) => { - "use strict"; - - const MongoError = __nccwpck_require__(3111).MongoError; - const collectionNamespace = __nccwpck_require__(7272).collectionNamespace; - const command = __nccwpck_require__(7276); - const decorateWithExplain = __nccwpck_require__(1371).decorateWithExplain; - const Explain = __nccwpck_require__(5293).Explain; - - 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 = {}; + } + /** Destroy the server connection */ + destroy(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = Object.assign({}, { force: false }, options); + if (this.s.state === common_1.STATE_CLOSED) { + if (typeof callback === 'function') { + callback(); + } + return; } - - options = options || {}; - const ordered = - typeof options.ordered === "boolean" ? options.ordered : true; - const writeConcern = options.writeConcern; - - let writeCommand = {}; - writeCommand[type] = collectionNamespace(ns); - writeCommand[opsField] = ops; - writeCommand.ordered = ordered; - - if (writeConcern && Object.keys(writeConcern).length > 0) { - writeCommand.writeConcern = writeConcern; + stateTransition(this, common_1.STATE_CLOSING); + if (!this.loadBalanced) { + this[kMonitor].close(); } - - if (options.collation) { - for (let i = 0; i < writeCommand[opsField].length; i++) { - if (!writeCommand[opsField][i].collation) { - writeCommand[opsField][i].collation = options.collation; + this.s.pool.close(options, err => { + stateTransition(this, common_1.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() { + if (!this.loadBalanced) { + this[kMonitor].requestCheck(); } - - if (options.bypassDocumentValidation === true) { - writeCommand.bypassDocumentValidation = - options.bypassDocumentValidation; + } + command(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options !== null && options !== void 0 ? options : {}); } - - // If a command is to be explained, we need to reformat the command after - // the other command properties are specified. - const explain = Explain.fromOptions(options); - if (explain) { - writeCommand = decorateWithExplain(writeCommand, explain); + if (callback == null) { + throw new error_1.MongoInvalidArgumentError('Callback must be provided'); } - - const commandOptions = Object.assign( - { - checkKeys: type === "insert", - numberToReturn: 1, - }, - options - ); - - command(server, ns, writeCommand, commandOptions, callback); - } - - module.exports = writeCommand; - - /***/ - }, - - /***/ 7159: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Transform = __nccwpck_require__(2413).Transform; - const PassThrough = __nccwpck_require__(2413).PassThrough; - const deprecate = __nccwpck_require__(1669).deprecate; - const handleCallback = __nccwpck_require__(1371).handleCallback; - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const MongoError = __nccwpck_require__(3994).MongoError; - const CoreCursor = __nccwpck_require__(4847).CoreCursor; - const CursorState = __nccwpck_require__(4847).CursorState; - const Map = __nccwpck_require__(3994).BSON.Map; - const maybePromise = __nccwpck_require__(1371).maybePromise; - const executeOperation = __nccwpck_require__(2548); - const formattedOrderClause = - __nccwpck_require__(1371).formattedOrderClause; - const Explain = __nccwpck_require__(5293).Explain; - const Aspect = __nccwpck_require__(1018).Aspect; - - const each = __nccwpck_require__(3554).each; - const CountOperation = __nccwpck_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); + if (ns.db == null || typeof ns === 'string') { + throw new error_1.MongoInvalidArgumentError('Namespace must not be a string'); } - - get readPreference() { - if (this.operation) { - return this.operation.readPreference; - } - - return this.options.readPreference; + if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) { + callback(new error_1.MongoServerClosedError()); + return; } - - get sortValue() { - return this.cmd.sort; + // Clone the options + const finalOptions = Object.assign({}, options, { wireProtocolCommand: false }); + // There are cases where we need to flag the read preference not to get sent in + // the command, such as pre-5.0 servers attempting to perform an aggregate write + // with a non-primary read preference. In this case the effective read preference + // (primary) is not the same as the provided and must be removed completely. + if (finalOptions.omitReadPreference) { + delete finalOptions.readPreference; } - - _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); + // error if collation not supported + if ((0, utils_1.collationNotSupported)(this, cmd)) { + callback(new error_1.MongoCompatibilityError(`Server ${this.name} does not support collation`)); + return; } - - /** - * 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); + const session = finalOptions.session; + const conn = session === null || session === void 0 ? void 0 : session.pinnedConnection; + // NOTE: This is a hack! We can't retrieve the connections used for executing an operation + // (and prevent them from being checked back in) at the point of operation execution. + // This should be considered as part of the work for NODE-2882 + if (this.loadBalanced && session && conn == null && isPinnableCommand(cmd, session)) { + this.s.pool.checkOut((err, checkedOut) => { + if (err || checkedOut == null) { + if (callback) + return callback(err); + return; + } + session.pin(checkedOut); + this.command(ns, cmd, finalOptions, callback); }); - }); + return; } - - /** - * 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) { + this.s.pool.withConnection(conn, (err, conn, cb) => { + if (err || !conn) { + markServerUnknown(this, 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; + conn.command(ns, cmd, finalOptions, makeOperationHandler(this, conn, cmd, finalOptions, cb)); + }, callback); + } + /** + * Execute a query against the server + * @internal + */ + query(ns, cmd, options, callback) { + if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) { + callback(new error_1.MongoServerClosedError()); + return; } - - /** - * 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; + this.s.pool.withConnection(undefined, (err, conn, cb) => { + if (err || !conn) { + markServerUnknown(this, err); + return cb(err); + } + conn.query(ns, cmd, options, makeOperationHandler(this, conn, cmd, options, cb)); + }, callback); + } + /** + * Execute a `getMore` against the server + * @internal + */ + getMore(ns, cursorId, options, callback) { + var _a; + if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) { + callback(new error_1.MongoServerClosedError()); + return; } - - /** - * 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; + this.s.pool.withConnection((_a = options.session) === null || _a === void 0 ? void 0 : _a.pinnedConnection, (err, conn, cb) => { + if (err || !conn) { + markServerUnknown(this, err); + return cb(err); + } + conn.getMore(ns, cursorId, options, makeOperationHandler(this, conn, {}, options, cb)); + }, callback); + } + /** + * Execute a `killCursors` command against the server + * @internal + */ + killCursors(ns, cursorIds, options, callback) { + var _a; + if (this.s.state === common_1.STATE_CLOSING || this.s.state === common_1.STATE_CLOSED) { + if (typeof callback === 'function') { + callback(new error_1.MongoServerClosedError()); + } + return; } - - /** - * 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; + this.s.pool.withConnection((_a = options.session) === null || _a === void 0 ? void 0 : _a.pinnedConnection, (err, conn, cb) => { + if (err || !conn) { + markServerUnknown(this, err); + return cb(err); + } + conn.killCursors(ns, cursorIds, options, makeOperationHandler(this, conn, {}, undefined, cb)); + }, callback); + } +} +exports.Server = Server; +/** @event */ +Server.SERVER_HEARTBEAT_STARTED = 'serverHeartbeatStarted'; +/** @event */ +Server.SERVER_HEARTBEAT_SUCCEEDED = 'serverHeartbeatSucceeded'; +/** @event */ +Server.SERVER_HEARTBEAT_FAILED = 'serverHeartbeatFailed'; +/** @event */ +Server.CONNECT = 'connect'; +/** @event */ +Server.DESCRIPTION_RECEIVED = 'descriptionReceived'; +/** @event */ +Server.CLOSED = 'closed'; +/** @event */ +Server.ENDED = 'ended'; +exports.HEARTBEAT_EVENTS = [ + Server.SERVER_HEARTBEAT_STARTED, + Server.SERVER_HEARTBEAT_SUCCEEDED, + Server.SERVER_HEARTBEAT_FAILED +]; +Object.defineProperty(Server.prototype, 'clusterTime', { + get() { + return this.s.topology.clusterTime; + }, + set(clusterTime) { + this.s.topology.clusterTime = clusterTime; + } +}); +function calculateRoundTripTime(oldRtt, duration) { + if (oldRtt === -1) { + return duration; + } + const alpha = 0.2; + return alpha * duration + (1 - alpha) * oldRtt; +} +function markServerUnknown(server, error) { + // Load balancer servers can never be marked unknown. + if (server.loadBalanced) { + return; + } + if (error instanceof error_1.MongoNetworkError && !(error instanceof error_1.MongoNetworkTimeoutError)) { + server[kMonitor].reset(); + } + server.emit(Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(server.description.hostAddress, undefined, { + error, + topologyVersion: error && error.topologyVersion ? error.topologyVersion : server.description.topologyVersion + })); +} +function isPinnableCommand(cmd, session) { + if (session) { + return (session.inTransaction() || + 'aggregate' in cmd || + 'find' in cmd || + 'getMore' in cmd || + 'listCollections' in cmd || + 'listIndexes' in cmd); + } + return false; +} +function connectionIsStale(pool, connection) { + if (connection.serviceId) { + return (connection.generation !== pool.serviceGenerations.get(connection.serviceId.toHexString())); + } + return connection.generation !== pool.generation; +} +function shouldHandleStateChangeError(server, err) { + const etv = err.topologyVersion; + const stv = server.description.topologyVersion; + return (0, server_description_1.compareTopologyVersion)(stv, etv) < 0; +} +function inActiveTransaction(session, cmd) { + return session && session.inTransaction() && !(0, transactions_1.isTransactionCommand)(cmd); +} +/** this checks the retryWrites option passed down from the client options, it + * does not check if the server supports retryable writes */ +function isRetryableWritesEnabled(topology) { + return topology.s.options.retryWrites !== false; +} +function makeOperationHandler(server, connection, cmd, options, callback) { + const session = options === null || options === void 0 ? void 0 : options.session; + return function handleOperationResult(err, result) { + if (err && !connectionIsStale(server.s.pool, connection)) { + if (err instanceof error_1.MongoNetworkError) { + if (session && !session.hasEnded && session.serverSession) { + session.serverSession.isDirty = true; + } + // inActiveTransaction check handles commit and abort. + if (inActiveTransaction(session, cmd) && !err.hasErrorLabel('TransientTransactionError')) { + err.addErrorLabel('TransientTransactionError'); + } + if ((isRetryableWritesEnabled(server.s.topology) || (0, transactions_1.isTransactionCommand)(cmd)) && + (0, utils_2.supportsRetryableWrites)(server) && + !inActiveTransaction(session, cmd)) { + err.addErrorLabel('RetryableWriteError'); + } + if (!(err instanceof error_1.MongoNetworkTimeoutError) || (0, error_1.isNetworkErrorBeforeHandshake)(err)) { + // In load balanced mode we never mark the server as unknown and always + // clear for the specific service id. + server.s.pool.clear(connection.serviceId); + if (!server.loadBalanced) { + markServerUnknown(server, err); + } + } + } + else { + // if pre-4.4 server, then add error label if its a retryable write error + if ((isRetryableWritesEnabled(server.s.topology) || (0, transactions_1.isTransactionCommand)(cmd)) && + (0, utils_1.maxWireVersion)(server) < 9 && + (0, error_1.isRetryableWriteError)(err) && + !inActiveTransaction(session, cmd)) { + err.addErrorLabel('RetryableWriteError'); + } + if ((0, error_1.isSDAMUnrecoverableError)(err)) { + if (shouldHandleStateChangeError(server, err)) { + if ((0, utils_1.maxWireVersion)(server) <= 7 || (0, error_1.isNodeShuttingDownError)(err)) { + server.s.pool.clear(connection.serviceId); + } + if (!server.loadBalanced) { + markServerUnknown(server, err); + process.nextTick(() => server.requestCheck()); + } + } + } + } + if (session && session.isPinned && err.hasErrorLabel('TransientTransactionError')) { + session.unpin({ force: true }); + } } - - /** - * 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; + callback(err, result); + }; +} +//# sourceMappingURL=server.js.map + +/***/ }), + +/***/ 9753: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.compareTopologyVersion = exports.parseServerType = exports.ServerDescription = void 0; +const utils_1 = __nccwpck_require__(1371); +const common_1 = __nccwpck_require__(472); +const bson_1 = __nccwpck_require__(5578); +const WRITABLE_SERVER_TYPES = new Set([ + common_1.ServerType.RSPrimary, + common_1.ServerType.Standalone, + common_1.ServerType.Mongos, + common_1.ServerType.LoadBalancer +]); +const DATA_BEARING_SERVER_TYPES = new Set([ + common_1.ServerType.RSPrimary, + common_1.ServerType.RSSecondary, + common_1.ServerType.Mongos, + common_1.ServerType.Standalone, + common_1.ServerType.LoadBalancer +]); +/** + * The client's view of a single server, based on the most recent ismaster outcome. + * + * Internal type, not meant to be directly instantiated + * @public + */ +class ServerDescription { + /** + * Create a ServerDescription + * @internal + * + * @param address - The address of the server + * @param ismaster - An optional ismaster response for this server + */ + constructor(address, ismaster, options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + if (typeof address === 'string') { + this._hostAddress = new utils_1.HostAddress(address); + this.address = this._hostAddress.toString(); } - - /** - * 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; + else { + this._hostAddress = address; + this.address = this._hostAddress.toString(); } - - /** - * 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; + this.type = parseServerType(ismaster, options); + this.hosts = (_b = (_a = ismaster === null || ismaster === void 0 ? void 0 : ismaster.hosts) === null || _a === void 0 ? void 0 : _a.map((host) => host.toLowerCase())) !== null && _b !== void 0 ? _b : []; + this.passives = (_d = (_c = ismaster === null || ismaster === void 0 ? void 0 : ismaster.passives) === null || _c === void 0 ? void 0 : _c.map((host) => host.toLowerCase())) !== null && _d !== void 0 ? _d : []; + this.arbiters = (_f = (_e = ismaster === null || ismaster === void 0 ? void 0 : ismaster.arbiters) === null || _e === void 0 ? void 0 : _e.map((host) => host.toLowerCase())) !== null && _f !== void 0 ? _f : []; + this.tags = (_g = ismaster === null || ismaster === void 0 ? void 0 : ismaster.tags) !== null && _g !== void 0 ? _g : {}; + this.minWireVersion = (_h = ismaster === null || ismaster === void 0 ? void 0 : ismaster.minWireVersion) !== null && _h !== void 0 ? _h : 0; + this.maxWireVersion = (_j = ismaster === null || ismaster === void 0 ? void 0 : ismaster.maxWireVersion) !== null && _j !== void 0 ? _j : 0; + this.roundTripTime = (_k = options === null || options === void 0 ? void 0 : options.roundTripTime) !== null && _k !== void 0 ? _k : -1; + this.lastUpdateTime = (0, utils_1.now)(); + this.lastWriteDate = (_m = (_l = ismaster === null || ismaster === void 0 ? void 0 : ismaster.lastWrite) === null || _l === void 0 ? void 0 : _l.lastWriteDate) !== null && _m !== void 0 ? _m : 0; + if (options === null || options === void 0 ? void 0 : options.topologyVersion) { + this.topologyVersion = options.topologyVersion; } - - /** - * 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; + else if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.topologyVersion) { + this.topologyVersion = ismaster.topologyVersion; } - - /** - * 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; + if (options === null || options === void 0 ? void 0 : options.error) { + this.error = options.error; } - - /** - * 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; + if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.primary) { + this.primary = ismaster.primary; } - - /** - * 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; + if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.me) { + this.me = ismaster.me.toLowerCase(); } - - /** - * 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; + if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.setName) { + this.setName = ismaster.setName; } - - /** - * 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; + if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.setVersion) { + this.setVersion = ismaster.setVersion; } - - /** - * 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; + if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.electionId) { + this.electionId = ismaster.electionId; } - - /** - * 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; + if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.logicalSessionTimeoutMinutes) { + this.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes; } - - /** - * 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; + if (ismaster === null || ismaster === void 0 ? void 0 : ismaster.$clusterTime) { + this.$clusterTime = ismaster.$clusterTime; } - - /** - * 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; + } + get hostAddress() { + if (this._hostAddress) + return this._hostAddress; + else + return new utils_1.HostAddress(this.address); + } + get allHosts() { + return this.hosts.concat(this.arbiters).concat(this.passives); + } + /** Is this server available for reads*/ + get isReadable() { + return this.type === common_1.ServerType.RSSecondary || this.isWritable; + } + /** Is this server data bearing */ + get isDataBearing() { + return DATA_BEARING_SERVER_TYPES.has(this.type); + } + /** 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) : 27017; + } + /** + * 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} + */ + equals(other) { + const topologyVersionsEqual = this.topologyVersion === other.topologyVersion || + compareTopologyVersion(this.topologyVersion, other.topologyVersion) === 0; + const electionIdsEqual = this.electionId && other.electionId + ? other.electionId && this.electionId.equals(other.electionId) + : this.electionId === other.electionId; + return (other != null && + (0, utils_1.errorStrictEqual)(this.error, other.error) && + this.type === other.type && + this.minWireVersion === other.minWireVersion && + (0, utils_1.arrayStrictEqual)(this.hosts, other.hosts) && + tagsStrictEqual(this.tags, other.tags) && + this.setName === other.setName && + this.setVersion === other.setVersion && + electionIdsEqual && + this.primary === other.primary && + this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes && + topologyVersionsEqual); + } +} +exports.ServerDescription = ServerDescription; +// Parses an `ismaster` message and determines the server type +function parseServerType(ismaster, options) { + if (options === null || options === void 0 ? void 0 : options.loadBalanced) { + return common_1.ServerType.LoadBalancer; + } + if (!ismaster || !ismaster.ok) { + return common_1.ServerType.Unknown; + } + if (ismaster.isreplicaset) { + return common_1.ServerType.RSGhost; + } + if (ismaster.msg && ismaster.msg === 'isdbgrid') { + return common_1.ServerType.Mongos; + } + if (ismaster.setName) { + if (ismaster.hidden) { + return common_1.ServerType.RSOther; } - - /** - * 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; + else if (ismaster.ismaster || ismaster.isWritablePrimary) { + return common_1.ServerType.RSPrimary; } - - /** - * 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; + else if (ismaster.secondary) { + return common_1.ServerType.RSSecondary; } - - /** - * 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); + else if (ismaster.arbiterOnly) { + return common_1.ServerType.RSArbiter; } - - /** - * 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) { - try { - iterator(doc); - } catch (error) { - callback(error); - return false; - } - 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 { - try { - iterator(doc); - } catch (error) { - reject(error); - return false; - } - return true; - } - }); - }); - } + else { + return common_1.ServerType.RSOther; } - - /** - * 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; + } + return common_1.ServerType.Standalone; +} +exports.parseServerType = parseServerType; +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])); +} +/** + * Compares two topology versions. + * + * @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)) { + // tests mock counter as just number, but in a real situation counter should always be a Long + const lhsCounter = bson_1.Long.isLong(lhs.counter) ? lhs.counter : bson_1.Long.fromNumber(lhs.counter); + const rhsCounter = bson_1.Long.isLong(rhs.counter) ? lhs.counter : bson_1.Long.fromNumber(rhs.counter); + return lhsCounter.compare(rhsCounter); + } + return -1; +} +exports.compareTopologyVersion = compareTopologyVersion; +//# sourceMappingURL=server_description.js.map + +/***/ }), + +/***/ 2081: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.readPreferenceServerSelector = exports.secondaryWritableServerSelector = exports.sameServerSelector = exports.writableServerSelector = exports.MIN_SECONDARY_WRITE_WIRE_VERSION = void 0; +const common_1 = __nccwpck_require__(472); +const read_preference_1 = __nccwpck_require__(9802); +const error_1 = __nccwpck_require__(9386); +// max staleness constants +const IDLE_WRITE_PERIOD = 10000; +const SMALLEST_MAX_STALENESS_SECONDS = 90; +// Minimum version to try writes on secondaries. +exports.MIN_SECONDARY_WRITE_WIRE_VERSION = 13; +/** + * Returns a server selector that selects for writable servers + */ +function writableServerSelector() { + return (topologyDescription, servers) => latencyWindowReducer(topologyDescription, servers.filter((s) => s.isWritable)); +} +exports.writableServerSelector = writableServerSelector; +/** + * The purpose of this selector is to select the same server, only + * if it is in a state that it can have commands sent to it. + */ +function sameServerSelector(description) { + return (topologyDescription, servers) => { + if (!description) + return []; + // Filter the servers to match the provided description only if + // the type is not unknown. + return servers.filter(sd => { + return sd.address === description.address && sd.type !== common_1.ServerType.Unknown; + }); + }; +} +exports.sameServerSelector = sameServerSelector; +/** + * Returns a server selector that uses a read preference to select a + * server potentially for a write on a secondary. + */ +function secondaryWritableServerSelector(wireVersion, readPreference) { + // If server version < 5.0, read preference always primary. + // If server version >= 5.0... + // - If read preference is supplied, use that. + // - If no read preference is supplied, use primary. + if (!readPreference || + !wireVersion || + (wireVersion && wireVersion < exports.MIN_SECONDARY_WRITE_WIRE_VERSION)) { + return readPreferenceServerSelector(read_preference_1.ReadPreference.primary); + } + return readPreferenceServerSelector(readPreference); +} +exports.secondaryWritableServerSelector = secondaryWritableServerSelector; +/** + * 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 - The read preference providing max staleness guidance + * @param topologyDescription - The topology description + * @param servers - The list of server descriptions to be reduced + * @returns 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 error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${maxStalenessVariance} seconds`); + } + if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { + throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds`); + } + if (topologyDescription.type === common_1.TopologyType.ReplicaSetWithPrimary) { + const primary = Array.from(topologyDescription.servers.values()).filter(primaryFilter)[0]; + return servers.reduce((result, server) => { + var _a; + const stalenessMS = server.lastUpdateTime - + server.lastWriteDate - + (primary.lastUpdateTime - primary.lastWriteDate) + + topologyDescription.heartbeatFrequencyMS; + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = (_a = readPreference.maxStalenessSeconds) !== null && _a !== void 0 ? _a : 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + return result; + }, []); + } + if (topologyDescription.type === common_1.TopologyType.ReplicaSetNoPrimary) { + if (servers.length === 0) { + return servers; } - - /** - * 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(); - }); + const sMax = servers.reduce((max, s) => s.lastWriteDate > max.lastWriteDate ? s : max); + return servers.reduce((result, server) => { + var _a; + const stalenessMS = sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = (_a = readPreference.maxStalenessSeconds) !== null && _a !== void 0 ? _a : 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + return result; + }, []); + } + return servers; +} +/** + * Determines whether a server's tags match a given set of tags + * + * @param tagSet - The requested tag set to match + * @param 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; } - - /** - * 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); + } + return true; +} +/** + * Reduces a set of server descriptions based on tags requested by the read preference + * + * @param readPreference - The read preference providing the requested tags + * @param servers - The list of server descriptions to reduce + * @returns 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 - The topology description + * @param servers - The list of servers to reduce + * @returns 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 === common_1.ServerType.RSPrimary; +} +function secondaryFilter(server) { + return server.type === common_1.ServerType.RSSecondary; +} +function nearestFilter(server) { + return server.type === common_1.ServerType.RSSecondary || server.type === common_1.ServerType.RSPrimary; +} +function knownFilter(server) { + return server.type !== common_1.ServerType.Unknown; +} +function loadBalancerFilter(server) { + return server.type === common_1.ServerType.LoadBalancer; +} +/** + * Returns a function which selects servers based on a provided read preference + * + * @param readPreference - The read preference to select with + */ +function readPreferenceServerSelector(readPreference) { + if (!readPreference.isValid()) { + throw new error_1.MongoInvalidArgumentError('Invalid read preference specified'); + } + return (topologyDescription, servers) => { + const commonWireVersion = topologyDescription.commonWireVersion; + if (commonWireVersion && + readPreference.minWireVersion && + readPreference.minWireVersion > commonWireVersion) { + throw new error_1.MongoCompatibilityError(`Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'`); } - - /** - * 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); - }); - }); + if (topologyDescription.type === common_1.TopologyType.LoadBalanced) { + return servers.filter(loadBalancerFilter); } - - /** - * 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; + if (topologyDescription.type === common_1.TopologyType.Unknown) { + return []; } - - /** - * Is the cursor closed - * @method - * @return {boolean} - */ - isClosed() { - return this.isDead(); + if (topologyDescription.type === common_1.TopologyType.Single || + topologyDescription.type === common_1.TopologyType.Sharded) { + return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); } - - destroy(err) { - if (err) this.emit("error", err); - this.pause(); - this.close(); + const mode = readPreference.mode; + if (mode === read_preference_1.ReadPreference.PRIMARY) { + return servers.filter(primaryFilter); } - - /** - * 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: replace this method with transformStream in next major release - */ - stream(options) { - this.cursorState.streamOptions = options || {}; - return this; + if (mode === read_preference_1.ReadPreference.PRIMARY_PREFERRED) { + const result = servers.filter(primaryFilter); + if (result.length) { + return result; + } } - - /** - * 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 })); + const filter = mode === read_preference_1.ReadPreference.NEAREST ? nearestFilter : secondaryFilter; + const selectedServers = latencyWindowReducer(topologyDescription, tagSetReducer(readPreference, maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter)))); + if (mode === read_preference_1.ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) { + return servers.filter(primaryFilter); } - - /** - * Execute the explain for the cursor - * - * For backwards compatibility, a verbosity of true is interpreted as "allPlansExecution" - * and false as "queryPlanner". Prior to server version 3.6, aggregate() - * ignores the verbosity parameter and executes in "queryPlanner". - * - * @method - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [verbosity=true] - An optional mode in which to run the explain. - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - explain(verbosity, callback) { - if (typeof verbosity === "function") - (callback = verbosity), (verbosity = true); - if (verbosity === undefined) verbosity = true; - - if ( - !this.operation || - !this.operation.hasAspect(Aspect.EXPLAINABLE) - ) { - throw new MongoError("This command cannot be explained"); - } - this.operation.explain = new Explain(verbosity); - - return maybePromise(this, callback, (cb) => { - CoreCursor.prototype._next.apply(this, [cb]); - }); + return selectedServers; + }; +} +exports.readPreferenceServerSelector = readPreferenceServerSelector; +//# sourceMappingURL=server_selection.js.map + +/***/ }), + +/***/ 3819: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SrvPoller = exports.SrvPollingEvent = void 0; +const dns = __nccwpck_require__(881); +const logger_1 = __nccwpck_require__(8874); +const utils_1 = __nccwpck_require__(1371); +const mongo_types_1 = __nccwpck_require__(696); +const error_1 = __nccwpck_require__(9386); +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param srvAddress - The address to check against a domain + * @param parentDomain - The domain to check the provided address against + * @returns 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); +} +/** + * @internal + * @category Event + */ +class SrvPollingEvent { + constructor(srvRecords) { + this.srvRecords = srvRecords; + } + hostnames() { + return new Set(this.srvRecords.map(r => utils_1.HostAddress.fromSrvRecord(r).toString())); + } +} +exports.SrvPollingEvent = SrvPollingEvent; +/** @internal */ +class SrvPoller extends mongo_types_1.TypedEventEmitter { + constructor(options) { + var _a, _b, _c; + super(); + if (!options || !options.srvHost) { + throw new error_1.MongoRuntimeError('Options for SrvPoller must exist and include srvHost'); + } + this.srvHost = options.srvHost; + this.srvMaxHosts = (_a = options.srvMaxHosts) !== null && _a !== void 0 ? _a : 0; + this.srvServiceName = (_b = options.srvServiceName) !== null && _b !== void 0 ? _b : 'mongodb'; + this.rescanSrvIntervalMS = 60000; + this.heartbeatFrequencyMS = (_c = options.heartbeatFrequencyMS) !== null && _c !== void 0 ? _c : 10000; + this.logger = new logger_1.Logger('srvPoller', options); + this.haMode = false; + this.generation = 0; + this._timeout = undefined; + } + get srvAddress() { + return `_${this.srvServiceName}._tcp.${this.srvHost}`; + } + get intervalMS() { + return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS; + } + start() { + if (!this._timeout) { + this.schedule(); } - - /** - * 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, - __nccwpck_require__ - ) => { - "use strict"; - - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const inherits = __nccwpck_require__(1669).inherits; - const getSingleProperty = __nccwpck_require__(1371).getSingleProperty; - const CommandCursor = __nccwpck_require__(538); - const handleCallback = __nccwpck_require__(1371).handleCallback; - const filterOptions = __nccwpck_require__(1371).filterOptions; - const toError = __nccwpck_require__(1371).toError; - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const MongoError = __nccwpck_require__(3994).MongoError; - const ObjectID = __nccwpck_require__(3994).ObjectID; - const Logger = __nccwpck_require__(3994).Logger; - const Collection = __nccwpck_require__(5193); - const conditionallyMergeWriteConcern = - __nccwpck_require__(1371).conditionallyMergeWriteConcern; - const executeLegacyOperation = - __nccwpck_require__(1371).executeLegacyOperation; - const ChangeStream = __nccwpck_require__(1117); - const deprecate = __nccwpck_require__(1669).deprecate; - const deprecateOptions = __nccwpck_require__(1371).deprecateOptions; - const MongoDBNamespace = __nccwpck_require__(1371).MongoDBNamespace; - const CONSTANTS = __nccwpck_require__(147); - const WriteConcern = __nccwpck_require__(2481); - const ReadConcern = __nccwpck_require__(7289); - const AggregationCursor = __nccwpck_require__(7429); - - // Operations - const createListener = __nccwpck_require__(2226).createListener; - const ensureIndex = __nccwpck_require__(2226).ensureIndex; - const evaluate = __nccwpck_require__(2226).evaluate; - const profilingInfo = __nccwpck_require__(2226).profilingInfo; - const validateDatabaseName = - __nccwpck_require__(2226).validateDatabaseName; - - const AggregateOperation = __nccwpck_require__(1554); - const AddUserOperation = __nccwpck_require__(7057); - const CollectionsOperation = __nccwpck_require__(286); - const CommandOperation = __nccwpck_require__(499); - const RunCommandOperation = __nccwpck_require__(1363); - const CreateCollectionOperation = __nccwpck_require__(5561); - const CreateIndexesOperation = __nccwpck_require__(6394); - const DropCollectionOperation = - __nccwpck_require__(2360).DropCollectionOperation; - const DropDatabaseOperation = - __nccwpck_require__(2360).DropDatabaseOperation; - const ExecuteDbAdminCommandOperation = __nccwpck_require__(1681); - const IndexInformationOperation = __nccwpck_require__(4245); - const ListCollectionsOperation = __nccwpck_require__(840); - const ProfilingLevelOperation = __nccwpck_require__(3969); - const RemoveUserOperation = __nccwpck_require__(1969); - const RenameOperation = __nccwpck_require__(2808); - const SetProfilingLevelOperation = __nccwpck_require__(6301); - - const executeOperation = __nccwpck_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", - "writeConcern", - "readPreference", - "readPreferenceTags", - "native_parser", - "forceServerObjectId", - "pkFactory", - "serializeFunctions", - "raw", - "bufferMaxEntries", - "authSource", - "ignoreUndefined", - "promiseLibrary", - "readConcern", - "retryMiliSeconds", - "numberOfRetries", - "parentDb", - "noListener", - "loggerLevel", - "logger", - "promoteBuffers", - "promoteLongs", - "promoteValues", - "bsonRegExp", - "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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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 {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @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 + } + stop() { + if (this._timeout) { + clearTimeout(this._timeout); + this.generation += 1; + this._timeout = undefined; + } + } + schedule() { + if (this._timeout) { + clearTimeout(this._timeout); + } + this._timeout = setTimeout(() => this._poll(), this.intervalMS); + } + success(srvRecords) { + this.haMode = false; + this.schedule(); + this.emit(SrvPoller.SRV_RECORD_DISCOVERY, 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 = []; + for (const record of srvRecords) { + 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); + }); + } +} +exports.SrvPoller = SrvPoller; +/** @event */ +SrvPoller.SRV_RECORD_DISCOVERY = 'srvRecordDiscovery'; +//# sourceMappingURL=srv_polling.js.map + +/***/ }), + +/***/ 8827: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ServerCapabilities = exports.TOPOLOGY_EVENTS = exports.Topology = void 0; +const Denque = __nccwpck_require__(2342); +const read_preference_1 = __nccwpck_require__(9802); +const server_description_1 = __nccwpck_require__(9753); +const topology_description_1 = __nccwpck_require__(5645); +const server_1 = __nccwpck_require__(165); +const sessions_1 = __nccwpck_require__(5259); +const srv_polling_1 = __nccwpck_require__(3819); +const connection_pool_1 = __nccwpck_require__(2529); +const error_1 = __nccwpck_require__(9386); +const server_selection_1 = __nccwpck_require__(2081); +const utils_1 = __nccwpck_require__(1371); +const common_1 = __nccwpck_require__(472); +const events_1 = __nccwpck_require__(2464); +const connection_1 = __nccwpck_require__(9820); +const connection_string_1 = __nccwpck_require__(5341); +const bson_1 = __nccwpck_require__(5578); +const mongo_types_1 = __nccwpck_require__(696); +// Global state +let globalTopologyCounter = 0; +// events that we relay to the `Topology` +const SERVER_RELAY_EVENTS = [ + server_1.Server.SERVER_HEARTBEAT_STARTED, + server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, + server_1.Server.SERVER_HEARTBEAT_FAILED, + connection_1.Connection.COMMAND_STARTED, + connection_1.Connection.COMMAND_SUCCEEDED, + connection_1.Connection.COMMAND_FAILED, + ...connection_pool_1.CMAP_EVENTS +]; +// all events we listen to from `Server` instances +const LOCAL_SERVER_EVENTS = [ + server_1.Server.CONNECT, + server_1.Server.DESCRIPTION_RECEIVED, + server_1.Server.CLOSED, + server_1.Server.ENDED +]; +const stateTransition = (0, utils_1.makeStateMachine)({ + [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, common_1.STATE_CONNECTING], + [common_1.STATE_CONNECTING]: [common_1.STATE_CONNECTING, common_1.STATE_CLOSING, common_1.STATE_CONNECTED, common_1.STATE_CLOSED], + [common_1.STATE_CONNECTED]: [common_1.STATE_CONNECTED, common_1.STATE_CLOSING, common_1.STATE_CLOSED], + [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, common_1.STATE_CLOSED] +}); +/** @internal */ +const kCancelled = Symbol('cancelled'); +/** @internal */ +const kWaitQueue = Symbol('waitQueue'); +/** + * A container of server instances representing a connection to a MongoDB topology. + * @internal + */ +class Topology extends mongo_types_1.TypedEventEmitter { + /** + * @param seedlist - a list of HostAddress instances to connect to + */ + constructor(seeds, options) { + var _a; + super(); + // Legacy CSFLE support + this.bson = Object.create(null); + this.bson.serialize = bson_1.serialize; + this.bson.deserialize = bson_1.deserialize; + // Options should only be undefined in tests, MongoClient will always have defined options + options = options !== null && options !== void 0 ? options : { + hosts: [utils_1.HostAddress.fromString('localhost:27017')], + retryReads: connection_string_1.DEFAULT_OPTIONS.get('retryReads'), + retryWrites: connection_string_1.DEFAULT_OPTIONS.get('retryWrites'), + serverSelectionTimeoutMS: connection_string_1.DEFAULT_OPTIONS.get('serverSelectionTimeoutMS'), + directConnection: connection_string_1.DEFAULT_OPTIONS.get('directConnection'), + loadBalanced: connection_string_1.DEFAULT_OPTIONS.get('loadBalanced'), + metadata: connection_string_1.DEFAULT_OPTIONS.get('metadata'), + monitorCommands: connection_string_1.DEFAULT_OPTIONS.get('monitorCommands'), + tls: connection_string_1.DEFAULT_OPTIONS.get('tls'), + maxPoolSize: connection_string_1.DEFAULT_OPTIONS.get('maxPoolSize'), + minPoolSize: connection_string_1.DEFAULT_OPTIONS.get('minPoolSize'), + waitQueueTimeoutMS: connection_string_1.DEFAULT_OPTIONS.get('waitQueueTimeoutMS'), + connectionType: connection_string_1.DEFAULT_OPTIONS.get('connectionType'), + connectTimeoutMS: connection_string_1.DEFAULT_OPTIONS.get('connectTimeoutMS'), + maxIdleTimeMS: connection_string_1.DEFAULT_OPTIONS.get('maxIdleTimeMS'), + heartbeatFrequencyMS: connection_string_1.DEFAULT_OPTIONS.get('heartbeatFrequencyMS'), + minHeartbeatFrequencyMS: connection_string_1.DEFAULT_OPTIONS.get('minHeartbeatFrequencyMS') + }; + if (typeof seeds === 'string') { + seeds = [utils_1.HostAddress.fromString(seeds)]; + } + else if (!Array.isArray(seeds)) { + seeds = [seeds]; + } + const seedlist = []; + for (const seed of seeds) { + if (typeof seed === 'string') { + seedlist.push(utils_1.HostAddress.fromString(seed)); + } + else if (seed instanceof utils_1.HostAddress) { + seedlist.push(seed); + } + else { + // FIXME(NODE-3483): May need to be a MongoParseError + throw new error_1.MongoRuntimeError(`Topology cannot be constructed from ${JSON.stringify(seed)}`); + } + } + const topologyType = topologyTypeFromOptions(options); + const topologyId = globalTopologyCounter++; + const selectedHosts = options.srvMaxHosts == null || + options.srvMaxHosts === 0 || + options.srvMaxHosts >= seedlist.length + ? seedlist + : (0, utils_1.shuffle)(seedlist, options.srvMaxHosts); + const serverDescriptions = new Map(); + for (const hostAddress of selectedHosts) { + serverDescriptions.set(hostAddress.toString(), new server_description_1.ServerDescription(hostAddress)); + } + this[kWaitQueue] = new Denque(); 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), + // the id of this topology + id: topologyId, + // passed in options + options, + // initial seedlist of servers to connect to + seedlist, + // initial state + state: common_1.STATE_CLOSED, + // the topology description + description: new topology_description_1.TopologyDescription(topologyType, serverDescriptions, options.replicaSet, undefined, undefined, undefined, options), + serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, + heartbeatFrequencyMS: options.heartbeatFrequencyMS, + minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS, + // a map of server instances to normalized addresses + servers: new Map(), + // Server Session Pool + sessionPool: new sessions_1.ServerSessionPool(this), + // Active client sessions + sessions: new Set(), + credentials: options === null || options === void 0 ? void 0 : options.credentials, + clusterTime: undefined, + // timer management + connectionTimers: new Set(), + detectShardedTopology: ev => this.detectShardedTopology(ev), + detectSrvRecords: ev => this.detectSrvRecords(ev) }; - - // 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); - - Db.prototype.on = deprecate(function () { - return Db.super_.prototype.on.apply(this, arguments); - }, "Listening to events on the Db class has been deprecated and will be removed in the next major version."); - - Db.prototype.once = deprecate(function () { - return Db.super_.prototype.once.apply(this, arguments); - }, "Listening to events on the Db class has been deprecated and will be removed in the next major version."); - - // 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: 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 {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output. - * @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 {boolean} [options.bsonRegExp=false] By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @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: remove this when NODE-2074 is resolved - if (typeof callback === "function") { - callback(null, cursor); - return; + if (options.srvHost && !options.loadBalanced) { + this.s.srvPoller = + (_a = options.srvPoller) !== null && _a !== void 0 ? _a : new srv_polling_1.SrvPoller({ + heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, + srvHost: options.srvHost, + srvMaxHosts: options.srvMaxHosts, + srvServiceName: options.srvServiceName + }); + this.on(Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); } - - return cursor; - }; - - /** - * Return the Admin db instance - * @method - * @return {Admin} return the new Admin db instance - */ - Db.prototype.admin = function () { - const Admin = __nccwpck_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 COLLECTION_OPTION_KEYS = [ - "pkFactory", - "readPreference", - "serializeFunctions", - "strict", - "readConcern", - "ignoreUndefined", - "promoteValues", - "promoteBuffers", - "promoteLongs", - "bsonRegExp", - ]; - - /** - * 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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 {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 = deprecateOptions( - { - name: "Db.collection", - deprecatedOptions: ["strict"], - optionsIndex: 1, - }, - function (name, options, callback) { - if (typeof options === "function") + } + detectShardedTopology(event) { + var _a, _b, _c; + const previousType = event.previousDescription.type; + const newType = event.newDescription.type; + const transitionToSharded = previousType !== common_1.TopologyType.Sharded && newType === common_1.TopologyType.Sharded; + const srvListeners = (_a = this.s.srvPoller) === null || _a === void 0 ? void 0 : _a.listeners(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY); + const listeningToSrvPolling = !!(srvListeners === null || srvListeners === void 0 ? void 0 : srvListeners.includes(this.s.detectSrvRecords)); + if (transitionToSharded && !listeningToSrvPolling) { + (_b = this.s.srvPoller) === null || _b === void 0 ? void 0 : _b.on(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + (_c = this.s.srvPoller) === null || _c === void 0 ? void 0 : _c.start(); + } + } + detectSrvRecords(ev) { + const previousTopologyDescription = this.s.description; + this.s.description = this.s.description.updateFromSrvPollingEvent(ev, this.s.options.srvMaxHosts); + if (this.s.description === previousTopologyDescription) { + // Nothing changed, so return + return; + } + updateServers(this); + this.emit(Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, previousTopologyDescription, this.s.description)); + } + /** + * @returns A `TopologyDescription` for this topology + */ + get description() { + return this.s.description; + } + get loadBalanced() { + return this.s.options.loadBalanced; + } + get capabilities() { + return new ServerCapabilities(this.lastIsMaster()); + } + /** Initiate server connect */ + connect(options, callback) { + var _a; + 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; - } - - for (const collectionOptionKey of COLLECTION_OPTION_KEYS) { - if ( - !(collectionOptionKey in options) && - this.s.options[collectionOptionKey] !== undefined - ) { - options[collectionOptionKey] = - this.s.options[collectionOptionKey]; + options = options !== null && options !== void 0 ? options : {}; + if (this.s.state === common_1.STATE_CONNECTED) { + if (typeof callback === 'function') { + callback(); } - } - - // Merge in all needed options and ensure correct writeConcern merging from db level - options = conditionallyMergeWriteConcern(options, this.s.options); - - // 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; + return; + } + stateTransition(this, common_1.STATE_CONNECTING); + // emit SDAM monitoring events + this.emit(Topology.TOPOLOGY_OPENING, new events_1.TopologyOpeningEvent(this.s.id)); + // emit an event for the topology change + this.emit(Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, new topology_description_1.TopologyDescription(common_1.TopologyType.Unknown), // initial is always Unknown + this.s.description)); + // connect all known servers, then attempt server selection to connect + const serverDescriptions = Array.from(this.s.description.servers.values()); + connectServers(this, serverDescriptions); + // In load balancer mode we need to fake a server description getting + // emitted from the monitor, since the monitor doesn't exist. + if (this.s.options.loadBalanced) { + for (const description of serverDescriptions) { + const newDescription = new server_description_1.ServerDescription(description.hostAddress, undefined, { + loadBalanced: this.s.options.loadBalanced + }); + this.serverUpdateHandler(newDescription); } - } - - // 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); - } + } + const readPreference = (_a = options.readPreference) !== null && _a !== void 0 ? _a : read_preference_1.ReadPreference.primary; + this.selectServer((0, server_selection_1.readPreferenceServerSelector)(readPreference), options, (err, server) => { + if (err) { + this.close(); + typeof callback === 'function' ? callback(err) : this.emit(Topology.ERROR, err); + return; + } + // TODO: NODE-2471 + if (server && this.s.credentials) { + server.command((0, utils_1.ns)('admin.$cmd'), { ping: 1 }, err => { + if (err) { + typeof callback === 'function' ? callback(err) : this.emit(Topology.ERROR, err); + return; + } + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Topology.OPEN, this); + this.emit(Topology.CONNECT, this); + if (typeof callback === 'function') + callback(undefined, this); + }); + return; + } + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Topology.OPEN, this); + this.emit(Topology.CONNECT, this); + if (typeof callback === 'function') + callback(undefined, this); + }); + } + /** Close this topology */ + close(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + if (typeof options === 'boolean') { + options = { force: options }; + } + options = options !== null && options !== void 0 ? options : {}; + if (this.s.state === common_1.STATE_CLOSED || this.s.state === common_1.STATE_CLOSING) { + if (typeof callback === 'function') { + callback(); + } + return; + } + stateTransition(this, common_1.STATE_CLOSING); + drainWaitQueue(this[kWaitQueue], new error_1.MongoTopologyClosedError()); + (0, common_1.drainTimerQueue)(this.s.connectionTimers); + if (this.s.srvPoller) { + this.s.srvPoller.stop(); + this.s.srvPoller.removeListener(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + } + this.removeListener(Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology); + (0, utils_1.eachAsync)(Array.from(this.s.sessions.values()), (session, cb) => session.endSession(cb), () => { + this.s.sessionPool.endAllPooledSessions(() => { + (0, utils_1.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(Topology.TOPOLOGY_CLOSED, new events_1.TopologyClosedEvent(this.s.id)); + stateTransition(this, common_1.STATE_CLOSED); + if (typeof callback === 'function') { + callback(err); + } + }); + }); + }); + } + selectServer(selector, _options, _callback) { + let options = _options; + const callback = (_callback !== null && _callback !== void 0 ? _callback : _options); + if (typeof options === 'function') { + options = {}; + } + let serverSelector; + if (typeof selector !== 'function') { + if (typeof selector === 'string') { + serverSelector = (0, server_selection_1.readPreferenceServerSelector)(read_preference_1.ReadPreference.fromString(selector)); + } + else { + let readPreference; + if (selector instanceof read_preference_1.ReadPreference) { + readPreference = selector; + } + else { + read_preference_1.ReadPreference.translate(options); + readPreference = options.readPreference || read_preference_1.ReadPreference.primary; + } + serverSelector = (0, server_selection_1.readPreferenceServerSelector)(readPreference); } - ); } - ); - - /** - * 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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", "w", "wtimeout", "j"], - 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, + else { + serverSelector = selector; + } + options = Object.assign({}, { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, options); + const isSharded = this.description.type === common_1.TopologyType.Sharded; + const session = options.session; + const transaction = session && session.transaction; + if (isSharded && transaction && transaction.server) { + callback(undefined, transaction.server); + return; + } + const waitQueueMember = { + serverSelector, + transaction, callback - ); + }; + const serverSelectionTimeoutMS = options.serverSelectionTimeoutMS; + if (serverSelectionTimeoutMS) { + waitQueueMember.timer = setTimeout(() => { + waitQueueMember[kCancelled] = true; + waitQueueMember.timer = undefined; + const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description); + waitQueueMember.callback(timeoutError); + }, serverSelectionTimeoutMS); } - ); - - /** - * 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; + this[kWaitQueue].push(waitQueueMember); + processWaitQueue(this); + } + // Sessions related methods + /** + * @returns Whether the topology should initiate selection to determine session support + */ + shouldCheckForSessionSupport() { + if (this.description.type === common_1.TopologyType.Single) { + return !this.description.hasKnownServers; } - - 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, + return !this.description.hasDataBearingServers; + } + /** + * @returns Whether sessions are supported on the current topology + */ + hasSessionSupport() { + return this.loadBalanced || this.description.logicalSessionTimeoutMinutes != null; + } + /** Start a logical session */ + startSession(options, clientOptions) { + const session = new sessions_1.ClientSession(this, this.s.sessionPool, options, clientOptions); + session.once('ended', () => { + this.s.sessions.delete(session); }); - - // 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 {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern 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.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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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; + this.s.sessions.add(session); + return session; + } + /** Send endSessions command(s) with the given session ids */ + endSessions(sessions, callback) { + if (!Array.isArray(sessions)) { + sessions = [sessions]; } - - 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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern 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.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 = []; + this.selectServer((0, server_selection_1.readPreferenceServerSelector)(read_preference_1.ReadPreference.primaryPreferred), (err, server) => { + if (err || !server) { + if (typeof callback === 'function') + callback(err); + return; + } + server.command((0, utils_1.ns)('admin.$cmd'), { endSessions: sessions }, { noResponse: true }, (err, result) => { + if (typeof callback === 'function') + callback(err, result); + }); + }); + } + /** + * Update the internal TopologyDescription with a ServerDescription + * + * @param 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); + if (!previousServerDescription) { + return; + } + // 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) { + (0, common_1._advanceClusterTime)(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(Topology.ERROR, new error_1.MongoCompatibilityError(this.s.description.compatibilityError)); + return; + } + // emit monitoring events for this change + if (!equalDescriptions) { + const newDescription = this.s.description.servers.get(serverDescription.address); + if (newDescription) { + this.emit(Topology.SERVER_DESCRIPTION_CHANGED, new events_1.ServerDescriptionChangedEvent(this.s.id, serverDescription.address, previousServerDescription, newDescription)); + } + } + // 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(Topology.TOPOLOGY_DESCRIPTION_CHANGED, new events_1.TopologyDescriptionChangedEvent(this.s.id, previousTopologyDescription, this.s.description)); + } + } + auth(credentials, callback) { + if (typeof credentials === 'function') + (callback = credentials), (credentials = undefined); + if (typeof callback === 'function') + callback(undefined, true); + } + get clientMetadata() { + return this.s.options.metadata; + } + isConnected() { + return this.s.state === common_1.STATE_CONNECTED; + } + isDestroyed() { + return this.s.state === common_1.STATE_CLOSED; + } + /** + * @deprecated This function is deprecated and will be removed in the next major version. + */ + unref() { + (0, utils_1.emitWarning)('`unref` is a noop and will be removed in the next major version'); + } + // 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 !== common_1.ServerType.Unknown)[0]; + const result = sd || { maxWireVersion: this.description.commonWireVersion }; + return result; + } + get commonWireVersion() { + return this.description.commonWireVersion; + } + get logicalSessionTimeoutMinutes() { + return this.description.logicalSessionTimeoutMinutes; + } + get clusterTime() { + return this.s.clusterTime; + } + set clusterTime(clusterTime) { + this.s.clusterTime = clusterTime; + } +} +exports.Topology = Topology; +/** @event */ +Topology.SERVER_OPENING = 'serverOpening'; +/** @event */ +Topology.SERVER_CLOSED = 'serverClosed'; +/** @event */ +Topology.SERVER_DESCRIPTION_CHANGED = 'serverDescriptionChanged'; +/** @event */ +Topology.TOPOLOGY_OPENING = 'topologyOpening'; +/** @event */ +Topology.TOPOLOGY_CLOSED = 'topologyClosed'; +/** @event */ +Topology.TOPOLOGY_DESCRIPTION_CHANGED = 'topologyDescriptionChanged'; +/** @event */ +Topology.ERROR = 'error'; +/** @event */ +Topology.OPEN = 'open'; +/** @event */ +Topology.CONNECT = 'connect'; +/** @event */ +Topology.CLOSE = 'close'; +/** @event */ +Topology.TIMEOUT = 'timeout'; +/** @public */ +exports.TOPOLOGY_EVENTS = [ + Topology.SERVER_OPENING, + Topology.SERVER_CLOSED, + Topology.SERVER_DESCRIPTION_CHANGED, + Topology.TOPOLOGY_OPENING, + Topology.TOPOLOGY_CLOSED, + Topology.TOPOLOGY_DESCRIPTION_CHANGED, + Topology.ERROR, + Topology.TIMEOUT, + Topology.CLOSE +]; +/** Destroys a server, and removes all event listeners from the instance */ +function destroyServer(server, topology, options, callback) { + options = options !== null && options !== void 0 ? options : {}; + for (const event of LOCAL_SERVER_EVENTS) { + server.removeAllListeners(event); + } + server.destroy(options, () => { + topology.emit(Topology.SERVER_CLOSED, new events_1.ServerClosedEvent(topology.s.id, server.description.address)); + for (const event of SERVER_RELAY_EVENTS) { + server.removeAllListeners(event); + } + if (typeof callback === 'function') { + callback(); + } + }); +} +/** Predicts the TopologyType from options */ +function topologyTypeFromOptions(options) { + if (options === null || options === void 0 ? void 0 : options.directConnection) { + return common_1.TopologyType.Single; + } + if (options === null || options === void 0 ? void 0 : options.replicaSet) { + return common_1.TopologyType.ReplicaSetNoPrimary; + } + if (options === null || options === void 0 ? void 0 : options.loadBalanced) { + return common_1.TopologyType.LoadBalanced; + } + return common_1.TopologyType.Unknown; +} +function randomSelection(array) { + return array[Math.floor(Math.random() * array.length)]; +} +/** + * Creates new server instances and attempts to connect them + * + * @param topology - The topology that this server belongs to + * @param serverDescription - The description for the server to initialize and connect to + * @param connectDelay - Time to wait before attempting initial connection + */ +function createAndConnectServer(topology, serverDescription, connectDelay) { + topology.emit(Topology.SERVER_OPENING, new events_1.ServerOpeningEvent(topology.s.id, serverDescription.address)); + const server = new server_1.Server(topology, serverDescription, topology.s.options); + for (const event of SERVER_RELAY_EVENTS) { + server.on(event, (e) => topology.emit(event, e)); + } + server.on(server_1.Server.DESCRIPTION_RECEIVED, description => topology.serverUpdateHandler(description)); + if (connectDelay) { + const connectTimer = setTimeout(() => { + (0, common_1.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 - The topology responsible for the servers + * @param 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()); +} +/** + * @param topology - Topology to update. + * @param incomingServerDescription - New server description. + */ +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); + if (server) { + 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; + } + if (!topology.s.servers.has(serverAddress)) { + continue; + } + const server = topology.s.servers.get(serverAddress); + topology.s.servers.delete(serverAddress); + // prepare server for garbage collection + if (server) { + destroyServer(server, topology); + } + } +} +function drainWaitQueue(queue, err) { + while (queue.length) { + const waitQueueMember = queue.shift(); + if (!waitQueueMember) { + continue; + } + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + if (!waitQueueMember[kCancelled]) { + waitQueueMember.callback(err); + } + } +} +function processWaitQueue(topology) { + if (topology.s.state === common_1.STATE_CLOSED) { + drainWaitQueue(topology[kWaitQueue], new error_1.MongoTopologyClosedError()); + return; + } + const isSharded = topology.description.type === common_1.TopologyType.Sharded; + const serverDescriptions = Array.from(topology.description.servers.values()); + const membersToProcess = topology[kWaitQueue].length; + for (let i = 0; i < membersToProcess; ++i) { + const waitQueueMember = topology[kWaitQueue].shift(); + if (!waitQueueMember) { + continue; + } + if (waitQueueMember[kCancelled]) { + continue; + } + let selectedDescriptions; + try { + const serverSelector = waitQueueMember.serverSelector; + selectedDescriptions = serverSelector + ? serverSelector(topology.description, serverDescriptions) + : serverDescriptions; + } + catch (e) { + if (waitQueueMember.timer) { + 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; + if (isSharded && transaction && transaction.isActive && selectedServer) { + transaction.pinServer(selectedServer); + } + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + waitQueueMember.callback(undefined, selectedServer); + } + if (topology[kWaitQueue].length > 0) { + // ensure all server monitors attempt monitoring soon + for (const [, server] of topology.s.servers) { + process.nextTick(function scheduleServerCheck() { + return server.requestCheck(); + }); + } + } +} +function isStaleServerDescription(topologyDescription, incomingServerDescription) { + const currentServerDescription = topologyDescription.servers.get(incomingServerDescription.address); + const currentTopologyVersion = currentServerDescription === null || currentServerDescription === void 0 ? void 0 : currentServerDescription.topologyVersion; + return ((0, server_description_1.compareTopologyVersion)(currentTopologyVersion, incomingServerDescription.topologyVersion) > 0); +} +/** @public */ +class ServerCapabilities { + constructor(ismaster) { + this.minWireVersion = ismaster.minWireVersion || 0; + this.maxWireVersion = ismaster.maxWireVersion || 0; + } + get hasAggregationCursor() { + return this.maxWireVersion >= 1; + } + get hasWriteCommands() { + return this.maxWireVersion >= 2; + } + get hasTextSearch() { + return this.minWireVersion >= 0; + } + get hasAuthCommands() { + return this.maxWireVersion >= 1; + } + get hasListCollectionsCommand() { + return this.maxWireVersion >= 3; + } + get hasListIndexesCommand() { + return this.maxWireVersion >= 3; + } + get supportsSnapshotReads() { + return this.maxWireVersion >= 13; + } + get commandsTakeWriteConcern() { + return this.maxWireVersion >= 5; + } + get commandsTakeCollation() { + return this.maxWireVersion >= 5; + } +} +exports.ServerCapabilities = ServerCapabilities; +//# sourceMappingURL=topology.js.map + +/***/ }), + +/***/ 5645: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TopologyDescription = void 0; +const server_description_1 = __nccwpck_require__(9753); +const WIRE_CONSTANTS = __nccwpck_require__(6042); +const common_1 = __nccwpck_require__(472); +const error_1 = __nccwpck_require__(9386); +const utils_1 = __nccwpck_require__(1371); +// constants related to compatibility 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; +const MONGOS_OR_UNKNOWN = new Set([common_1.ServerType.Mongos, common_1.ServerType.Unknown]); +const MONGOS_OR_STANDALONE = new Set([common_1.ServerType.Mongos, common_1.ServerType.Standalone]); +const NON_PRIMARY_RS_MEMBERS = new Set([ + common_1.ServerType.RSSecondary, + common_1.ServerType.RSArbiter, + common_1.ServerType.RSOther +]); +/** + * Representation of a deployment of servers + * @public + */ +class TopologyDescription { + /** + * Create a TopologyDescription + */ + constructor(topologyType, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, options) { + var _a, _b; + options = options !== null && options !== void 0 ? options : {}; + // TODO: 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 !== null && topologyType !== void 0 ? topologyType : common_1.TopologyType.Unknown; + this.servers = serverDescriptions !== null && serverDescriptions !== void 0 ? serverDescriptions : new Map(); + this.stale = false; + this.compatible = true; + this.heartbeatFrequencyMS = (_a = options.heartbeatFrequencyMS) !== null && _a !== void 0 ? _a : 0; + this.localThresholdMS = (_b = options.localThresholdMS) !== null && _b !== void 0 ? _b : 0; + if (setName) { + this.setName = setName; + } + if (maxSetVersion) { + this.maxSetVersion = maxSetVersion; + } + if (maxElectionId) { + this.maxElectionId = maxElectionId; + } + if (commonWireVersion) { + this.commonWireVersion = commonWireVersion; + } + // determine server compatibility + for (const serverDescription of this.servers.values()) { + // Load balancer mode is always compatible. + if (serverDescription.type === common_1.ServerType.Unknown || + serverDescription.type === common_1.ServerType.LoadBalancer) { + 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; + } } - - 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, - __nccwpck_require__ - ) => { - "use strict"; - - let collection; - let cursor; - let db; - - function loadCollection() { - if (!collection) { - collection = __nccwpck_require__(5193); + // 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. + this.logicalSessionTimeoutMinutes = undefined; + for (const [, server] of this.servers) { + if (server.isReadable) { + if (server.logicalSessionTimeoutMinutes == null) { + // If any of the servers have a null logicalSessionsTimeout, then the whole topology does + this.logicalSessionTimeoutMinutes = undefined; + break; + } + if (this.logicalSessionTimeoutMinutes == null) { + // First server with a non null logicalSessionsTimeout + this.logicalSessionTimeoutMinutes = server.logicalSessionTimeoutMinutes; + continue; + } + // Always select the smaller of the: + // current server logicalSessionsTimeout and the topologies logicalSessionsTimeout + this.logicalSessionTimeoutMinutes = Math.min(this.logicalSessionTimeoutMinutes, server.logicalSessionTimeoutMinutes); + } } - return collection; - } - - function loadCursor() { - if (!cursor) { - cursor = __nccwpck_require__(7159); + } + /** + * Returns a new TopologyDescription based on the SrvPollingEvent + * @internal + */ + updateFromSrvPollingEvent(ev, srvMaxHosts = 0) { + /** The SRV addresses defines the set of addresses we should be using */ + const incomingHostnames = ev.hostnames(); + const currentHostnames = new Set(this.servers.keys()); + const hostnamesToAdd = new Set(incomingHostnames); + const hostnamesToRemove = new Set(); + for (const hostname of currentHostnames) { + // filter hostnamesToAdd (made from incomingHostnames) down to what is *not* present in currentHostnames + hostnamesToAdd.delete(hostname); + if (!incomingHostnames.has(hostname)) { + // If the SRV Records no longer include this hostname + // we have to stop using it + hostnamesToRemove.add(hostname); + } + } + if (hostnamesToAdd.size === 0 && hostnamesToRemove.size === 0) { + // No new hosts to add and none to remove + return this; } - return cursor; - } - - function loadDb() { - if (!db) { - db = __nccwpck_require__(6662); + const serverDescriptions = new Map(this.servers); + for (const removedHost of hostnamesToRemove) { + serverDescriptions.delete(removedHost); } - return db; - } - - module.exports = { - loadCollection, - loadCursor, - loadDb, - }; - - /***/ - }, - - /***/ 3012: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const MongoClient = __nccwpck_require__(1545); - const BSON = __nccwpck_require__(7746).retrieveBSON(); - const MongoError = __nccwpck_require__(3111).MongoError; - - let mongodbClientEncryption = undefined; - try { - // Ensure you always wrap an optional require in the try block NODE-3199 - mongodbClientEncryption = __nccwpck_require__(5764); - } catch (err) { - throw new MongoError( - "Auto-encryption requested, but the module is not installed. " + - "Please add `mongodb-client-encryption` as a dependency of your project" - ); - } - - if ( - mongodbClientEncryption === undefined || - typeof mongodbClientEncryption.extension !== "function" - ) { - throw 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`" - ); - } - - const AutoEncrypter = mongodbClientEncryption.extension( - __nccwpck_require__(5517) - ).AutoEncrypter; - - const kInternalClient = Symbol("internalClient"); - - class Encrypter { - /** - * @param {MongoClient} client - * @param {{autoEncryption: import('./mongo_client').AutoEncryptionOptions, bson: object}} options - */ - constructor(client, options) { - this.bypassAutoEncryption = - !!options.autoEncryption.bypassAutoEncryption; - this.needsConnecting = false; - - if ( - options.maxPoolSize === 0 && - options.autoEncryption.keyVaultClient == null - ) { - options.autoEncryption.keyVaultClient = client; - } else if (options.autoEncryption.keyVaultClient == null) { - options.autoEncryption.keyVaultClient = - this.getInternalClient(client); - } - - if (this.bypassAutoEncryption) { - options.autoEncryption.metadataClient = undefined; - } else if (options.maxPoolSize === 0) { - options.autoEncryption.metadataClient = client; - } else { - options.autoEncryption.metadataClient = - this.getInternalClient(client); - } - - options.autoEncryption.bson = Encrypter.makeBSON(options); - - this.autoEncrypter = new AutoEncrypter( - client, - options.autoEncryption - ); + if (hostnamesToAdd.size > 0) { + if (srvMaxHosts === 0) { + // Add all! + for (const hostToAdd of hostnamesToAdd) { + serverDescriptions.set(hostToAdd, new server_description_1.ServerDescription(hostToAdd)); + } + } + else if (serverDescriptions.size < srvMaxHosts) { + // Add only the amount needed to get us back to srvMaxHosts + const selectedHosts = (0, utils_1.shuffle)(hostnamesToAdd, srvMaxHosts - serverDescriptions.size); + for (const selectedHostToAdd of selectedHosts) { + serverDescriptions.set(selectedHostToAdd, new server_description_1.ServerDescription(selectedHostToAdd)); + } + } } - - getInternalClient(client) { - if (!this[kInternalClient]) { - const clonedOptions = {}; - - for (const key of Object.keys(client.s.options)) { - if ( - [ - "autoEncryption", - "minPoolSize", - "servers", - "caseTranslate", - "dbName", - ].indexOf(key) !== -1 - ) - continue; - clonedOptions[key] = client.s.options[key]; + return new TopologyDescription(this.type, serverDescriptions, this.setName, this.maxSetVersion, this.maxElectionId, this.commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }); + } + /** + * Returns a copy of this description updated with a given ServerDescription + * @internal + */ + update(serverDescription) { + const address = serverDescription.address; + // potentially mutated values + let { type: topologyType, setName, maxSetVersion, maxElectionId, commonWireVersion } = this; + if (serverDescription.setName && setName && serverDescription.setName !== setName) { + serverDescription = new server_description_1.ServerDescription(address, undefined); + } + const serverType = serverDescription.type; + const serverDescriptions = new Map(this.servers); + // update common wire version + if (serverDescription.maxWireVersion !== 0) { + if (commonWireVersion == null) { + commonWireVersion = serverDescription.maxWireVersion; } - - clonedOptions.minPoolSize = 0; - - const allEvents = [ - // APM - "commandStarted", - "commandSucceeded", - "commandFailed", - - // SDAM - "serverOpening", - "serverClosed", - "serverDescriptionChanged", - "serverHeartbeatStarted", - "serverHeartbeatSucceeded", - "serverHeartbeatFailed", - "topologyOpening", - "topologyClosed", - "topologyDescriptionChanged", - - // Legacy - "joined", - "left", - "ping", - "ha", - - // CMAP - "connectionPoolCreated", - "connectionPoolClosed", - "connectionCreated", - "connectionReady", - "connectionClosed", - "connectionCheckOutStarted", - "connectionCheckOutFailed", - "connectionCheckedOut", - "connectionCheckedIn", - "connectionPoolCleared", - ]; - - this[kInternalClient] = new MongoClient( - client.s.url, - clonedOptions - ); - - for (const eventName of allEvents) { - for (const listener of client.listeners(eventName)) { - this[kInternalClient].on(eventName, listener); - } + else { + commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); } - - client.on("newListener", (eventName, listener) => { - this[kInternalClient].on(eventName, listener); - }); - - this.needsConnecting = true; - } - return this[kInternalClient]; } - - connectInternalClient(callback) { - if (this.needsConnecting) { - this.needsConnecting = false; - return this[kInternalClient].connect(callback); - } - - return callback(); + // update the actual server description + serverDescriptions.set(address, serverDescription); + if (topologyType === common_1.TopologyType.Single) { + // once we are defined as single, that never changes + return new TopologyDescription(common_1.TopologyType.Single, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }); } - - close(client, force, callback) { - this.autoEncrypter.teardown((e) => { - if (this[kInternalClient] && client !== this[kInternalClient]) { - return this[kInternalClient].close(force, callback); + if (topologyType === common_1.TopologyType.Unknown) { + if (serverType === common_1.ServerType.Standalone && this.servers.size !== 1) { + serverDescriptions.delete(address); + } + else { + topologyType = topologyTypeForServerType(serverType); } - callback(e); - }); } - - static makeBSON(options) { - return ( - (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, - ]) - ); + if (topologyType === common_1.TopologyType.Sharded) { + if (!MONGOS_OR_UNKNOWN.has(serverType)) { + serverDescriptions.delete(address); + } } - } - - module.exports = { Encrypter }; - - /***/ - }, - - /***/ 9386: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const MongoNetworkError = __nccwpck_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"); + if (topologyType === common_1.TopologyType.ReplicaSetNoPrimary) { + if (MONGOS_OR_STANDALONE.has(serverType)) { + serverDescriptions.delete(address); + } + if (serverType === common_1.ServerType.RSPrimary) { + const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId); + topologyType = result[0]; + setName = result[1]; + maxSetVersion = result[2]; + maxElectionId = result[3]; + } + else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { + const result = updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName); + topologyType = result[0]; + setName = result[1]; + } } - - return GET_MORE_RESUMABLE_CODES.has(error.code); - } - - module.exports = { GET_MORE_RESUMABLE_CODES, isResumableError }; - - /***/ - }, - - /***/ 5293: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const MongoError = __nccwpck_require__(3111).MongoError; - - const ExplainVerbosity = { - queryPlanner: "queryPlanner", - queryPlannerExtended: "queryPlannerExtended", - executionStats: "executionStats", - allPlansExecution: "allPlansExecution", - }; - - /** - * @class - * @property {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'} verbosity The verbosity mode for the explain output. - */ - class Explain { - /** - * Constructs an Explain from the explain verbosity. - * - * For backwards compatibility, true is interpreted as "allPlansExecution" - * and false as "queryPlanner". Prior to server version 3.6, aggregate() - * ignores the verbosity parameter and executes in "queryPlanner". - * - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [verbosity] The verbosity mode for the explain output. - */ - constructor(verbosity) { - if (typeof verbosity === "boolean") { - this.verbosity = verbosity ? "allPlansExecution" : "queryPlanner"; - } else { - this.verbosity = verbosity; - } + if (topologyType === common_1.TopologyType.ReplicaSetWithPrimary) { + if (MONGOS_OR_STANDALONE.has(serverType)) { + serverDescriptions.delete(address); + topologyType = checkHasPrimary(serverDescriptions); + } + else if (serverType === common_1.ServerType.RSPrimary) { + const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId); + topologyType = result[0]; + setName = result[1]; + maxSetVersion = result[2]; + maxElectionId = result[3]; + } + else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) { + topologyType = updateRsWithPrimaryFromMember(serverDescriptions, serverDescription, setName); + } + else { + topologyType = checkHasPrimary(serverDescriptions); + } } - - /** - * Construct an Explain given an options object. - * - * @param {object} [options] The options object from which to extract the explain. - * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output - * @return {Explain} - */ - static fromOptions(options) { - if (options == null || options.explain === undefined) { - return; - } - - const explain = options.explain; - if (typeof explain === "boolean" || explain in ExplainVerbosity) { - return new Explain(options.explain); - } - - throw new MongoError( - `explain must be one of ${Object.keys( - ExplainVerbosity - )} or a boolean` - ); + return new TopologyDescription(topologyType, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }); + } + get error() { + const descriptionsWithError = Array.from(this.servers.values()).filter((sd) => sd.error); + if (descriptionsWithError.length > 0) { + return descriptionsWithError[0].error; } - } - - module.exports = { Explain }; - - /***/ - }, - - /***/ 4190: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - var stream = __nccwpck_require__(2413), - util = __nccwpck_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; + } + /** + * Determines if the topology description has any known servers + */ + get hasKnownServers() { + return Array.from(this.servers.values()).some((sd) => sd.type !== common_1.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 + * @internal + */ + hasServer(address) { + return this.servers.has(address); + } +} +exports.TopologyDescription = TopologyDescription; +function topologyTypeForServerType(serverType) { + switch (serverType) { + case common_1.ServerType.Standalone: + return common_1.TopologyType.Single; + case common_1.ServerType.Mongos: + return common_1.TopologyType.Sharded; + case common_1.ServerType.RSPrimary: + return common_1.TopologyType.ReplicaSetWithPrimary; + case common_1.ServerType.RSOther: + case common_1.ServerType.RSSecondary: + return common_1.TopologyType.ReplicaSetNoPrimary; + default: + return common_1.TopologyType.Unknown; + } +} +// TODO: improve these docs when ObjectId is properly typed +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, serverDescription, setName, 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 server_description_1.ServerDescription(serverDescription.address)); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } } - - waitForFile(_this, function () { - doRead(_this); + 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, server] of serverDescriptions) { + if (server.type === common_1.ServerType.RSPrimary && server.address !== serverDescription.address) { + // Reset old primary's type to Unknown. + serverDescriptions.set(address, new server_description_1.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 server_description_1.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, serverDescription, setName) { + if (setName == null) { + // TODO(NODE-3483): should be an appropriate runtime error + throw new error_1.MongoRuntimeError('Argument "setName" is required if connected to a replica set'); + } + if (setName !== serverDescription.setName || + (serverDescription.me && serverDescription.address !== serverDescription.me)) { + serverDescriptions.delete(serverDescription.address); + } + return checkHasPrimary(serverDescriptions); +} +function updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName) { + const topologyType = common_1.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 server_description_1.ServerDescription(address)); + } + }); + if (serverDescription.me && serverDescription.address !== serverDescription.me) { + serverDescriptions.delete(serverDescription.address); + } + return [topologyType, setName]; +} +function checkHasPrimary(serverDescriptions) { + for (const serverDescription of serverDescriptions.values()) { + if (serverDescription.type === common_1.ServerType.RSPrimary) { + return common_1.TopologyType.ReplicaSetWithPrimary; + } + } + return common_1.TopologyType.ReplicaSetNoPrimary; +} +//# sourceMappingURL=topology_description.js.map + +/***/ }), + +/***/ 5259: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +var _a; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.updateSessionFromResponse = exports.applySession = exports.commandSupportsReadConcern = exports.ServerSessionPool = exports.ServerSession = exports.maybeClearPinnedConnection = exports.ClientSession = void 0; +const promise_provider_1 = __nccwpck_require__(2725); +const bson_1 = __nccwpck_require__(5578); +const read_preference_1 = __nccwpck_require__(9802); +const transactions_1 = __nccwpck_require__(8883); +const common_1 = __nccwpck_require__(472); +const shared_1 = __nccwpck_require__(1580); +const error_1 = __nccwpck_require__(9386); +const utils_1 = __nccwpck_require__(1371); +const execute_operation_1 = __nccwpck_require__(2548); +const run_command_1 = __nccwpck_require__(1363); +const connection_1 = __nccwpck_require__(9820); +const metrics_1 = __nccwpck_require__(2610); +const mongo_types_1 = __nccwpck_require__(696); +const read_concern_1 = __nccwpck_require__(7289); +const minWireVersionForShardedTransactions = 8; +function assertAlive(session, callback) { + if (session.serverSession == null) { + const error = new error_1.MongoExpiredSessionError(); + if (typeof callback === 'function') { + callback(error); + return false; + } + throw error; + } + return true; +} +/** @internal */ +const kServerSession = Symbol('serverSession'); +/** @internal */ +const kSnapshotTime = Symbol('snapshotTime'); +/** @internal */ +const kSnapshotEnabled = Symbol('snapshotEnabled'); +/** @internal */ +const kPinnedConnection = Symbol('pinnedConnection'); +/** + * A class representing a client session on the server + * + * NOTE: not meant to be instantiated directly. + * @public + */ +class ClientSession extends mongo_types_1.TypedEventEmitter { + /** + * Create a client session. + * @internal + * @param topology - The current client's topology (Internal Class) + * @param sessionPool - The server session pool (Internal Class) + * @param options - Optional settings + * @param clientOptions - Optional settings provided when creating a MongoClient + */ + constructor(topology, sessionPool, options, clientOptions) { + super(); + /** @internal */ + this[_a] = false; + if (topology == null) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('ClientSession requires a topology'); + } + if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('ClientSession requires a ServerSessionPool'); + } + options = options !== null && options !== void 0 ? options : {}; + if (options.snapshot === true) { + this[kSnapshotEnabled] = true; + if (options.causalConsistency === true) { + throw new error_1.MongoInvalidArgumentError('Properties "causalConsistency" and "snapshot" are mutually exclusive'); + } + } + this.topology = topology; + this.sessionPool = sessionPool; + this.hasEnded = false; + this.clientOptions = clientOptions; + this[kServerSession] = undefined; + this.supports = { + causalConsistency: options.snapshot !== true && options.causalConsistency !== false + }; + this.clusterTime = options.initialClusterTime; + this.operationTime = undefined; + this.explicit = !!options.explicit; + this.owner = options.owner; + this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); + this.transaction = new transactions_1.Transaction(); + } + /** The server id associated with this session */ + get id() { + var _b; + return (_b = this.serverSession) === null || _b === void 0 ? void 0 : _b.id; + } + get serverSession() { + if (this[kServerSession] == null) { + this[kServerSession] = this.sessionPool.acquire(); + } + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return this[kServerSession]; + } + /** Whether or not this session is configured for snapshot reads */ + get snapshotEnabled() { + return this[kSnapshotEnabled]; + } + get loadBalanced() { + return this.topology.description.type === common_1.TopologyType.LoadBalanced; + } + /** @internal */ + get pinnedConnection() { + return this[kPinnedConnection]; + } + /** @internal */ + pin(conn) { + if (this[kPinnedConnection]) { + throw TypeError('Cannot pin multiple connections to the same session'); + } + this[kPinnedConnection] = conn; + conn.emit(connection_1.Connection.PINNED, this.inTransaction() ? metrics_1.ConnectionPoolMetrics.TXN : metrics_1.ConnectionPoolMetrics.CURSOR); + } + /** @internal */ + unpin(options) { + if (this.loadBalanced) { + return maybeClearPinnedConnection(this, options); + } + this.transaction.unpinServer(); + } + get isPinned() { + return this.loadBalanced ? !!this[kPinnedConnection] : this.transaction.isPinned; + } + endSession(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + const finalOptions = { force: true, ...options }; + return (0, utils_1.maybePromise)(callback, done => { + if (this.hasEnded) { + maybeClearPinnedConnection(this, finalOptions); + return done(); + } + const completeEndSession = () => { + maybeClearPinnedConnection(this, finalOptions); + // release the server session back to the pool + this.sessionPool.release(this.serverSession); + this[kServerSession] = undefined; + // mark the session as ended, and emit a signal + this.hasEnded = true; + this.emit('ended', this); + // spec indicates that we should ignore all errors for `endSessions` + done(); + }; + if (this.serverSession && this.inTransaction()) { + this.abortTransaction(err => { + if (err) + return done(err); + completeEndSession(); + }); + return; + } + completeEndSession(); }); - }; - - /** - * 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(); + } + /** + * Advances the operationTime for a ClientSession. + * + * @param 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; + } + } + /** + * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession + * + * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature + */ + advanceClusterTime(clusterTime) { + var _b, _c; + if (!clusterTime || typeof clusterTime !== 'object') { + throw new error_1.MongoInvalidArgumentError('input cluster time must be an object'); + } + if (!clusterTime.clusterTime || clusterTime.clusterTime._bsontype !== 'Timestamp') { + throw new error_1.MongoInvalidArgumentError('input cluster time "clusterTime" property must be a valid BSON Timestamp'); + } + if (!clusterTime.signature || + ((_b = clusterTime.signature.hash) === null || _b === void 0 ? void 0 : _b._bsontype) !== 'Binary' || + (typeof clusterTime.signature.keyId !== 'number' && + ((_c = clusterTime.signature.keyId) === null || _c === void 0 ? void 0 : _c._bsontype) !== 'Long') // apparently we decode the key to number? + ) { + throw new error_1.MongoInvalidArgumentError('input cluster time must have a valid "signature" property with BSON Binary hash and BSON Long keyId'); + } + (0, common_1._advanceClusterTime)(this, clusterTime); + } + /** + * Used to determine if this session equals another + * + * @param session - The session to compare to + */ + equals(session) { + if (!(session instanceof ClientSession)) { + return false; + } + if (this.id == null || session.id == null) { + return false; + } + return this.id.id.buffer.equals(session.id.id.buffer); + } + /** Increment the transaction number on the internal ServerSession */ + incrementTransactionNumber() { + if (this.serverSession) { + this.serverSession.txnNumber = + typeof this.serverSession.txnNumber === 'number' ? this.serverSession.txnNumber + 1 : 0; + } + } + /** @returns whether this session is currently in a transaction or not */ + inTransaction() { + return this.transaction.isActive; + } + /** + * Starts a new transaction with the given options. + * + * @param options - Options for the transaction + */ + startTransaction(options) { + var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + if (this[kSnapshotEnabled]) { + throw new error_1.MongoCompatibilityError('Transactions are not allowed with snapshot sessions'); + } + assertAlive(this); + if (this.inTransaction()) { + throw new error_1.MongoTransactionError('Transaction already in progress'); + } + if (this.isPinned && this.transaction.isCommitted) { + this.unpin(); + } + const topologyMaxWireVersion = (0, utils_1.maxWireVersion)(this.topology); + if ((0, shared_1.isSharded)(this.topology) && + topologyMaxWireVersion != null && + topologyMaxWireVersion < minWireVersionForShardedTransactions) { + throw new error_1.MongoCompatibilityError('Transactions are not supported on sharded clusters in MongoDB < 4.2.'); + } + // increment txnNumber + this.incrementTransactionNumber(); + // create transaction state + this.transaction = new transactions_1.Transaction({ + readConcern: (_c = (_b = options === null || options === void 0 ? void 0 : options.readConcern) !== null && _b !== void 0 ? _b : this.defaultTransactionOptions.readConcern) !== null && _c !== void 0 ? _c : (_d = this.clientOptions) === null || _d === void 0 ? void 0 : _d.readConcern, + writeConcern: (_f = (_e = options === null || options === void 0 ? void 0 : options.writeConcern) !== null && _e !== void 0 ? _e : this.defaultTransactionOptions.writeConcern) !== null && _f !== void 0 ? _f : (_g = this.clientOptions) === null || _g === void 0 ? void 0 : _g.writeConcern, + readPreference: (_j = (_h = options === null || options === void 0 ? void 0 : options.readPreference) !== null && _h !== void 0 ? _h : this.defaultTransactionOptions.readPreference) !== null && _j !== void 0 ? _j : (_k = this.clientOptions) === null || _k === void 0 ? void 0 : _k.readPreference, + maxCommitTimeMS: (_l = options === null || options === void 0 ? void 0 : options.maxCommitTimeMS) !== null && _l !== void 0 ? _l : this.defaultTransactionOptions.maxCommitTimeMS + }); + this.transaction.transition(transactions_1.TxnState.STARTING_TRANSACTION); + } + commitTransaction(callback) { + return (0, utils_1.maybePromise)(callback, cb => endTransaction(this, 'commitTransaction', cb)); + } + abortTransaction(callback) { + return (0, utils_1.maybePromise)(callback, cb => endTransaction(this, 'abortTransaction', cb)); + } + /** + * This is here to ensure that ClientSession is never serialized to BSON. + */ + toBSON() { + throw new error_1.MongoRuntimeError('ClientSession cannot be serialized to BSON.'); + } + /** + * 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 fn - A lambda to run within a transaction + * @param options - Optional settings for the transaction + */ + withTransaction(fn, options) { + const startTime = (0, utils_1.now)(); + return attemptTransaction(this, startTime, fn, options); + } +} +exports.ClientSession = ClientSession; +_a = kSnapshotEnabled; +const MAX_WITH_TRANSACTION_TIMEOUT = 120000; +const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([ + 'CannotSatisfyWriteConcern', + 'UnknownReplWriteConcern', + 'UnsatisfiableWriteConcern' +]); +function hasNotTimedOut(startTime, max) { + return (0, utils_1.calculateDurationInMs)(startTime) < max; +} +function isUnknownTransactionCommitResult(err) { + const isNonDeterministicWriteConcernError = err instanceof error_1.MongoServerError && + err.codeName && + NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName); + return (isMaxTimeMSExpiredError(err) || + (!isNonDeterministicWriteConcernError && + err.code !== error_1.MONGODB_ERROR_CODES.UnsatisfiableWriteConcern && + err.code !== error_1.MONGODB_ERROR_CODES.UnknownReplWriteConcern)); +} +function maybeClearPinnedConnection(session, options) { + // unpin a connection if it has been pinned + const conn = session[kPinnedConnection]; + const error = options === null || options === void 0 ? void 0 : options.error; + if (session.inTransaction() && + error && + error instanceof error_1.MongoError && + error.hasErrorLabel('TransientTransactionError')) { + return; + } + // NOTE: the spec talks about what to do on a network error only, but the tests seem to + // to validate that we don't unpin on _all_ errors? + if (conn) { + const servers = Array.from(session.topology.s.servers.values()); + const loadBalancer = servers[0]; + if ((options === null || options === void 0 ? void 0 : options.error) == null || (options === null || options === void 0 ? void 0 : options.force)) { + loadBalancer.s.pool.checkIn(conn); + conn.emit(connection_1.Connection.UNPINNED, session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION + ? metrics_1.ConnectionPoolMetrics.TXN + : metrics_1.ConnectionPoolMetrics.CURSOR); + if (options === null || options === void 0 ? void 0 : options.forceClear) { + loadBalancer.s.pool.clear(conn.serviceId); + } + } + session[kPinnedConnection] = undefined; + } +} +exports.maybeClearPinnedConnection = maybeClearPinnedConnection; +function isMaxTimeMSExpiredError(err) { + if (err == null || !(err instanceof error_1.MongoServerError)) { + return false; + } + return (err.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired || + (err.writeConcernError && err.writeConcernError.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired)); +} +function attemptTransactionCommit(session, startTime, fn, options) { + return session.commitTransaction().catch((err) => { + if (err instanceof error_1.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); + } } - }; - - /** - * @ignore - */ - - function throwIfInitialized(self) { - if (self.s.init) { - throw new Error( - "You cannot change options after the stream has entered" + - "flowing mode!" - ); + throw err; + }); +} +const USER_EXPLICIT_TXN_END_STATES = new Set([ + transactions_1.TxnState.NO_TRANSACTION, + transactions_1.TxnState.TRANSACTION_COMMITTED, + transactions_1.TxnState.TRANSACTION_ABORTED +]); +function userExplicitlyEndedTransaction(session) { + return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state); +} +function attemptTransaction(session, startTime, fn, options) { + const Promise = promise_provider_1.PromiseProvider.get(); + session.startTransaction(options); + let promise; + try { + promise = fn(session); + } + catch (err) { + promise = Promise.reject(err); + } + if (!(0, utils_1.isPromiseLike)(promise)) { + session.abortTransaction(); + throw new error_1.MongoInvalidArgumentError('Function provided to `withTransaction` must return a Promise'); + } + return promise.then(() => { + if (userExplicitlyEndedTransaction(session)) { + return; } - } - - /** - * @ignore - */ - - function doRead(_this) { - if (_this.destroyed) { - return; + return attemptTransactionCommit(session, startTime, fn, options); + }, err => { + function maybeRetryOrThrow(err) { + if (err instanceof error_1.MongoError && + err.hasErrorLabel('TransientTransactionError') && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT)) { + return attemptTransaction(session, startTime, fn, options); + } + if (isMaxTimeMSExpiredError(err)) { + err.addErrorLabel('UnknownTransactionCommitResult'); + } + throw err; } - - _this.s.cursor.next(function (error, doc) { - if (_this.destroyed) { + 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 + const txnState = session.transaction.state; + if (txnState === transactions_1.TxnState.NO_TRANSACTION) { + callback(new error_1.MongoTransactionError('No transaction started')); + return; + } + if (commandName === 'commitTransaction') { + if (txnState === transactions_1.TxnState.STARTING_TRANSACTION || + txnState === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) { + // the transaction was never started, we can safely exit here + session.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY); + callback(); 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"); - }); - }); - + } + if (txnState === transactions_1.TxnState.TRANSACTION_ABORTED) { + callback(new error_1.MongoTransactionError('Cannot call commitTransaction after calling abortTransaction')); + return; + } + } + else { + if (txnState === transactions_1.TxnState.STARTING_TRANSACTION) { + // the transaction was never started, we can safely exit here + session.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED); + callback(); 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 (txnState === transactions_1.TxnState.TRANSACTION_ABORTED) { + callback(new error_1.MongoTransactionError('Cannot call abortTransaction twice')); + return; } - if (self.s.options && self.s.options.skip) { - findOneOptions.skip = self.s.options.skip; + if (txnState === transactions_1.TxnState.TRANSACTION_COMMITTED || + txnState === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) { + callback(new error_1.MongoTransactionError('Cannot call abortTransaction after calling commitTransaction')); + return; } - - self.s.files.findOne( - self.s.filter, - findOneOptions, - function (error, doc) { - if (error) { - return __handleError(self, error); + } + // 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.writeConcern) { + writeConcern = { w: session.clientOptions.writeConcern.w }; + } + if (txnState === transactions_1.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(transactions_1.TxnState.TRANSACTION_ABORTED); + if (session.loadBalanced) { + maybeClearPinnedConnection(session, { force: false }); } - - 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); + // The spec indicates that we should ignore all errors on `abortTransaction` + return callback(); + } + session.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED); + if (e) { + if (e instanceof error_1.MongoNetworkError || + e instanceof error_1.MongoWriteConcernError || + (0, error_1.isRetryableError)(e) || + isMaxTimeMSExpiredError(e)) { + if (isUnknownTransactionCommitResult(e)) { + e.addErrorLabel('UnknownTransactionCommitResult'); + // per txns spec, must unpin session in this case + session.unpin({ error: e }); + } } - - // If document is empty, kill the stream immediately and don't - // execute any reads - if (doc.length <= 0) { - self.push(null); - return; + else if (e.hasErrorLabel('TransientTransactionError')) { + session.unpin({ error: e }); } - - 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; + } + callback(e, r); + } + // Assumption here that commandName is "commitTransaction" or "abortTransaction" + if (session.transaction.recoveryToken) { + command.recoveryToken = session.transaction.recoveryToken; + } + // send the command + (0, execute_operation_1.executeOperation)(session.topology, new run_command_1.RunAdminCommandOperation(undefined, command, { + session, + readPreference: read_preference_1.ReadPreference.primary, + bypassPinningCheck: true + }), (err, reply) => { + if (command.abortTransaction) { + // always unpin on abort regardless of command outcome + session.unpin(); + } + if (err && (0, error_1.isRetryableEndTransactionError)(err)) { + // SPEC-1185: apply majority write concern when retrying commitTransaction + if (command.commitTransaction) { + // per txns spec, must unpin session in this case + session.unpin({ force: true }); + command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, { + w: 'majority' + }); } - - try { - self.s.bytesToSkip = handleStartOption(self, doc, self.s.options); - } catch (error) { - return __handleError(self, error); + return (0, execute_operation_1.executeOperation)(session.topology, new run_command_1.RunAdminCommandOperation(undefined, command, { + session, + readPreference: read_preference_1.ReadPreference.primary, + bypassPinningCheck: true + }), (_err, _reply) => commandHandler(_err, _reply)); + } + commandHandler(err, reply); + }); +} +/** + * 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. + * @public + */ +class ServerSession { + /** @internal */ + constructor() { + this.id = { id: new bson_1.Binary((0, utils_1.uuidV4)(), bson_1.Binary.SUBTYPE_UUID) }; + this.lastUse = (0, utils_1.now)(); + this.txnNumber = 0; + this.isDirty = false; + } + /** + * Determines if the server session has timed out. + * + * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes" + */ + 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((((0, utils_1.calculateDurationInMs)(this.lastUse) % 86400000) % 3600000) / 60000); + return idleTimeMinutes > sessionTimeoutMinutes - 1; + } +} +exports.ServerSession = ServerSession; +/** + * Maintains a pool of Server Sessions. + * For internal use only + * @internal + */ +class ServerSessionPool { + constructor(topology) { + if (topology == null) { + throw new error_1.MongoRuntimeError('ServerSessionPool requires a topology'); + } + this.topology = topology; + this.sessions = []; + } + /** Ends all sessions in the session pool */ + 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. + */ + acquire() { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes || 10; + while (this.sessions.length) { + const session = this.sessions.shift(); + if (session && (this.topology.loadBalanced || !session.hasTimedOut(sessionTimeoutMinutes))) { + return session; } - - 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 }; - } + } + 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. + * + * @param session - The session to release to the pool + */ + release(session) { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; + if (this.topology.loadBalanced && !sessionTimeoutMinutes) { + this.sessions.unshift(session); + } + if (!sessionTimeoutMinutes) { + return; + } + while (this.sessions.length) { + const pooledSession = this.sessions[this.sessions.length - 1]; + if (pooledSession.hasTimedOut(sessionTimeoutMinutes)) { + this.sessions.pop(); } - self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 }); - - if (self.s.readPreference) { - self.s.cursor.setReadPreference(self.s.readPreference); + else { + break; } - - 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); + } + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + if (session.isDirty) { + return; } - - self.emit("file", doc); - } - ); - } - - /** - * @ignore - */ - - function waitForFile(_this, callback) { - if (_this.s.file) { - return callback(); + // otherwise, readd this session to the session pool + this.sessions.unshift(session); } - - if (!_this.s.init) { - init(_this); - _this.s.init = true; + } +} +exports.ServerSessionPool = ServerSessionPool; +// TODO: 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.geoNear) { + return true; + } + if (command.mapReduce && + options && + options.out && + (options.out.inline === 1 || options.out === 'inline')) { + return true; + } + return false; +} +exports.commandSupportsReadConcern = commandSupportsReadConcern; +/** + * Optionally decorate a command with sessions specific keys + * + * @param session - the session tracking transaction state + * @param command - the command to decorate + * @param options - Optional settings passed to calling operation + */ +function applySession(session, command, options) { + var _b; + // TODO: merge this with `assertAlive`, did not want to throw a try/catch here + if (session.hasEnded) { + return new error_1.MongoExpiredSessionError(); + } + const serverSession = session.serverSession; + if (serverSession == null) { + return new error_1.MongoRuntimeError('Unable to acquire server session'); + } + // SPEC-1019: silently ignore explicit session with unacknowledged write for backwards compatibility + // FIXME: NODE-2781, this check for write concern shouldn't be happening here, but instead during command construction + if (options && options.writeConcern && options.writeConcern.w === 0) { + if (session && session.explicit) { + return new error_1.MongoAPIError('Cannot have explicit session with unacknowledged writes'); } - - _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; + return; + } + // mark the last use of this session, and apply the `lsid` + serverSession.lastUse = (0, utils_1.now)(); + command.lsid = serverSession.id; + // first apply non-transaction-specific sessions data + const inTransaction = session.inTransaction() || (0, transactions_1.isTransactionCommand)(command); + const isRetryableWrite = (options === null || options === void 0 ? void 0 : options.willRetryWrite) || false; + if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) { + command.txnNumber = bson_1.Long.fromNumber(serverSession.txnNumber); + } + if (!inTransaction) { + if (session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION) { + session.transaction.transition(transactions_1.TxnState.NO_TRANSACTION); } - } - - /** - * @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 - ); + if (session.supports.causalConsistency && + session.operationTime && + commandSupportsReadConcern(command, options)) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); } - } - - /** - * @ignore - */ - - function __handleError(_this, error) { - _this.emit("error", error); - } - - /***/ - }, - - /***/ 2573: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - var Emitter = __nccwpck_require__(8614).EventEmitter; - var GridFSBucketReadStream = __nccwpck_require__(4190); - var GridFSBucketWriteStream = __nccwpck_require__(1413); - var shallowClone = __nccwpck_require__(1371).shallowClone; - var toError = __nccwpck_require__(1371).toError; - var util = __nccwpck_require__(1669); - var executeLegacyOperation = - __nccwpck_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 if (session[kSnapshotEnabled]) { + command.readConcern = command.readConcern || { level: read_concern_1.ReadConcernLevel.snapshot }; + if (session[kSnapshotTime] != null) { + Object.assign(command.readConcern, { atClusterTime: session[kSnapshotTime] }); } - } - } 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 = {}; + return; + } + // now attempt to apply transaction-specific sessions data + // `autocommit` must always be false to differentiate from retryable writes + command.autocommit = false; + if (session.transaction.state === transactions_1.TxnState.STARTING_TRANSACTION) { + session.transaction.transition(transactions_1.TxnState.TRANSACTION_IN_PROGRESS); + command.startTransaction = true; + const readConcern = session.transaction.options.readConcern || ((_b = session === null || session === void 0 ? void 0 : session.clientOptions) === null || _b === void 0 ? void 0 : _b.readConcern); + if (readConcern) { + command.readConcern = readConcern; } - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; + if (session.supports.causalConsistency && session.operationTime) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); } - 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 = {}; + } +} +exports.applySession = applySession; +function updateSessionFromResponse(session, document) { + var _b; + if (document.$clusterTime) { + (0, common_1._advanceClusterTime)(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; + } + if ((session === null || session === void 0 ? void 0 : session[kSnapshotEnabled]) && session[kSnapshotTime] == null) { + // find and aggregate commands return atClusterTime on the cursor + // distinct includes it in the response body + const atClusterTime = ((_b = document.cursor) === null || _b === void 0 ? void 0 : _b.atClusterTime) || document.atClusterTime; + if (atClusterTime) { + session[kSnapshotTime] = atClusterTime; } - - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; + } +} +exports.updateSessionFromResponse = updateSessionFromResponse; +//# sourceMappingURL=sessions.js.map + +/***/ }), + +/***/ 8370: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.formatSort = void 0; +const error_1 = __nccwpck_require__(9386); +/** @internal */ +function prepareDirection(direction = 1) { + const value = `${direction}`.toLowerCase(); + if (isMeta(direction)) + return direction; + switch (value) { + case 'ascending': + case 'asc': + case '1': + return 1; + case 'descending': + case 'desc': + case '-1': + return -1; + default: + throw new error_1.MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(direction)}`); + } +} +/** @internal */ +function isMeta(t) { + return typeof t === 'object' && t != null && '$meta' in t && typeof t.$meta === 'string'; +} +/** @internal */ +function isPair(t) { + if (Array.isArray(t) && t.length === 2) { + try { + prepareDirection(t[1]); + return true; } - - 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(); + catch (e) { + return false; + } + } + return false; +} +function isDeep(t) { + return Array.isArray(t) && Array.isArray(t[0]); +} +function isMap(t) { + return t instanceof Map && t.size > 0; +} +/** @internal */ +function pairToMap(v) { + return new Map([[`${v[0]}`, prepareDirection([v[1]])]]); +} +/** @internal */ +function deepToMap(t) { + const sortEntries = t.map(([k, v]) => [`${k}`, prepareDirection(v)]); + return new Map(sortEntries); +} +/** @internal */ +function stringsToMap(t) { + const sortEntries = t.map(key => [`${key}`, 1]); + return new Map(sortEntries); +} +/** @internal */ +function objectToMap(t) { + const sortEntries = Object.entries(t).map(([k, v]) => [ + `${k}`, + prepareDirection(v) + ]); + return new Map(sortEntries); +} +/** @internal */ +function mapToMap(t) { + const sortEntries = Array.from(t).map(([k, v]) => [ + `${k}`, + prepareDirection(v) + ]); + return new Map(sortEntries); +} +/** converts a Sort type into a type that is valid for the server (SortForCmd) */ +function formatSort(sort, direction) { + if (sort == null) + return undefined; + if (typeof sort === 'string') + return new Map([[sort, prepareDirection(direction)]]); + if (typeof sort !== 'object') { + throw new error_1.MongoInvalidArgumentError(`Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object`); + } + if (!Array.isArray(sort)) { + return isMap(sort) ? mapToMap(sort) : Object.keys(sort).length ? objectToMap(sort) : undefined; + } + if (!sort.length) + return undefined; + if (isDeep(sort)) + return deepToMap(sort); + if (isPair(sort)) + return pairToMap(sort); + return stringsToMap(sort); +} +exports.formatSort = formatSort; +//# sourceMappingURL=sort.js.map + +/***/ }), + +/***/ 8883: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isTransactionCommand = exports.Transaction = exports.TxnState = void 0; +const read_preference_1 = __nccwpck_require__(9802); +const error_1 = __nccwpck_require__(9386); +const read_concern_1 = __nccwpck_require__(7289); +const write_concern_1 = __nccwpck_require__(2481); +/** @internal */ +exports.TxnState = Object.freeze({ + NO_TRANSACTION: 'NO_TRANSACTION', + STARTING_TRANSACTION: 'STARTING_TRANSACTION', + TRANSACTION_IN_PROGRESS: 'TRANSACTION_IN_PROGRESS', + TRANSACTION_COMMITTED: 'TRANSACTION_COMMITTED', + TRANSACTION_COMMITTED_EMPTY: 'TRANSACTION_COMMITTED_EMPTY', + TRANSACTION_ABORTED: 'TRANSACTION_ABORTED' +}); +const stateMachine = { + [exports.TxnState.NO_TRANSACTION]: [exports.TxnState.NO_TRANSACTION, exports.TxnState.STARTING_TRANSACTION], + [exports.TxnState.STARTING_TRANSACTION]: [ + exports.TxnState.TRANSACTION_IN_PROGRESS, + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.TRANSACTION_ABORTED + ], + [exports.TxnState.TRANSACTION_IN_PROGRESS]: [ + exports.TxnState.TRANSACTION_IN_PROGRESS, + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_ABORTED + ], + [exports.TxnState.TRANSACTION_COMMITTED]: [ + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.STARTING_TRANSACTION, + exports.TxnState.NO_TRANSACTION + ], + [exports.TxnState.TRANSACTION_ABORTED]: [exports.TxnState.STARTING_TRANSACTION, exports.TxnState.NO_TRANSACTION], + [exports.TxnState.TRANSACTION_COMMITTED_EMPTY]: [ + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.NO_TRANSACTION + ] +}; +const ACTIVE_STATES = new Set([ + exports.TxnState.STARTING_TRANSACTION, + exports.TxnState.TRANSACTION_IN_PROGRESS +]); +const COMMITTED_STATES = new Set([ + exports.TxnState.TRANSACTION_COMMITTED, + exports.TxnState.TRANSACTION_COMMITTED_EMPTY, + exports.TxnState.TRANSACTION_ABORTED +]); +/** + * @public + * A class maintaining state related to a server transaction. Internal Only + */ +class Transaction { + /** Create a transaction @internal */ + constructor(options) { + options = options !== null && options !== void 0 ? options : {}; + this.state = exports.TxnState.NO_TRANSACTION; + this.options = {}; + const writeConcern = write_concern_1.WriteConcern.fromOptions(options); + if (writeConcern) { + if (writeConcern.w === 0) { + throw new error_1.MongoTransactionError('Transactions do not support unacknowledged write concern'); } - ); - }); - } - - /** - * 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); + this.options.writeConcern = writeConcern; } - if (options.limit != null) { - cursor.limit(options.limit); + if (options.readConcern) { + this.options.readConcern = read_concern_1.ReadConcern.fromOptions(options); } - if (options.maxTimeMS != null) { - cursor.maxTimeMS(options.maxTimeMS); + if (options.readPreference) { + this.options.readPreference = read_preference_1.ReadPreference.fromOptions(options); } - if (options.noCursorTimeout != null) { - cursor.addCursorFlag("noCursorTimeout", options.noCursorTimeout); + if (options.maxCommitTimeMS) { + this.options.maxTimeMS = options.maxCommitTimeMS; } - if (options.skip != null) { - cursor.skip(options.skip); + // TODO: This isn't technically necessary + this._pinnedServer = undefined; + this._recoveryToken = undefined; + } + /** @internal */ + get server() { + return this._pinnedServer; + } + get recoveryToken() { + return this._recoveryToken; + } + get isPinned() { + return !!this.server; + } + /** @returns Whether the transaction has started */ + get isStarting() { + return this.state === exports.TxnState.STARTING_TRANSACTION; + } + /** + * @returns Whether this session is presently in a transaction + */ + get isActive() { + return ACTIVE_STATES.has(this.state); + } + get isCommitted() { + return COMMITTED_STATES.has(this.state); + } + /** + * Transition the transaction in the state machine + * @internal + * @param nextState - The new state to transition to + */ + transition(nextState) { + const nextStates = stateMachine[this.state]; + if (nextStates && nextStates.includes(nextState)) { + this.state = nextState; + if (this.state === exports.TxnState.NO_TRANSACTION || + this.state === exports.TxnState.STARTING_TRANSACTION || + this.state === exports.TxnState.TRANSACTION_ABORTED) { + this.unpinServer(); + } + return; } - if (options.sort != null) { - cursor.sort(options.sort); + throw new error_1.MongoRuntimeError(`Attempted illegal state transition from [${this.state}] to [${nextState}]`); + } + /** @internal */ + pinServer(server) { + if (this.isActive) { + this._pinnedServer = server; } - - 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; - } + } + /** @internal */ + unpinServer() { + this._pinnedServer = undefined; + } +} +exports.Transaction = Transaction; +function isTransactionCommand(command) { + return !!(command.commitTransaction || command.abortTransaction); +} +exports.isTransactionCommand = isTransactionCommand; +//# sourceMappingURL=transactions.js.map + +/***/ }), + +/***/ 1371: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.shuffle = exports.parsePackageVersion = exports.supportsRetryableWrites = exports.enumToString = exports.emitWarningOnce = exports.emitWarning = exports.MONGODB_WARNING_CODE = exports.DEFAULT_PK_FACTORY = exports.HostAddress = exports.BufferPool = exports.deepCopy = exports.isRecord = exports.setDifference = exports.isSuperset = exports.resolveOptions = exports.hasAtomicOperators = exports.makeInterruptibleAsyncInterval = exports.calculateDurationInMs = exports.now = exports.makeClientMetadata = exports.makeStateMachine = exports.errorStrictEqual = exports.arrayStrictEqual = exports.eachAsyncSeries = exports.eachAsync = exports.collationNotSupported = exports.maxWireVersion = exports.uuidV4 = exports.databaseNamespace = exports.maybePromise = exports.makeCounter = exports.MongoDBNamespace = exports.ns = exports.deprecateOptions = exports.defaultMsgHandler = exports.getTopology = exports.decorateWithExplain = exports.decorateWithReadConcern = exports.decorateWithCollation = exports.isPromiseLike = exports.applyWriteConcern = exports.applyRetryableWrites = exports.executeLegacyOperation = exports.filterOptions = exports.mergeOptions = exports.isObject = exports.parseIndexOptions = exports.normalizeHintField = exports.checkCollectionName = exports.MAX_JS_INT = void 0; +const os = __nccwpck_require__(2087); +const crypto = __nccwpck_require__(6417); +const promise_provider_1 = __nccwpck_require__(2725); +const error_1 = __nccwpck_require__(9386); +const write_concern_1 = __nccwpck_require__(2481); +const common_1 = __nccwpck_require__(472); +const read_concern_1 = __nccwpck_require__(7289); +const bson_1 = __nccwpck_require__(5578); +const read_preference_1 = __nccwpck_require__(9802); +const url_1 = __nccwpck_require__(8835); +const constants_1 = __nccwpck_require__(6042); +exports.MAX_JS_INT = Number.MAX_SAFE_INTEGER + 1; +/** + * Throws if collectionName is not a valid mongodb collection namespace. + * @internal + */ +function checkCollectionName(collectionName) { + if ('string' !== typeof collectionName) { + throw new error_1.MongoInvalidArgumentError('Collection name must be a String'); + } + if (!collectionName || collectionName.indexOf('..') !== -1) { + throw new error_1.MongoInvalidArgumentError('Collection names cannot be empty'); + } + if (collectionName.indexOf('$') !== -1 && + collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new error_1.MongoInvalidArgumentError("Collection names must not contain '$'"); + } + if (collectionName.match(/^\.|\.$/) != null) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new error_1.MongoInvalidArgumentError("Collection names must not start or end with '.'"); + } + // Validate that we are not passing 0x00 in the collection name + if (collectionName.indexOf('\x00') !== -1) { + // TODO(NODE-3483): Use MongoNamespace static method + throw new error_1.MongoInvalidArgumentError('Collection names cannot contain a null character'); + } +} +exports.checkCollectionName = checkCollectionName; +/** + * Ensure Hint field is in a shape we expect: + * - object of index names mapping to 1 or -1 + * - just an index name + * @internal + */ +function normalizeHintField(hint) { + let finalHint = undefined; + if (typeof hint === 'string') { + finalHint = hint; + } + else if (Array.isArray(hint)) { + finalHint = {}; + hint.forEach(param => { + finalHint[param] = 1; + }); + } + else if (hint != null && typeof hint === 'object') { + finalHint = {}; + for (const name in hint) { + finalHint[name] = hint[name]; } - - 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")); + } + return finalHint; +} +exports.normalizeHintField = normalizeHintField; +/** + * Create an index specifier based on + * @internal + */ +function parseIndexOptions(indexSpec) { + const fieldHash = {}; + const indexes = []; + let keys; + // Get all the fields accordingly + if ('string' === typeof indexSpec) { + // 'type' + indexes.push(indexSpec + '_' + 1); + fieldHash[indexSpec] = 1; + } + else if (Array.isArray(indexSpec)) { + indexSpec.forEach((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(k => { + indexes.push(k + '_' + f[k]); + fieldHash[k] = f[k]; + }); } - 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); + else { + // undefined (ignore) } - - 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, - __nccwpck_require__ - ) => { - "use strict"; - - var core = __nccwpck_require__(3994); - var crypto = __nccwpck_require__(6417); - var stream = __nccwpck_require__(2413); - var util = __nccwpck_require__(1669); - var Buffer = __nccwpck_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|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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 || {}; - stream.Writable.call(this, 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); + } + else if (isObject(indexSpec)) { + // {location:'2d', type:1} + keys = Object.keys(indexSpec); + Object.entries(indexSpec).forEach(([key, value]) => { + indexes.push(key + '_' + value); + fieldHash[key] = value; }); - }; - - /** - * 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); + } + return { + name: indexes.join('_'), + keys: keys, + fieldHash: fieldHash + }; +} +exports.parseIndexOptions = parseIndexOptions; +/** + * Checks if arg is an Object: + * - **NOTE**: the check is based on the `[Symbol.toStringTag]() === 'Object'` + * @internal + */ +// eslint-disable-next-line @typescript-eslint/ban-types +function isObject(arg) { + return '[object Object]' === Object.prototype.toString.call(arg); +} +exports.isObject = isObject; +/** @internal */ +function mergeOptions(target, source) { + return { ...target, ...source }; +} +exports.mergeOptions = mergeOptions; +/** @internal */ +function filterOptions(options, names) { + const filterOptions = {}; + for (const name in options) { + if (names.includes(name)) { + filterOptions[name] = options[name]; } - 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); + } + // Filtered options + return filterOptions; +} +exports.filterOptions = filterOptions; +/** + * Executes the given operation with provided arguments. + * + * @remarks + * 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 + * + * @internal + * + * @param topology - The topology to execute this operation on + * @param operation - The operation to execute + * @param args - Arguments to apply the provided operation + * @param options - Options that modify the behavior of the method + */ +function executeLegacyOperation(topology, operation, args, options) { + const Promise = promise_provider_1.PromiseProvider.get(); + if (!Array.isArray(args)) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('This method requires an array of arguments to apply'); + } + options = options !== null && options !== void 0 ? options : {}; + 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; + let opOptions; + let 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 }); } - 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); + else if (opOptions.session && opOptions.session.hasEnded) { + throw new error_1.MongoExpiredSessionError(); } - - if (checkAborted(this, callback)) { - return; + } + function makeExecuteCallback(resolve, reject) { + return function (err, result) { + if (session && session.owner === owner && !(options === null || options === void 0 ? void 0 : 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(undefined, result), err => callback(err, null)); + args.push(handler); + try { + return operation(...args); } - this.state.streamEnd = true; - - if (callback) { - this.once("finish", function (result) { - callback(null, result); - }); + catch (e) { + handler(e); + throw e; } - - if (!chunk) { - waitForIndexes(this, function () { - writeRemnant(_this); - }); - return; + } + // Return a Promise + if (args[args.length - 1] != null) { + // TODO(NODE-3483) + throw new error_1.MongoRuntimeError('Final argument to `executeLegacyOperation` must be a callback'); + } + return new Promise((resolve, reject) => { + const handler = makeExecuteCallback(resolve, reject); + args[args.length - 1] = handler; + try { + return operation(...args); } - - this.write(chunk, encoding, function () { - writeRemnant(_this); - }); - }; - - /** - * @ignore - */ - - function __handleError(_this, error, callback) { - if (_this.state.errored) { - return; + catch (e) { + handler(e); } - _this.state.errored = true; - if (callback) { - return callback(error); + }); +} +exports.executeLegacyOperation = executeLegacyOperation; +/** + * Applies retryWrites: true to a command if retryWrites is set on the command's database. + * @internal + * + * @param target - The target command to which we will apply retryWrites. + * @param db - The database from which we can inherit a retryWrites value. + */ +function applyRetryableWrites(target, db) { + var _a; + if (db && ((_a = db.s.options) === null || _a === void 0 ? void 0 : _a.retryWrites)) { + target.retryWrites = true; + } + return target; +} +exports.applyRetryableWrites = applyRetryableWrites; +/** + * Applies a write concern to a command based on well defined inheritance rules, optionally + * detecting support for the write concern in the first place. + * @internal + * + * @param target - the target command we will be applying the write concern to + * @param sources - sources where we can inherit default write concerns from + * @param options - optional settings passed into a command for write concern overrides + */ +function applyWriteConcern(target, sources, options) { + options = options !== null && options !== void 0 ? 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; } - _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); - _this.emit("close"); - } - ); - - return true; + return target; + } + const writeConcern = write_concern_1.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; +} +exports.applyWriteConcern = applyWriteConcern; +/** + * Checks if a given value is a Promise + * + * @typeParam T - The result type of maybePromise + * @param maybePromise - An object that could be a promise + * @returns true if the provided value is a Promise + */ +function isPromiseLike(maybePromise) { + return !!maybePromise && typeof maybePromise.then === 'function'; +} +exports.isPromiseLike = isPromiseLike; +/** + * Applies collation to a given command. + * @internal + * + * @param command - the command on which to apply collation + * @param target - target of command + * @param options - options containing collation settings + */ +function decorateWithCollation(command, target, options) { + const capabilities = getTopology(target).capabilities; + if (options.collation && typeof options.collation === 'object') { + if (capabilities && capabilities.commandsTakeCollation) { + command.collation = options.collation; } - - 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); + else { + throw new error_1.MongoCompatibilityError(`Current topology does not support collation`); + } + } +} +exports.decorateWithCollation = decorateWithCollation; +/** + * Applies a read concern to a given command. + * @internal + * + * @param command - the command on which to apply the read concern + * @param coll - the parent collection of the operation calling this method + */ +function decorateWithReadConcern(command, coll, options) { + if (options && options.session && options.session.inTransaction()) { + return; + } + const 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 }); + } +} +exports.decorateWithReadConcern = decorateWithReadConcern; +/** + * Applies an explain to a given command. + * @internal + * + * @param command - the command on which to apply the explain + * @param options - the options containing the explain verbosity + */ +function decorateWithExplain(command, explain) { + if (command.explain) { + return command; + } + return { explain: command, verbosity: explain.verbosity }; +} +exports.decorateWithExplain = decorateWithExplain; +/** + * A helper function to get the topology from a given provider. Throws + * if the topology cannot be found. + * @internal + */ +function getTopology(provider) { + if (`topology` in provider && provider.topology) { + return provider.topology; + } + else if ('client' in provider.s && provider.s.client.topology) { + return provider.s.client.topology; + } + else if ('db' in provider.s && provider.s.db.s.client.topology) { + return provider.s.db.s.client.topology; + } + throw new error_1.MongoNotConnectedError('MongoClient must be connected to perform this operation'); +} +exports.getTopology = getTopology; +/** + * Default message handler for generating deprecation warnings. + * @internal + * + * @param name - function name + * @param option - option name + * @returns warning message + */ +function defaultMsgHandler(name, option) { + return `${name} option [${option}] is deprecated and will be removed in a later version.`; +} +exports.defaultMsgHandler = defaultMsgHandler; +/** + * Deprecates a given function's options. + * @internal + * + * @param this - the bound class if this is a method + * @param config - configuration for deprecation + * @param fn - the target function of deprecation + * @returns modified function that warns once per deprecated option, and executes original function + */ +function deprecateOptions(config, fn) { + if (process.noDeprecation === true) { + return fn; + } + const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; + const optionsWarned = new Set(); + function deprecated(...args) { + const options = args[config.optionsIndex]; + // ensure options is a valid, non-empty object, otherwise short-circuit + if (!isObject(options) || Object.keys(options).length === 0) { + return fn.bind(this)(...args); // call the function, no change + } + // interrupt the function call with a warning + for (const deprecatedOption of config.deprecatedOptions) { + if (deprecatedOption in options && !optionsWarned.has(deprecatedOption)) { + optionsWarned.add(deprecatedOption); + const msg = msgHandler(config.name, deprecatedOption); + emitWarning(msg); + if (this && 'getLogger' in this) { + const logger = this.getLogger(); + if (logger) { + logger.warn(msg); } - - 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); - }); } - }); + } + return fn.bind(this)(...args); + } + // 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; +} +exports.deprecateOptions = deprecateOptions; +/** @internal */ +function ns(ns) { + return MongoDBNamespace.fromString(ns); +} +exports.ns = ns; +/** @public */ +class MongoDBNamespace { + /** + * Create a namespace object + * + * @param db - database name + * @param collection - collection name + */ + 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) { + // TODO(NODE-3483): Replace with MongoNamespaceError + throw new error_1.MongoRuntimeError(`Cannot parse namespace from "${namespace}"`); + } + const [db, ...collection] = namespace.split('.'); + return new MongoDBNamespace(db, collection.join('.')); + } +} +exports.MongoDBNamespace = MongoDBNamespace; +/** @internal */ +function* makeCounter(seed = 0) { + let count = seed; + while (true) { + const newCount = count; + count += 1; + yield newCount; + } +} +exports.makeCounter = makeCounter; +/** + * Helper function for either accepting a callback, or returning a promise + * @internal + * + * @param callback - The last function argument in exposed method, controls if a Promise is returned + * @param wrapper - A function that wraps the callback + * @returns Returns void if a callback is supplied, else returns a Promise. + */ +function maybePromise(callback, wrapper) { + const Promise = promise_provider_1.PromiseProvider.get(); + let result; + if (typeof callback !== 'function') { + result = new Promise((resolve, reject) => { + callback = (err, res) => { + if (err) + return reject(err); + resolve(res); + }; }); - } - - /** - * @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; + } + wrapper((err, res) => { + if (err != null) { + try { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + callback(err); + } + catch (error) { + process.nextTick(() => { + throw error; + }); + } + return; } - - if (contentType) { - ret.contentType = contentType; + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + callback(err, res); + }); + return result; +} +exports.maybePromise = maybePromise; +/** @internal */ +function databaseNamespace(ns) { + return ns.split('.')[0]; +} +exports.databaseNamespace = databaseNamespace; +/** + * Synchronously Generate a UUIDv4 + * @internal + */ +function uuidV4() { + const result = crypto.randomBytes(16); + result[6] = (result[6] & 0x0f) | 0x40; + result[8] = (result[8] & 0x3f) | 0x80; + return result; +} +exports.uuidV4 = uuidV4; +/** + * A helper function for determining `maxWireVersion` between legacy and new topology instances + * @internal + */ +function maxWireVersion(topologyOrServer) { + if (topologyOrServer) { + if (topologyOrServer.loadBalanced) { + // Since we do not have a monitor, we assume the load balanced server is always + // pointed at the latest mongodb version. There is a risk that for on-prem + // deployments that don't upgrade immediately that this could alert to the + // application that a feature is avaiable that is actually not. + return constants_1.MAX_SUPPORTED_WIRE_VERSION; + } + if (topologyOrServer.ismaster) { + return topologyOrServer.ismaster.maxWireVersion; } - - if (aliases) { - ret.aliases = aliases; + if ('lastIsMaster' in topologyOrServer && typeof topologyOrServer.lastIsMaster === 'function') { + const lastIsMaster = topologyOrServer.lastIsMaster(); + if (lastIsMaster) { + return lastIsMaster.maxWireVersion; + } } - - if (metadata) { - ret.metadata = metadata; + if (topologyOrServer.description && + 'maxWireVersion' in topologyOrServer.description && + topologyOrServer.description.maxWireVersion != null) { + return topologyOrServer.description.maxWireVersion; } - - return ret; - } - - /** - * @ignore - */ - - function doWrite(_this, chunk, encoding, callback) { - if (checkAborted(_this, callback)) { - return false; + } + return 0; +} +exports.maxWireVersion = maxWireVersion; +/** + * Checks that collation is supported by server. + * @internal + * + * @param server - to check against + * @param cmd - object where collation may be specified + */ +function collationNotSupported(server, cmd) { + return cmd && cmd.collation && maxWireVersion(server) < 5; +} +exports.collationNotSupported = collationNotSupported; +/** + * Applies the function `eachFn` to each item in `arr`, in parallel. + * @internal + * + * @param arr - An array of items to asynchronously iterate over + * @param 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 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; } - - 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; + if (idx === arr.length && awaiting <= 0) { + callback(); } - - // 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); + } +} +exports.eachAsync = eachAsync; +/** @internal */ +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; } - - // 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. + if (idx === arr.length && awaiting <= 0) { + callback(); + return; + } + eachFn(arr[idx], eachCallback); + } + eachFn(arr[idx], eachCallback); +} +exports.eachAsyncSeries = eachAsyncSeries; +/** @internal */ +function arrayStrictEqual(arr, arr2) { + if (!Array.isArray(arr) || !Array.isArray(arr2)) { 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 arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]); +} +exports.arrayStrictEqual = arrayStrictEqual; +/** @internal */ +function errorStrictEqual(lhs, rhs) { + if (lhs === rhs) { + return true; + } + if (!lhs || !rhs) { + return lhs === rhs; + } + 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; +} +exports.errorStrictEqual = errorStrictEqual; +/** @internal */ +function makeStateMachine(stateTable) { + return function stateTransition(target, newState) { + const legalStates = stateTable[target.s.state]; + if (legalStates && legalStates.indexOf(newState) < 0) { + throw new error_1.MongoRuntimeError(`illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]`); + } + target.emit('stateChanged', target.s.state, newState); + target.s.state = newState; + }; +} +exports.makeStateMachine = makeStateMachine; +// eslint-disable-next-line @typescript-eslint/no-var-requires +const NODE_DRIVER_VERSION = __nccwpck_require__(306).version; +function makeClientMetadata(options) { + options = options !== null && options !== void 0 ? options : {}; + const metadata = { + driver: { + name: 'nodejs', + version: NODE_DRIVER_VERSION + }, + os: { + type: os.type(), + name: process.platform, + architecture: process.arch, + version: os.release() + }, + platform: `Node.js ${process.version}, ${os.endianness()} (unified)` + }; + // support optionally provided wrapping driver info + if (options.driverInfo) { + if (options.driverInfo.name) { + metadata.driver.name = `${metadata.driver.name}|${options.driverInfo.name}`; } - return obj; - } - - /** - * @ignore - */ - - function waitForIndexes(_this, callback) { - if (_this.bucket.s.checkedIndexes) { - return callback(false); + if (options.driverInfo.version) { + metadata.version = `${metadata.driver.version}|${options.driverInfo.version}`; } - - _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); + if (options.driverInfo.platform) { + metadata.platform = `${metadata.platform}|${options.driverInfo.platform}`; } - - ++_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); + } + if (options.appName) { + // MongoDB requires the appName not exceed a byte length of 128 + const buffer = Buffer.from(options.appName); + metadata.application = { + name: buffer.byteLength > 128 ? buffer.slice(0, 128).toString('utf8') : options.appName + }; + } + return metadata; +} +exports.makeClientMetadata = makeClientMetadata; +/** @internal */ +function now() { + const hrtime = process.hrtime(); + return Math.floor(hrtime[0] * 1000 + hrtime[1] / 1000000); +} +exports.now = now; +/** @internal */ +function calculateDurationInMs(started) { + if (typeof started !== 'number') { + throw new error_1.MongoInvalidArgumentError('Numeric value required to calculate duration'); + } + const elapsed = now() - started; + return elapsed < 0 ? 0 : elapsed; +} +exports.calculateDurationInMs = calculateDurationInMs; +/** + * 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. + * @internal + * + * @param fn - An async function to run on an interval, must accept a `callback` as its only parameter + */ +function makeInterruptibleAsyncInterval(fn, options) { + let timerId; + let lastCallTime; + let cannotBeExpedited = false; + let stopped = false; + options = options !== null && options !== void 0 ? options : {}; + const interval = options.interval || 1000; + const minInterval = options.minInterval || 500; + const immediate = typeof options.immediate === 'boolean' ? options.immediate : false; + const clock = typeof options.clock === 'function' ? options.clock : now; + function wake() { + const currentTime = clock(); + const nextScheduledCallTime = lastCallTime + interval; + const timeUntilNextCall = nextScheduledCallTime - 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. + // This is possible in virtualized environments like AWS Lambda where our + // clock is unreliable. In these cases the timer is "running" but never + // actually completes, so we want to execute immediately and then attempt + // to reschedule. + if (timeUntilNextCall < 0) { + executeAndReschedule(); + return; } - var doc = createChunkDoc(_this.id, _this.n, remnant); - - // If the stream was aborted, do not write remnant - if (checkAborted(_this, callback)) { - return false; + // debounce multiple calls to wake within the `minInterval` + if (cannotBeExpedited) { + return; } - - _this.chunks.insertOne(doc, getWriteOptions(_this), function (error) { - if (error) { - return __handleError(_this, error); - } - --_this.state.outstandingRequests; - checkDone(_this); + // reschedule a call as soon as possible, ensuring the call never happens + // faster than the `minInterval` + if (timeUntilNextCall > minInterval) { + reschedule(minInterval); + cannotBeExpedited = true; + } + } + function stop() { + stopped = true; + if (timerId) { + clearTimeout(timerId); + timerId = undefined; + } + lastCallTime = 0; + cannotBeExpedited = false; + } + function reschedule(ms) { + if (stopped) + return; + if (timerId) { + clearTimeout(timerId); + } + timerId = setTimeout(executeAndReschedule, ms || interval); + } + function executeAndReschedule() { + cannotBeExpedited = false; + lastCallTime = clock(); + fn(err => { + if (err) + throw err; + reschedule(interval); }); - } - - /** - * @ignore - */ - - function checkAborted(_this, callback) { - if (_this.state.aborted) { - if (typeof callback === "function") { - callback(new Error("this stream has been aborted")); - } - return true; + } + if (immediate) { + executeAndReschedule(); + } + else { + lastCallTime = clock(); + reschedule(undefined); + } + return { wake, stop }; +} +exports.makeInterruptibleAsyncInterval = makeInterruptibleAsyncInterval; +/** @internal */ +function hasAtomicOperators(doc) { + if (Array.isArray(doc)) { + for (const document of doc) { + if (hasAtomicOperators(document)) { + return true; + } } return false; - } - - /***/ - }, - - /***/ 3890: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - var Binary = __nccwpck_require__(3994).BSON.Binary, - ObjectID = __nccwpck_require__(3994).BSON.ObjectID; - - var Buffer = __nccwpck_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"); + } + const keys = Object.keys(doc); + return keys.length > 0 && keys[0][0] === '$'; +} +exports.hasAtomicOperators = hasAtomicOperators; +/** + * Merge inherited properties from parent into options, prioritizing values from options, + * then values from parent. + * @internal + */ +function resolveOptions(parent, options) { + var _a, _b, _c; + const result = Object.assign({}, options, (0, bson_1.resolveBSONOptions)(options, parent)); + // Users cannot pass a readConcern/writeConcern to operations in a transaction + const session = options === null || options === void 0 ? void 0 : options.session; + if (!(session === null || session === void 0 ? void 0 : session.inTransaction())) { + const readConcern = (_a = read_concern_1.ReadConcern.fromOptions(options)) !== null && _a !== void 0 ? _a : parent === null || parent === void 0 ? void 0 : parent.readConcern; + if (readConcern) { + result.readConcern = readConcern; + } + const writeConcern = (_b = write_concern_1.WriteConcern.fromOptions(options)) !== null && _b !== void 0 ? _b : parent === null || parent === void 0 ? void 0 : parent.writeConcern; + if (writeConcern) { + result.writeConcern = writeConcern; } - - // 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 ""; + } + const readPreference = (_c = read_preference_1.ReadPreference.fromOptions(options)) !== null && _c !== void 0 ? _c : parent === null || parent === void 0 ? void 0 : parent.readPreference; + if (readPreference) { + result.readPreference = readPreference; + } + return result; +} +exports.resolveOptions = resolveOptions; +function isSuperset(set, subset) { + set = Array.isArray(set) ? new Set(set) : set; + subset = Array.isArray(subset) ? new Set(subset) : subset; + for (const elem of subset) { + if (!set.has(elem)) { + return false; } - }; - - 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; + } + return true; +} +exports.isSuperset = isSuperset; +/** Returns the items that are uniquely in setA */ +function setDifference(setA, setB) { + const difference = new Set(setA); + for (const elem of setB) { + difference.delete(elem); + } + return difference; +} +exports.setDifference = setDifference; +function isRecord(value, requiredKeys = undefined) { + const toString = Object.prototype.toString; + const hasOwnProperty = Object.prototype.hasOwnProperty; + const isObject = (v) => toString.call(v) === '[object Object]'; + if (!isObject(value)) { + return false; + } + const ctor = value.constructor; + if (ctor && ctor.prototype) { + if (!isObject(ctor.prototype)) { + return false; + } + // Check to see if some method exists from the Object exists + if (!hasOwnProperty.call(ctor.prototype, 'isPrototypeOf')) { + return false; + } + } + if (requiredKeys) { + const keys = Object.keys(value); + return isSuperset(keys, requiredKeys); + } + return true; +} +exports.isRecord = isRecord; +/** + * Make a deep copy of an object + * + * NOTE: This is not meant to be the perfect implementation of a deep copy, + * but instead something that is good enough for the purposes of + * command monitoring. + */ +function deepCopy(value) { + if (value == null) { + return value; + } + else if (Array.isArray(value)) { + return value.map(item => deepCopy(item)); + } + else if (isRecord(value)) { + const res = {}; + for (const key in value) { + res[key] = deepCopy(value[key]); + } + return res; + } + const ctor = value.constructor; + if (ctor) { + switch (ctor.name.toLowerCase()) { + case 'date': + return new ctor(Number(value)); + case 'map': + return new Map(value); + case 'set': + return new Set(value); + case 'buffer': + return Buffer.from(value); + } + } + return value; +} +exports.deepCopy = deepCopy; +/** @internal */ +const kBuffers = Symbol('buffers'); +/** @internal */ +const kLength = Symbol('length'); +/** + * A pool of Buffers which allow you to read them as if they were one + * @internal + */ +class BufferPool { + constructor() { + this[kBuffers] = []; + this[kLength] = 0; + } + get length() { + return this[kLength]; + } + /** Adds a buffer to the internal buffer pool list */ + append(buffer) { + this[kBuffers].push(buffer); + this[kLength] += buffer.length; + } + /** Returns the requested number of bytes without consuming them */ + peek(size) { + return this.read(size, false); + } + /** Reads the requested number of bytes, optionally consuming them */ + read(size, consume = true) { + if (typeof size !== 'number' || size < 0) { + throw new error_1.MongoInvalidArgumentError('Argument "size" must be a non-negative number'); + } + if (size > this[kLength]) { + return Buffer.alloc(0); + } + let result; + // read the whole buffer + if (size === this.length) { + result = Buffer.concat(this[kBuffers]); + if (consume) { + this[kBuffers] = []; + this[kLength] = 0; + } + } + // size is within first buffer, no need to concat + else if (size <= this[kBuffers][0].length) { + result = this[kBuffers][0].slice(0, size); + if (consume) { + this[kBuffers][0] = this[kBuffers][0].slice(size); + this[kLength] -= size; + } } - }; - - /** - * 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); + // size is beyond first buffer, need to track and copy + else { + result = Buffer.allocUnsafe(size); + let idx; + let offset = 0; + let bytesToCopy = size; + for (idx = 0; idx < this[kBuffers].length; ++idx) { + let bytesCopied; + if (bytesToCopy > this[kBuffers][idx].length) { + bytesCopied = this[kBuffers][idx].copy(result, offset, 0); + offset += bytesCopied; } - ); - }); - } 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, - __nccwpck_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 = __nccwpck_require__(3890); - const ObjectID = __nccwpck_require__(3994).BSON.ObjectID; - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const Buffer = __nccwpck_require__(1867).Buffer; - const fs = __nccwpck_require__(5747); - const f = __nccwpck_require__(1669).format; - const util = __nccwpck_require__(1669); - const MongoError = __nccwpck_require__(3994).MongoError; - const inherits = util.inherits; - const Duplex = __nccwpck_require__(2413).Duplex; - const shallowClone = __nccwpck_require__(1371).shallowClone; - const executeLegacyOperation = - __nccwpck_require__(1371).executeLegacyOperation; - const deprecate = __nccwpck_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] **Deprecated** The write concern. Use writeConcern instead. - * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @param {boolean} [options.fsync=false] **Deprecated** Specify a file sync write concern. Use writeConcern instead. - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @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 - ) - ) { - // eslint-disable-next-line no-self-assign - this.internalChunkSize = this.internalChunkSize; - } else { - this.internalChunkSize = value; + else { + bytesCopied = this[kBuffers][idx].copy(result, offset, 0, bytesToCopy); + if (consume) { + this[kBuffers][idx] = this[kBuffers][idx].slice(bytesCopied); + } + offset += bytesCopied; + break; + } + bytesToCopy -= bytesCopied; + } + // compact the internal buffer array + if (consume) { + this[kBuffers] = this[kBuffers].slice(idx); + this[kLength] -= size; } - }, - }); - - 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); - }); + return result; + } +} +exports.BufferPool = BufferPool; +/** @public */ +class HostAddress { + constructor(hostString) { + const escapedHost = hostString.split(' ').join('%20'); // escape spaces, for socket path hosts + const { hostname, port } = new url_1.URL(`mongodb://${escapedHost}`); + if (hostname.endsWith('.sock')) { + // heuristically determine if we're working with a domain socket + this.socketPath = decodeURIComponent(hostname); } - }; - - /** - * 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 if (typeof hostname === 'string') { + this.isIPv6 = false; + let normalized = decodeURIComponent(hostname).toLowerCase(); + if (normalized.startsWith('[') && normalized.endsWith(']')) { + this.isIPv6 = true; + normalized = normalized.substring(1, hostname.length - 1); + } + this.host = normalized.toLowerCase(); + if (typeof port === 'number') { + this.port = port; + } + else if (typeof port === 'string' && port !== '') { + this.port = Number.parseInt(port, 10); + } + else { + this.port = 27017; + } + if (this.port === 0) { + throw new error_1.MongoParseError('Invalid port (zero) with hostname'); } - ); - } 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"); + else { + throw new error_1.MongoInvalidArgumentError('Either socketPath or host must be defined.'); } - }; - - /** - * 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; + Object.freeze(this); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new HostAddress('${this.toString(true)}')`; + } + /** + * @param ipv6Brackets - optionally request ipv6 bracket notation required for connection strings + */ + toString(ipv6Brackets = false) { + if (typeof this.host === 'string') { + if (this.isIPv6 && ipv6Brackets) { + return `[${this.host}]:${this.port}`; + } + return `${this.host}:${this.port}`; } + return `${this.socketPath}`; + } + static fromString(s) { + return new HostAddress(s); + } + static fromSrvRecord({ name, port }) { + return HostAddress.fromString(`${name}:${port}`); + } +} +exports.HostAddress = HostAddress; +exports.DEFAULT_PK_FACTORY = { + // We prefer not to rely on ObjectId having a createPk method + createPk() { + return new bson_1.ObjectId(); + } +}; +/** + * When the driver used emitWarning the code will be equal to this. + * @public + * + * @example + * ```js + * process.on('warning', (warning) => { + * if (warning.code === MONGODB_WARNING_CODE) console.error('Ah an important warning! :)') + * }) + * ``` + */ +exports.MONGODB_WARNING_CODE = 'MONGODB DRIVER'; +/** @internal */ +function emitWarning(message) { + return process.emitWarning(message, { code: exports.MONGODB_WARNING_CODE }); +} +exports.emitWarning = emitWarning; +const emittedWarnings = new Set(); +/** + * Will emit a warning once for the duration of the application. + * Uses the message to identify if it has already been emitted + * so using string interpolation can cause multiple emits + * @internal + */ +function emitWarningOnce(message) { + if (!emittedWarnings.has(message)) { + emittedWarnings.add(message); + return emitWarning(message); + } +} +exports.emitWarningOnce = emitWarningOnce; +/** + * Takes a JS object and joins the values into a string separated by ', ' + */ +function enumToString(en) { + return Object.values(en).join(', '); +} +exports.enumToString = enumToString; +/** + * Determine if a server supports retryable writes. + * + * @internal + */ +function supportsRetryableWrites(server) { + return (!!server.loadBalanced || + (server.description.maxWireVersion >= 6 && + !!server.description.logicalSessionTimeoutMinutes && + server.description.type !== common_1.ServerType.Standalone)); +} +exports.supportsRetryableWrites = supportsRetryableWrites; +function parsePackageVersion({ version }) { + const [major, minor, patch] = version.split('.').map((n) => Number.parseInt(n, 10)); + return { major, minor, patch }; +} +exports.parsePackageVersion = parsePackageVersion; +/** + * Fisher–Yates Shuffle + * + * Reference: https://bost.ocks.org/mike/shuffle/ + * @param sequence - items to be shuffled + * @param limit - Defaults to `0`. If nonzero shuffle will slice the randomized array e.g, `.slice(0, limit)` otherwise will return the entire randomized array. + */ +function shuffle(sequence, limit = 0) { + const items = Array.from(sequence); // shallow copy in order to never shuffle the input + if (limit > items.length) { + throw new error_1.MongoRuntimeError('Limit must be less than the number of items'); + } + let remainingItemsToShuffle = items.length; + const lowerBound = limit % items.length === 0 ? 1 : items.length - limit; + while (remainingItemsToShuffle > lowerBound) { + // Pick a remaining element + const randomIndex = Math.floor(Math.random() * remainingItemsToShuffle); + remainingItemsToShuffle -= 1; + // And swap it with the current element + const swapHold = items[remainingItemsToShuffle]; + items[remainingItemsToShuffle] = items[randomIndex]; + items[randomIndex] = swapHold; + } + return limit % items.length === 0 ? items : items.slice(lowerBound); +} +exports.shuffle = shuffle; +//# sourceMappingURL=utils.js.map - 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); +/***/ 2481: +/***/ ((__unused_webpack_module, exports) => { - // 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; - } +"use strict"; - 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; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WriteConcern = exports.WRITE_CONCERN_KEYS = void 0; +exports.WRITE_CONCERN_KEYS = ['w', 'wtimeout', 'j', 'journal', 'fsync']; +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @public + * + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ +class WriteConcern { + /** + * Constructs a WriteConcern from the write concern properties. + * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. + * @param wtimeout - specify a time limit to prevent write operations from blocking indefinitely + * @param j - request acknowledgment that the write operation has been written to the on-disk journal + * @param fsync - equivalent to the j option + */ + constructor(w, wtimeout, j, fsync) { + if (w != null) { + if (!Number.isNaN(Number(w))) { + this.w = Number(w); + } + else { + 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. */ + static fromOptions(options, inherit) { + if (options == null) + return undefined; + inherit = inherit !== null && inherit !== void 0 ? inherit : {}; + let opts; + if (typeof options === 'string' || typeof options === 'number') { + opts = { w: options }; + } + else if (options instanceof WriteConcern) { + opts = options; + } + else { + opts = options.writeConcern; + } + const parentOpts = inherit instanceof WriteConcern ? inherit : inherit.writeConcern; + const { w = undefined, wtimeout = undefined, j = undefined, fsync = undefined, journal = undefined, wtimeoutMS = undefined } = { + ...parentOpts, + ...opts + }; + if (w != null || + wtimeout != null || + wtimeoutMS != null || + j != null || + journal != null || + fsync != null) { + return new WriteConcern(w, wtimeout !== null && wtimeout !== void 0 ? wtimeout : wtimeoutMS, j !== null && j !== void 0 ? j : journal, fsync); + } + return undefined; + } +} +exports.WriteConcern = WriteConcern; +//# sourceMappingURL=write_concern.js.map - 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; - } +/***/ 4740: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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, - }) - ); - } - }; +"use strict"; - /** - * 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"); - }; +/** + * Export lib/mongoose + * + */ - /** - * 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); - } +module.exports = __nccwpck_require__(1028); - 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"); - }; +/***/ 4336: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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 } - ); - }; +"use strict"; - 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; - } +/*! + * Module dependencies + */ - callback(null, items); - }); - }; +const AggregationCursor = __nccwpck_require__(3890); +const Query = __nccwpck_require__(1615); +const applyGlobalMaxTimeMS = __nccwpck_require__(7428); +const getConstructorName = __nccwpck_require__(7323); +const prepareDiscriminatorPipeline = __nccwpck_require__(9337); +const promiseOrCallback = __nccwpck_require__(4046); +const stringifyFunctionOperators = __nccwpck_require__(7765); +const util = __nccwpck_require__(1669); +const utils = __nccwpck_require__(9232); +const read = Query.prototype.read; +const readConcern = Query.prototype.readConcern; + +/** + * Aggregate constructor used for building aggregation pipelines. Do not + * instantiate this class directly, use [Model.aggregate()](/docs/api.html#model_Model.aggregate) instead. + * + * ####Example: + * + * const aggregate = Model.aggregate([ + * { $project: { a: 1, b: 1 } }, + * { $skip: 5 } + * ]); + * + * Model. + * aggregate([{ $match: { age: { $gte: 21 }}}]). + * unwind('tags'). + * exec(callback); + * + * ####Note: + * + * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). + * - Mongoose does **not** cast pipeline stages. The below will **not** work unless `_id` is a string in the database + * + * ```javascript + * new Aggregate([{ $match: { _id: '00000000000000000000000a' } }]); + * // Do this instead to cast to an ObjectId + * new Aggregate([{ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } }]); + * ``` + * + * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ + * @see driver http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#aggregate + * @param {Array} [pipeline] aggregation pipeline as an array of objects + * @param {Model} [model] the model to use with this aggregate. + * @api public + */ - /** - * 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 || {}; +function Aggregate(pipeline, model) { + this._pipeline = []; + this._model = model; + this.options = {}; - return executeLegacyOperation( - this.db.s.topology, - rewind, - [this, options, callback], - { - skipSessions: true, - } - ); - }; + if (arguments.length === 1 && util.isArray(pipeline)) { + this.append.apply(this, pipeline); + } +} - 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); - } - }; +/** + * Contains options passed down to the [aggregate command](https://docs.mongodb.com/manual/reference/command/aggregate/). + * Supported options are: + * + * - `readPreference` + * - [`cursor`](./api.html#aggregate_Aggregate-cursor) + * - [`explain`](./api.html#aggregate_Aggregate-explain) + * - [`allowDiskUse`](./api.html#aggregate_Aggregate-allowDiskUse) + * - `maxTimeMS` + * - `bypassDocumentValidation` + * - `raw` + * - `promoteLongs` + * - `promoteValues` + * - `promoteBuffers` + * - [`collation`](./api.html#aggregate_Aggregate-collation) + * - `comment` + * - [`session`](./api.html#aggregate_Aggregate-session) + * + * @property options + * @memberOf Aggregate + * @api public + */ - /** - * 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 } - ); - }; +Aggregate.prototype.options; - 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; +/** + * Get/set the model that this aggregation will execute on. + * + * ####Example: + * const aggregate = MyModel.aggregate([{ $match: { answer: 42 } }]); + * aggregate.model() === MyModel; // true + * + * // Change the model. There's rarely any reason to do this. + * aggregate.model(SomeOtherModel); + * aggregate.model() === SomeOtherModel; // true + * + * @param {Model} [model] set the model associated with this aggregate. + * @return {Model} + * @api public + */ - 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); - } +Aggregate.prototype.model = function(model) { + if (arguments.length === 0) { + return this._model; + } - // 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 - ); - } - } - } - ); - }; + this._model = model; + if (model.schema != null) { + if (this.options.readPreference == null && + model.schema.options.read != null) { + this.options.readPreference = model.schema.options.read; + } + if (this.options.collation == null && + model.schema.options.collation != null) { + this.options.collation = model.schema.options.collation; + } + } - /** - * 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); - }); - }; + return model; +}; - /** - * 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 } - ); - }; +/** + * Appends new operators to this aggregate pipeline + * + * ####Examples: + * + * aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); + * + * // or pass an array + * const pipeline = [{ $match: { daw: 'Logic Audio X' }} ]; + * aggregate.append(pipeline); + * + * @param {Object} ops operator(s) to append + * @return {Aggregate} + * @api public + */ - 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, - }) - ); - } +Aggregate.prototype.append = function() { + const args = (arguments.length === 1 && util.isArray(arguments[0])) + ? arguments[0] + : utils.args(arguments); - var seekLocationFinal = - seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; - var finalPosition = position; - var targetPosition = 0; + if (!args.every(isOperator)) { + throw new Error('Arguments must be aggregate pipeline operators'); + } - // 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; - } + this._pipeline = this._pipeline.concat(args); - // 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")); + return this; +}; - // Set the current chunk - self.currentChunk = chunk; - self.position = targetPosition; - self.currentChunk.position = self.position % self.chunkSize; - callback(err, self); - }); - }; +/** + * Appends a new $addFields operator to this aggregate pipeline. + * Requires MongoDB v3.4+ to work + * + * ####Examples: + * + * // adding new fields based on existing fields + * aggregate.addFields({ + * newField: '$b.nested' + * , plusTen: { $add: ['$val', 10]} + * , sub: { + * name: '$a' + * } + * }) + * + * // etc + * aggregate.addFields({ salary_k: { $divide: [ "$salary", 1000 ] } }); + * + * @param {Object} arg field specification + * @see $addFields https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/ + * @return {Aggregate} + * @api public + */ +Aggregate.prototype.addFields = function(arg) { + const fields = {}; + if (typeof arg === 'object' && !util.isArray(arg)) { + Object.keys(arg).forEach(function(field) { + fields[field] = arg[field]; + }); + } else { + throw new Error('Invalid addFields() argument. Must be an object'); + } + return this.append({ $addFields: fields }); +}; - seekChunk(); - }; +/** + * Appends a new $project operator to this aggregate pipeline. + * + * Mongoose query [selection syntax](#query_Query-select) is also supported. + * + * ####Examples: + * + * // include a, include b, exclude _id + * aggregate.project("a b -_id"); + * + * // or you may use object notation, useful when + * // you have keys already prefixed with a "-" + * aggregate.project({a: 1, b: 1, _id: 0}); + * + * // reshaping documents + * aggregate.project({ + * newField: '$b.nested' + * , plusTen: { $add: ['$val', 10]} + * , sub: { + * name: '$a' + * } + * }) + * + * // etc + * aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } }); + * + * @param {Object|String} arg field specification + * @see projection http://docs.mongodb.org/manual/reference/aggregation/project/ + * @return {Aggregate} + * @api public + */ - /** - * @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 - ); - } +Aggregate.prototype.project = function(arg) { + const fields = {}; - // 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); - } - ); - } - } + if (typeof arg === 'object' && !util.isArray(arg)) { + Object.keys(arg).forEach(function(field) { + fields[field] = arg[field]; + }); + } else if (arguments.length === 1 && typeof arg === 'string') { + arg.split(/\s+/).forEach(function(field) { + if (!field) { + return; + } + const include = field[0] === '-' ? 0 : 1; + if (include === 0) { + field = field.substring(1); + } + fields[field] = include; + }); + } else { + throw new Error('Invalid project() argument. Must be string or object'); + } - // only pass error to callback once - function error(err) { - if (error.err) return; - callback((error.err = err)); - } - }; + return this.append({ $project: fields }); +}; - /** - * @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); +/** + * Appends a new custom $group operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.group({ _id: "$department" }); + * + * @see $group http://docs.mongodb.org/manual/reference/aggregation/group/ + * @method group + * @memberOf Aggregate + * @instance + * @param {Object} arg $group operator contents + * @return {Aggregate} + * @api public + */ - // Update the position for the gridstore - self.position = self.position + buffer.length; - // Total number of chunks to write - var numberOfChunksToWrite = chunksToWrite.length; +/** + * Appends a new custom $match operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.match({ department: { $in: [ "sales", "engineering" ] } }); + * + * @see $match http://docs.mongodb.org/manual/reference/aggregation/match/ + * @method match + * @memberOf Aggregate + * @instance + * @param {Object} arg $match operator contents + * @return {Aggregate} + * @api public + */ - for (var i = 0; i < chunksToWrite.length; i++) { - chunksToWrite[i].save({}, function (err) { - if (err) return callback(err); +/** + * Appends a new $skip operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.skip(10); + * + * @see $skip http://docs.mongodb.org/manual/reference/aggregation/skip/ + * @method skip + * @memberOf Aggregate + * @instance + * @param {Number} num number of records to skip before next stage + * @return {Aggregate} + * @api public + */ - numberOfChunksToWrite = numberOfChunksToWrite - 1; +/** + * Appends a new $limit operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.limit(10); + * + * @see $limit http://docs.mongodb.org/manual/reference/aggregation/limit/ + * @method limit + * @memberOf Aggregate + * @instance + * @param {Number} num maximum number of records to pass to the next stage + * @return {Aggregate} + * @api public + */ - if (numberOfChunksToWrite <= 0) { - // We care closing the file before returning - if (finalClose) { - return self.close(function (err) { - callback(err, self); - }); - } +/** + * Appends a new $geoNear operator to this aggregate pipeline. + * + * ####NOTE: + * + * **MUST** be used as the first operator in the pipeline. + * + * ####Examples: + * + * aggregate.near({ + * near: [40.724, -73.997], + * distanceField: "dist.calculated", // required + * maxDistance: 0.008, + * query: { type: "public" }, + * includeLocs: "dist.location", + * uniqueDocs: true, + * num: 5 + * }); + * + * @see $geoNear http://docs.mongodb.org/manual/reference/aggregation/geoNear/ + * @method near + * @memberOf Aggregate + * @instance + * @param {Object} arg + * @return {Aggregate} + * @api public + */ - // 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); - } - } - }; +Aggregate.prototype.near = function(arg) { + const op = {}; + op.$geoNear = arg; + return this.append(op); +}; - /** - * 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, - }; +/*! + * define methods + */ - var md5Command = { filemd5: self.fileId, root: self.root }; - self.db.command(md5Command, function (err, results) { - if (err) return callback(err); +'group match skip limit out'.split(' ').forEach(function($operator) { + Aggregate.prototype[$operator] = function(arg) { + const op = {}; + op['$' + $operator] = arg; + return this.append(op); + }; +}); - mongoObject.md5 = results.md5; - callback(null, mongoObject); - }); - }; +/** + * Appends new custom $unwind operator(s) to this aggregate pipeline. + * + * Note that the `$unwind` operator requires the path name to start with '$'. + * Mongoose will prepend '$' if the specified field doesn't start '$'. + * + * ####Examples: + * + * aggregate.unwind("tags"); + * aggregate.unwind("a", "b", "c"); + * aggregate.unwind({ path: '$tags', preserveNullAndEmptyArrays: true }); + * + * @see $unwind http://docs.mongodb.org/manual/reference/aggregation/unwind/ + * @param {String|Object} fields the field(s) to unwind, either as field names or as [objects with options](https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/#document-operand-with-options). If passing a string, prefixing the field name with '$' is optional. If passing an object, `path` must start with '$'. + * @return {Aggregate} + * @api public + */ - /** - * 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); +Aggregate.prototype.unwind = function() { + const args = utils.args(arguments); - var finalChunk = chunk == null ? {} : chunk; - callback(null, new Chunk(self, finalChunk, self.writeConcern)); - } - ); - }; + const res = []; + for (const arg of args) { + if (arg && typeof arg === 'object') { + res.push({ $unwind: arg }); + } else if (typeof arg === 'string') { + res.push({ + $unwind: (arg && arg.startsWith('$')) ? arg : '$' + arg + }); + } else { + throw new Error('Invalid arg "' + arg + '" to unwind(), ' + + 'must be string or object'); + } + } - /** - * @ignore - */ - var lastChunkNumber = function (self) { - return Math.floor((self.length ? self.length - 1 : 0) / self.chunkSize); - }; + return this.append.apply(this, res); +}; - /** - * 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); - } - }; +/** + * Appends a new $replaceRoot operator to this aggregate pipeline. + * + * Note that the `$replaceRoot` operator requires field strings to start with '$'. + * If you are passing in a string Mongoose will prepend '$' if the specified field doesn't start '$'. + * If you are passing in an object the strings in your expression will not be altered. + * + * ####Examples: + * + * aggregate.replaceRoot("user"); + * + * aggregate.replaceRoot({ x: { $concat: ['$this', '$that'] } }); + * + * @see $replaceRoot https://docs.mongodb.org/manual/reference/operator/aggregation/replaceRoot + * @param {String|Object} the field or document which will become the new root document + * @return {Aggregate} + * @api public + */ - /** - * 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 || {}; +Aggregate.prototype.replaceRoot = function(newRoot) { + let ret; - return executeLegacyOperation( - db.s.topology, - exists, - [db, fileIdObject, rootCollection, options, callback], - { skipSessions: true } - ); - }; + if (typeof newRoot === 'string') { + ret = newRoot.startsWith('$') ? newRoot : '$' + newRoot; + } else { + ret = newRoot; + } - 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); - } - ); - } - ); - }; + return this.append({ + $replaceRoot: { + newRoot: ret + } + }); +}; - /** - * 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 || {}; +/** + * Appends a new $count operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.count("userCount"); + * + * @see $count https://docs.mongodb.org/manual/reference/operator/aggregation/count + * @param {String} the name of the count field + * @return {Aggregate} + * @api public + */ - return executeLegacyOperation( - db.s.topology, - list, - [db, rootCollection, options, callback], - { - skipSessions: true, - } - ); - }; +Aggregate.prototype.count = function(countName) { + return this.append({ $count: countName }); +}; - 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); - } - }); - } - ); - } - ); - }; +/** + * Appends a new $sortByCount operator to this aggregate pipeline. Accepts either a string field name + * or a pipeline object. + * + * Note that the `$sortByCount` operator requires the new root to start with '$'. + * Mongoose will prepend '$' if the specified field name doesn't start with '$'. + * + * ####Examples: + * + * aggregate.sortByCount('users'); + * aggregate.sortByCount({ $mergeObjects: [ "$employee", "$business" ] }) + * + * @see $sortByCount https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/ + * @param {Object|String} arg + * @return {Aggregate} this + * @api public + */ - /** - * 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 || {}; +Aggregate.prototype.sortByCount = function(arg) { + if (arg && typeof arg === 'object') { + return this.append({ $sortByCount: arg }); + } else if (typeof arg === 'string') { + return this.append({ + $sortByCount: (arg && arg.startsWith('$')) ? arg : '$' + arg + }); + } else { + throw new TypeError('Invalid arg "' + arg + '" to sortByCount(), ' + + 'must be string or object'); + } +}; - return executeLegacyOperation( - db.s.topology, - readStatic, - [db, name, length, offset, options, callback], - { skipSessions: true } - ); - }; +/** + * Appends new custom $lookup operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' }); + * + * @see $lookup https://docs.mongodb.org/manual/reference/operator/aggregation/lookup/#pipe._S_lookup + * @param {Object} options to $lookup as described in the above link + * @return {Aggregate}* @api public + */ - 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 - ); +Aggregate.prototype.lookup = function(options) { + return this.append({ $lookup: options }); +}; - if (offset != null) { - gridStore.seek(offset, function (err, gridStore) { - if (err) return callback(err); - gridStore.read(length, callback); - }); - } else { - gridStore.read(length, callback); - } - }); - }; +/** + * Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection. + * + * Note that graphLookup can only consume at most 100MB of memory, and does not allow disk use even if `{ allowDiskUse: true }` is specified. + * + * #### Examples: + * // Suppose we have a collection of courses, where a document might look like `{ _id: 0, name: 'Calculus', prerequisite: 'Trigonometry'}` and `{ _id: 0, name: 'Trigonometry', prerequisite: 'Algebra' }` + * aggregate.graphLookup({ from: 'courses', startWith: '$prerequisite', connectFromField: 'prerequisite', connectToField: 'name', as: 'prerequisites', maxDepth: 3 }) // this will recursively search the 'courses' collection up to 3 prerequisites + * + * @see $graphLookup https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/#pipe._S_graphLookup + * @param {Object} options to $graphLookup as described in the above link + * @return {Aggregate} + * @api public + */ - /** - * 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 || {}; +Aggregate.prototype.graphLookup = function(options) { + const cloneOptions = {}; + if (options) { + if (!utils.isObject(options)) { + throw new TypeError('Invalid graphLookup() argument. Must be an object.'); + } - return executeLegacyOperation( - db.s.topology, - readlinesStatic, - [db, name, separator, options, callback], - { skipSessions: true } - ); - }; + utils.mergeClone(cloneOptions, options); + const startWith = cloneOptions.startWith; - 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); - }); - }; + if (startWith && typeof startWith === 'string') { + cloneOptions.startWith = cloneOptions.startWith.startsWith('$') ? + cloneOptions.startWith : + '$' + cloneOptions.startWith; + } - /** - * 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 this.append({ $graphLookup: cloneOptions }); +}; - return executeLegacyOperation( - db.s.topology, - unlinkStatic, - [this, db, names, options, callback], - { - skipSessions: true, - } - ); - }; +/** + * Appends new custom $sample operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.sample(3); // Add a pipeline that picks 3 random documents + * + * @see $sample https://docs.mongodb.org/manual/reference/operator/aggregation/sample/#pipe._S_sample + * @param {Number} size number of random documents to pick + * @return {Aggregate} + * @api public + */ - 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); - } - ); - }); - }); - }); - } - }; +Aggregate.prototype.sample = function(size) { + return this.append({ $sample: { size: size } }); +}; - /** - * @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 - ); - } - }; +/** + * Appends a new $sort operator to this aggregate pipeline. + * + * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. + * + * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. + * + * ####Examples: + * + * // these are equivalent + * aggregate.sort({ field: 'asc', test: -1 }); + * aggregate.sort('field -test'); + * + * @see $sort http://docs.mongodb.org/manual/reference/aggregation/sort/ + * @param {Object|String} arg + * @return {Aggregate} this + * @api public + */ - /** - * @ignore - */ - var _setWriteConcernHash = function (options) { - const baseOptions = Object.assign(options, options.writeConcern); - var finalOptions = {}; - if (baseOptions.w != null) finalOptions.w = baseOptions.w; - if (baseOptions.journal === true) finalOptions.j = baseOptions.journal; - if (baseOptions.j === true) finalOptions.j = baseOptions.j; - if (baseOptions.fsync === true) finalOptions.fsync = baseOptions.fsync; - if (baseOptions.wtimeout != null) - finalOptions.wtimeout = baseOptions.wtimeout; - return finalOptions; - }; +Aggregate.prototype.sort = function(arg) { + // TODO refactor to reuse the query builder logic - /** - * @ignore - */ - var _getWriteConcern = function (self, options) { - // Final options - var finalOptions = { w: 1 }; - options = options || {}; + const sort = {}; - // Local options verification - if ( - options.writeConcern != null || - 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.writeConcern != null || - 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 }; - } + if (getConstructorName(arg) === 'Object') { + const desc = ['desc', 'descending', -1]; + Object.keys(arg).forEach(function(field) { + // If sorting by text score, skip coercing into 1/-1 + if (arg[field] instanceof Object && arg[field].$meta) { + sort[field] = arg[field]; + return; + } + sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1; + }); + } else if (arguments.length === 1 && typeof arg === 'string') { + arg.split(/\s+/).forEach(function(field) { + if (!field) { + return; + } + const ascend = field[0] === '-' ? -1 : 1; + if (ascend === -1) { + field = field.substring(1); + } + sort[field] = ascend; + }); + } else { + throw new TypeError('Invalid sort() argument. Must be a string or object.'); + } - // 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 this.append({ $sort: sort }); +}; - // Return the options - return finalOptions; - }; +/** + * Appends new $unionWith operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.unionWith({ coll: 'users', pipeline: [ { $match: { _id: 1 } } ] }); + * + * @see $unionWith https://docs.mongodb.com/manual/reference/operator/aggregation/unionWith + * @param {Object} options to $unionWith query as described in the above link + * @return {Aggregate}* @api public + */ - /** - * 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; - }; +Aggregate.prototype.unionWith = function(options) { + return this.append({ $unionWith: options }); +}; - // - // Inherit duplex - inherits(GridStoreStream, Duplex); - GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; +/** + * Sets the readPreference option for the aggregation query. + * + * ####Example: + * + * await Model.aggregate(pipeline).read('primaryPreferred'); + * + * @param {String} pref one of the listed preference options or their aliases + * @param {Array} [tags] optional tags for this query + * @return {Aggregate} this + * @api public + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences + */ - // Set up override - GridStoreStream.prototype.pipe = function (destination) { - var self = this; +Aggregate.prototype.read = function(pref, tags) { + if (!this.options) { + this.options = {}; + } + read.call(this, pref, tags); + return 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]); - } +/** + * Sets the readConcern level for the aggregation query. + * + * ####Example: + * + * await Model.aggregate(pipeline).readConcern('majority'); + * + * @param {String} level one of the listed read concern level or their aliases + * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/ + * @return {Aggregate} this + * @api public + */ - return destination; - }; +Aggregate.prototype.readConcern = function(level) { + if (!this.options) { + this.options = {}; + } + readConcern.call(this, level); + return this; +}; - // Called by stream - GridStoreStream.prototype._read = function () { - var self = this; +/** + * Appends a new $redact operator to this aggregate pipeline. + * + * If 3 arguments are supplied, Mongoose will wrap them with if-then-else of $cond operator respectively + * If `thenExpr` or `elseExpr` is string, make sure it starts with $$, like `$$DESCEND`, `$$PRUNE` or `$$KEEP`. + * + * ####Example: + * + * await Model.aggregate(pipeline).redact({ + * $cond: { + * if: { $eq: [ '$level', 5 ] }, + * then: '$$PRUNE', + * else: '$$DESCEND' + * } + * }); + * + * // $redact often comes with $cond operator, you can also use the following syntax provided by mongoose + * await Model.aggregate(pipeline).redact({ $eq: [ '$level', 5 ] }, '$$PRUNE', '$$DESCEND'); + * + * @param {Object} expression redact options or conditional expression + * @param {String|Object} [thenExpr] true case for the condition + * @param {String|Object} [elseExpr] false case for the condition + * @return {Aggregate} this + * @see $redact https://docs.mongodb.com/manual/reference/operator/aggregation/redact/ + * @api public + */ - var read = function () { - // Read data - self.gs.read(length, function (err, buffer) { - if (err && !self.endCalled) return self.emit("error", err); +Aggregate.prototype.redact = function(expression, thenExpr, elseExpr) { + if (arguments.length === 3) { + if ((typeof thenExpr === 'string' && !thenExpr.startsWith('$$')) || + (typeof elseExpr === 'string' && !elseExpr.startsWith('$$'))) { + throw new Error('If thenExpr or elseExpr is string, it must start with $$. e.g. $$DESCEND, $$PRUNE, $$KEEP'); + } - // 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)); - } + expression = { + $cond: { + if: expression, + then: thenExpr, + else: elseExpr + } + }; + } else if (arguments.length !== 1) { + throw new TypeError('Invalid arguments'); + } - // Finished reading - if (self.totalBytesToRead <= 0) { - self.endCalled = true; - } - }); - }; + return this.append({ $redact: expression }); +}; - // 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(); - } - }; +/** + * Execute the aggregation with explain + * + * ####Example: + * + * Model.aggregate(..).explain(callback) + * + * @param {Function} callback + * @return {Promise} + */ - GridStoreStream.prototype.destroy = function () { - this.pause(); - this.endCalled = true; - this.gs.close(); - this.emit("end"); - }; +Aggregate.prototype.explain = function(callback) { + const model = this._model; - 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; - } - }; + return promiseOrCallback(callback, cb => { + if (!this._pipeline.length) { + const err = new Error('Aggregate has empty pipeline'); + return cb(err); + } - 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"); - }); - }); - } + prepareDiscriminatorPipeline(this._pipeline, this._model.schema); - self.gs.close(function () { - if (typeof callback === "function") callback(); - self.emit("end"); + model.hooks.execPre('aggregate', this, error => { + if (error) { + const _opts = { error: error }; + return model.hooks.execPost('aggregate', this, [null], _opts, error => { + cb(error); }); - }; - - /** - * 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, - __nccwpck_require__ - ) => { - "use strict"; - - const ChangeStream = __nccwpck_require__(1117); - const Db = __nccwpck_require__(6662); - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const inherits = __nccwpck_require__(1669).inherits; - const MongoError = __nccwpck_require__(3994).MongoError; - const deprecate = __nccwpck_require__(1669).deprecate; - const WriteConcern = __nccwpck_require__(2481); - const MongoDBNamespace = __nccwpck_require__(1371).MongoDBNamespace; - const ReadPreference = __nccwpck_require__(4485); - const maybePromise = __nccwpck_require__(1371).maybePromise; - const NativeTopology = __nccwpck_require__(2632); - const connect = __nccwpck_require__(5210).connect; - const validOptions = __nccwpck_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 - */ - - /** - * @public - * @typedef AutoEncryptionOptions - * @property {MongoClient} [keyVaultClient] A `MongoClient` used to fetch keys from a key vault - * @property {string} [keyVaultNamespace] The namespace where keys are stored in the key vault - * @property {object} [kmsProviders] Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. - * @property {object} [schemaMap] A map of namespaces to a local JSON schema for encryption - * - * > **NOTE**: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server. - * > It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted. - * > Schemas supplied in the schemaMap only apply to configuring automatic encryption for client side encryption. - * > Other validation rules in the JSON schema will not be enforced by the driver and will result in an error. - * - * @property {object} [options] An optional hook to catch logging messages from the underlying encryption engine - * @property {object} [extraOptions] - * @property {boolean} [bypassAutoEncryption] - */ - - /** - * @typedef {object} MongoClientOptions - * @property {number} [poolSize] (**default**: 5) The maximum size of the individual server pool - * @property {boolean} [ssl] (**default**: false) Enable SSL connection. *deprecated* use `tls` variants - * @property {boolean} [sslValidate] (**default**: false) Validate mongod server certificate against Certificate Authority - * @property {buffer} [sslCA] (**default**: undefined) SSL Certificate store binary buffer *deprecated* use `tls` variants - * @property {buffer} [sslCert] (**default**: undefined) SSL Certificate binary buffer *deprecated* use `tls` variants - * @property {buffer} [sslKey] (**default**: undefined) SSL Key file binary buffer *deprecated* use `tls` variants - * @property {string} [sslPass] (**default**: undefined) SSL Certificate pass phrase *deprecated* use `tls` variants - * @property {buffer} [sslCRL] (**default**: undefined) SSL Certificate revocation list binary buffer *deprecated* use `tls` variants - * @property {boolean|function} [checkServerIdentity] (**default**: 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 - * @property {boolean} [tls] (**default**: false) Enable TLS connections - * @property {boolean} [tlsInsecure] (**default**: false) Relax TLS constraints, disabling validation - * @property {string} [tlsCAFile] A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection - * @property {string} [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 - * @property {string} [tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections - * @property {boolean} [tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid - * @property {boolean} [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 - * @property {boolean} [autoReconnect] (**default**: true) Enable autoReconnect for single server instances - * @property {boolean} [noDelay] (**default**: true) TCP Connection no delay - * @property {boolean} [keepAlive] (**default**: true) TCP Connection keep alive enabled - * @property {number} [keepAliveInitialDelay] (**default**: 120000) The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @property {number} [connectTimeoutMS] (**default**: 10000) How long to wait for a connection to be established before timing out - * @property {number} [socketTimeoutMS] (**default**: 0) How long a send or receive on a socket can take before timing out - * @property {number} [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 - * @property {number} [reconnectTries] (**default**: 30) Server attempt to reconnect #times - * @property {number} [reconnectInterval] (**default**: 1000) Server will wait # milliseconds between retries - * @property {boolean} [ha] (**default**: true) Control if high availability monitoring runs for Replicaset or Mongos proxies - * @property {number} [haInterval] (**default**: 10000) The High availability period for replicaset inquiry - * @property {string} [replicaSet] (**default**: undefined) The Replicaset set name - * @property {number} [secondaryAcceptableLatencyMS] (**default**: 15) Cutoff latency point in MS for Replicaset member selection - * @property {number} [acceptableLatencyMS] (**default**: 15) Cutoff latency point in MS for Mongos proxies selection - * @property {boolean} [connectWithNoPrimary] (**default**: false) Sets if the driver should connect even if no primary is available - * @property {string} [authSource] (**default**: undefined) Define the database to authenticate against - * @property {(number|string)} [w] **Deprecated** The write concern. Use writeConcern instead. - * @property {number} [wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead. - * @property {boolean} [j] (**default**: false) **Deprecated** Specify a journal write concern. Use writeConcern instead. - * @property {boolean} [fsync] (**default**: false) **Deprecated** Specify a file sync write concern. Use writeConcern instead. - * @property {object|WriteConcern} [writeConcern] Specify write concern settings. - * @property {boolean} [forceServerObjectId] (**default**: false) Force server to assign _id values instead of driver - * @property {boolean} [serializeFunctions] (**default**: false) Serialize functions on any object - * @property {Boolean} [ignoreUndefined] (**default**: false) Specify if the BSON serializer should ignore undefined fields - * @property {boolean} [raw] (**default**: false) Return document results as raw BSON buffers - * @property {number} [bufferMaxEntries] (**default**: -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 - * @property {(ReadPreference|string)} [readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) - * @property {object} [pkFactory] A primary key factory object for generation of custom _id keys - * @property {object} [promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @property {object} [readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) - * @property {ReadConcernLevel} [readConcern.level] (**default**: {Level: 'local'}) Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @property {number} [maxStalenessSeconds] (**default**: undefined) The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) - * @property {string} [loggerLevel] (**default**: undefined) The logging level (error/warn/info/debug) - * @property {object} [logger] (**default**: undefined) Custom logger object - * @property {boolean} [promoteValues] (**default**: true) Promotes BSON values to native types where possible, set to false to only receive wrapper types - * @property {boolean} [promoteBuffers] (**default**: false) Promotes Binary BSON values to native Node Buffers - * @property {boolean} [promoteLongs] (**default**: true) Promotes long values to number if they fit inside the 53 bits resolution - * * @param {boolean} [bsonRegExp] (**default**: false) By default, regex returned from MDB will be native to the language. Setting to true will ensure that a BSON.BSONRegExp object is returned. - * @property {boolean} [domainsEnabled] (**default**: false) Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit - * @property {object} [validateOptions] (**default**: false) Validate MongoClient passed in options for correctness - * @property {string} [appname] (**default**: 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 - * @property {string} [options.auth.user] (**default**: undefined) The username for auth - * @property {string} [options.auth.password] (**default**: undefined) The password for auth - * @property {string} [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. - * @property {object} [compression] Type of compression to use: snappy or zlib - * @property {array} [readPreferenceTags] Read preference tags - * @property {number} [numberOfRetries] (**default**: 5) The number of retries for a tailable cursor - * @property {boolean} [auto_reconnect] (**default**: true) Enable auto reconnecting for single server instances - * @property {boolean} [monitorCommands] (**default**: false) Enable command monitoring for this client - * @property {number} [minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections - * @property {boolean} [useNewUrlParser] (**default**: 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. - * @property {boolean} [useUnifiedTopology] Enables the new unified topology layer - * @property {number} [localThresholdMS] (**default**: 15) **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers - * @property {number} [serverSelectionTimeoutMS] (**default**: 30000) **Only applies to the unified topology** How long to block for server selection before throwing an error - * @property {number} [heartbeatFrequencyMS] (**default**: 10000) **Only applies to the unified topology** The frequency with which topology updates are scheduled - * @property {number} [maxPoolSize] (**default**: 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. - * @property {number} [minPoolSize] (**default**: 0) **Only applies to the unified topology** The minimum number of connections that MUST exist at any moment in a single connection pool. - * @property {number} [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. - * @property {number} [waitQueueTimeoutMS] (**default**: 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. - * @property {AutoEncryptionOptions} [autoEncryption] Optionally enable client side auto encryption. - * - * > Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error - * > (see [libmongocrypt: Auto Encryption Allow-List](https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.rst#libmongocrypt-auto-encryption-allow-list)). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts. - * > - * > Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://docs.mongodb.com/manual/reference/command/listCollections/#dbcmd.listCollections). - * > - * > If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true: - * > - AutoEncryptionOptions.keyVaultClient is not passed. - * > - AutoEncryptionOptions.bypassAutomaticEncryption is false. - * > If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted. - * - * @property {DriverInfoOptions} [driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver - * @property {boolean} [directConnection] (**default**: false) Enable directConnection - * @property {function} [callback] The command result callback - */ - - /** - * Creates a new MongoClient instance - * @constructor - * @extends {EventEmitter} - * @param {string} url The connection URI string - * @param {MongoClientOptions} [options] Optional settings - */ - function MongoClient(url, options) { - if (!(this instanceof MongoClient)) - return new MongoClient(url, options); - // Set up event emitter - EventEmitter.call(this); - - if (options && options.autoEncryption) __nccwpck_require__(3012); // Does CSFLE lib check - - // The internal state - this.s = { - url: url, - options: options || {}, - promiseLibrary: (options && options.promiseLibrary) || Promise, - dbCache: new Map(), - sessions: new Set(), - writeConcern: WriteConcern.fromOptions(options), - readPreference: - ReadPreference.fromOptions(options) || ReadPreference.primary, - namespace: new MongoDBNamespace("admin"), - }; } - /** - * @ignore - */ - inherits(MongoClient, EventEmitter); + this.options.explain = true; - Object.defineProperty(MongoClient.prototype, "writeConcern", { - enumerable: true, - get: function () { - return this.s.writeConcern; - }, + model.collection.aggregate(this._pipeline, this.options, (error, cursor) => { + if (error != null) { + const _opts = { error: error }; + return model.hooks.execPost('aggregate', this, [null], _opts, error => { + cb(error); + }); + } + cursor.explain((error, result) => { + const _opts = { error: error }; + return model.hooks.execPost('aggregate', this, [result], _opts, error => { + if (error) { + return cb(error); + } + return cb(null, result); + }); + }); }); + }); + }, model.events); +}; - Object.defineProperty(MongoClient.prototype, "readPreference", { - enumerable: true, - get: function () { - return this.s.readPreference; - }, - }); +/** + * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) + * + * ####Example: + * + * await Model.aggregate([{ $match: { foo: 'bar' } }]).allowDiskUse(true); + * + * @param {Boolean} value Should tell server it can use hard drive to store data during aggregation. + * @param {Array} [tags] optional tags for this query + * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ + */ - /** - * 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"); - } +Aggregate.prototype.allowDiskUse = function(value) { + this.options.allowDiskUse = value; + return this; +}; - const client = this; - return maybePromise(this, callback, (cb) => { - const err = validOptions(client.s.options); - if (err) return cb(err); +/** + * Sets the hint option for the aggregation query (ignored for < 3.6.0) + * + * ####Example: + * + * Model.aggregate(..).hint({ qty: 1, category: 1 }).exec(callback) + * + * @param {Object|String} value a hint object or the index name + * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ + */ - connect(client, client.s.url, client.s.options, (err) => { - if (err) return cb(err); - cb(null, client); - }); - }); - }; +Aggregate.prototype.hint = function(value) { + this.options.hint = value; + return this; +}; - 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"); +/** + * Sets the session for this aggregation. Useful for [transactions](/docs/transactions.html). + * + * ####Example: + * + * const session = await Model.startSession(); + * await Model.aggregate(..).session(session); + * + * @param {ClientSession} session + * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ + */ - /** - * 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; - } +Aggregate.prototype.session = function(session) { + if (session == null) { + delete this.options.session; + } else { + this.options.session = session; + } + return this; +}; - const client = this; - return maybePromise(this, callback, (cb) => { - const completeClose = (err) => { - client.emit("close", client); +/** + * Lets you set arbitrary options, for middleware or plugins. + * + * ####Example: + * + * const agg = Model.aggregate(..).option({ allowDiskUse: true }); // Set the `allowDiskUse` option + * agg.options; // `{ allowDiskUse: true }` + * + * @param {Object} options keys to merge into current options + * @param [options.maxTimeMS] number limits the time this aggregation will run, see [MongoDB docs on `maxTimeMS`](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) + * @param [options.allowDiskUse] boolean if true, the MongoDB server will use the hard drive to store data during this aggregation + * @param [options.collation] object see [`Aggregate.prototype.collation()`](./docs/api.html#aggregate_Aggregate-collation) + * @param [options.session] ClientSession see [`Aggregate.prototype.session()`](./docs/api.html#aggregate_Aggregate-session) + * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ + * @return {Aggregate} this + * @api public + */ - if (!(client.topology instanceof NativeTopology)) { - for (const item of client.s.dbCache) { - item[1].emit("close", client); - } - } +Aggregate.prototype.option = function(value) { + for (const key in value) { + this.options[key] = value[key]; + } + return this; +}; - client.removeAllListeners("close"); - cb(err); - }; +/** + * Sets the `cursor` option and executes this aggregation, returning an aggregation cursor. + * Cursors are useful if you want to process the results of the aggregation one-at-a-time + * because the aggregation result is too big to fit into memory. + * + * ####Example: + * + * const cursor = Model.aggregate(..).cursor({ batchSize: 1000 }); + * cursor.eachAsync(function(doc, i) { + * // use doc + * }); + * + * @param {Object} options + * @param {Number} options.batchSize set the cursor batch size + * @param {Boolean} [options.useMongooseAggCursor] use experimental mongoose-specific aggregation cursor (for `eachAsync()` and other query cursor semantics) + * @return {AggregationCursor} cursor representing this aggregation + * @api public + * @see mongodb http://mongodb.github.io/node-mongodb-native/2.0/api/AggregationCursor.html + */ - if (client.topology == null) { - completeClose(); - return; - } +Aggregate.prototype.cursor = function(options) { + if (!this.options) { + this.options = {}; + } + this.options.cursor = options || {}; + return new AggregationCursor(this); // return this; +}; - client.topology.close(force, (err) => { - const encrypter = client.topology.s.options.encrypter; - if (encrypter) { - return encrypter.close(client, force, (err2) => { - completeClose(err || err2); - }); - } - completeClose(err); - }); - }); - }; +/** + * Adds a collation + * + * ####Example: + * + * const res = await Model.aggregate(pipeline).collation({ locale: 'en_US', strength: 1 }); + * + * @param {Object} collation options + * @return {Aggregate} this + * @api public + * @see mongodb http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#aggregate + */ - /** - * 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 || {}; +Aggregate.prototype.collation = function(collation) { + if (!this.options) { + this.options = {}; + } + this.options.collation = collation; + return this; +}; - // Default to db from connection string if not provided - if (!dbName) { - dbName = this.s.options.dbName; - } +/** + * Combines multiple aggregation pipelines. + * + * ####Example: + * + * const res = await Model.aggregate().facet({ + * books: [{ groupBy: '$author' }], + * price: [{ $bucketAuto: { groupBy: '$price', buckets: 2 } }] + * }); + * + * // Output: { books: [...], price: [{...}, {...}] } + * + * @param {Object} facet options + * @return {Aggregate} this + * @see $facet https://docs.mongodb.com/v3.4/reference/operator/aggregation/facet/ + * @api public + */ - // Copy the options and add out internal override of the not shared flag - const finalOptions = Object.assign({}, this.s.options, options); +Aggregate.prototype.facet = function(options) { + return this.append({ $facet: 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); - } +/** + * Helper for [Atlas Text Search](https://docs.atlas.mongodb.com/reference/atlas-search/tutorial/)'s + * `$search` stage. + * + * ####Example: + * + * const res = await Model.aggregate(). + * search({ + * text: { + * query: 'baseball', + * path: 'plot' + * } + * }); + * + * // Output: [{ plot: '...', title: '...' }] + * + * @param {Object} $search options + * @return {Aggregate} this + * @see $search https://docs.atlas.mongodb.com/reference/atlas-search/tutorial/ + * @api public + */ - // Add promiseLibrary - finalOptions.promiseLibrary = this.s.promiseLibrary; +Aggregate.prototype.search = function(options) { + return this.append({ $search: options }); +}; - // If no topology throw an error message - if (!this.topology) { - throw new MongoError( - "MongoClient must be connected before calling MongoClient.prototype.db" - ); - } +/** + * Returns the current pipeline + * + * ####Example: + * + * MyModel.aggregate().match({ test: 1 }).pipeline(); // [{ $match: { test: 1 } }] + * + * @return {Array} + * @api public + */ - // 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; - }; +Aggregate.prototype.pipeline = function() { + return this._pipeline; +}; - /** - * 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 || {}; +/** + * Executes the aggregate pipeline on the currently bound Model. + * + * ####Example: + * + * aggregate.exec(callback); + * + * // Because a promise is returned, the `callback` is optional. + * const promise = aggregate.exec(); + * promise.then(..); + * + * @see Promise #promise_Promise + * @param {Function} [callback] + * @return {Promise} + * @api public + */ - if (!this.topology) return false; - return this.topology.isConnected(options); - }; +Aggregate.prototype.exec = function(callback) { + if (!this._model) { + throw new Error('Aggregate not bound to any Model'); + } + const model = this._model; + const collection = this._model.collection; - /** - * 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 {MongoClientOptions} [options] Optional settings - * @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 || {}; + applyGlobalMaxTimeMS(this.options, model); - // Create client - const mongoClient = new MongoClient(url, options); - // Execute the connect method - return mongoClient.connect(callback); - }; + if (this.options && this.options.cursor) { + return new AggregationCursor(this); + } - /** - * 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" - ); - } + return promiseOrCallback(callback, cb => { + prepareDiscriminatorPipeline(this._pipeline, this._model.schema); + stringifyFunctionOperators(this._pipeline); - return this.topology.startSession(options, this.s.options); - }; + model.hooks.execPre('aggregate', this, error => { + if (error) { + const _opts = { error: error }; + return model.hooks.execPost('aggregate', this, [null], _opts, error => { + cb(error); + }); + } + if (!this._pipeline.length) { + return cb(new Error('Aggregate has empty pipeline')); + } - /** - * 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); + const options = utils.clone(this.options || {}); - let cleanupHandler = (err, result, opts) => { - // prevent multiple calls to cleanupHandler - cleanupHandler = () => { - throw new ReferenceError( - "cleanupHandler was called too many times" - ); - }; + collection.aggregate(this._pipeline, options, (err, cursor) => { + if (err != null) { + return cb(err); + } - opts = Object.assign({ throw: true }, opts); - session.endSession(); + cursor.toArray((error, result) => { + const _opts = { error: error }; + model.hooks.execPost('aggregate', this, [result], _opts, (error, result) => { + if (error) { + return cb(error); + } - if (err) { - if (opts.throw) throw err; - return Promise.reject(err); - } - }; + cb(null, result); + }); + }); + }); + }); + }, model.events); +}; - 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 || {}; +/** + * Provides promise for aggregate. + * + * ####Example: + * + * Model.aggregate(..).then(successCallback, errorCallback); + * + * @see Promise #promise_Promise + * @param {Function} [resolve] successCallback + * @param {Function} [reject] errorCallback + * @return {Promise} + */ +Aggregate.prototype.then = function(resolve, reject) { + return this.exec().then(resolve, reject); +}; + +/** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + * Like [`.then()`](#query_Query-then), but only takes a rejection handler. + * + * @param {Function} [reject] + * @return {Promise} + * @api public + */ - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } +Aggregate.prototype.catch = function(reject) { + return this.exec().then(null, reject); +}; - return new ChangeStream(this, pipeline, options); - }; +/** + * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js + * You do not need to call this function explicitly, the JavaScript runtime + * will call it for you. + * + * ####Example + * + * const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]); + * for await (const doc of agg) { + * console.log(doc.name); + * } + * + * Node.js 10.x supports async iterators natively without any flags. You can + * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). + * + * **Note:** This function is not set if `Symbol.asyncIterator` is undefined. If + * `Symbol.asyncIterator` is undefined, that means your Node.js version does not + * support async iterators. + * + * @method Symbol.asyncIterator + * @memberOf Aggregate + * @instance + * @api public + */ - /** - * Return the mongo client logger - * @method - * @return {Logger} return the mongo client logger - * @ignore - */ - MongoClient.prototype.getLogger = function () { - return this.s.options.logger; - }; +if (Symbol.asyncIterator != null) { + Aggregate.prototype[Symbol.asyncIterator] = function() { + return this.cursor({ useMongooseAggCursor: true }). + transformNull(). + _transformForAsyncIterator(); + }; +} - module.exports = MongoClient; +/*! + * Helpers + */ - /***/ - }, +/** + * Checks whether an object is likely a pipeline operator + * + * @param {Object} obj object to check + * @return {Boolean} + * @api private + */ - /***/ 7057: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Aspect = __nccwpck_require__(1018).Aspect; - const CommandOperation = __nccwpck_require__(499); - const defineAspects = __nccwpck_require__(1018).defineAspects; - const crypto = __nccwpck_require__(6417); - const handleCallback = __nccwpck_require__(1371).handleCallback; - const toError = __nccwpck_require__(1371).toError; - const emitWarning = __nccwpck_require__(1371).emitWarning; - - 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 = []; - if (Array.isArray(options.roles)) roles = options.roles; - if (typeof options.roles === "string") roles = [options.roles]; - - // If not roles defined print deprecated message - // TODO: handle deprecation properly - if (roles.length === 0) { - emitWarning( - "Creating a user without roles is deprecated in MongoDB >= 2.6" - ); - } +function isOperator(obj) { + if (typeof obj !== 'object') { + return false; + } - // 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 k = Object.keys(obj); - const digestPassword = - db.s.topology.lastIsMaster().maxWireVersion >= 7; + return k.length === 1 && k.some(key => { return key[0] === '$'; }); +} - let userPassword = password; +/*! + * Adds the appropriate `$match` pipeline step to the top of an aggregate's + * pipeline, should it's model is a non-root discriminator type. This is + * analogous to the `prepareDiscriminatorCriteria` function in `lib/query.js`. + * + * @param {Aggregate} aggregate Aggregate to prepare + */ - 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"); - } +Aggregate._prepareDiscriminatorPipeline = prepareDiscriminatorPipeline; - // Build the command to execute - const command = { - createUser: username, - customData: options.customData || {}, - roles: roles, - digestPassword, - }; +/*! + * Exports + */ - // No password - if (typeof password === "string") { - command.pwd = userPassword; - } +module.exports = Aggregate; - 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." - ) - ); - } +/***/ 6830: +/***/ ((module, exports, __nccwpck_require__) => { - // Attempt to execute auth command - super.execute((err, r) => { - if (!err) { - return handleCallback(callback, err, r); - } +"use strict"; +/*! + * Module dependencies. + */ - return handleCallback(callback, err, null); - }); - } - } - defineAspects(AddUserOperation, Aspect.WRITE_OPERATION); - module.exports = AddUserOperation; +const NodeJSDocument = __nccwpck_require__(6717); +const EventEmitter = __nccwpck_require__(8614).EventEmitter; +const MongooseError = __nccwpck_require__(4327); +const Schema = __nccwpck_require__(7606); +const ObjectId = __nccwpck_require__(2706); +const ValidationError = MongooseError.ValidationError; +const applyHooks = __nccwpck_require__(5373); +const isObject = __nccwpck_require__(273); - /***/ - }, +/** + * Document constructor. + * + * @param {Object} obj the values to set + * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data + * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `init`: Emitted on a document after it has was retrieved from the db and fully hydrated by Mongoose. + * @event `save`: Emitted when the document is successfully saved + * @api private + */ - /***/ 1554: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const CommandOperationV2 = __nccwpck_require__(1189); - const MongoError = __nccwpck_require__(3994).MongoError; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_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; - } - } +function Document(obj, schema, fields, skipId, skipInit) { + if (!(this instanceof Document)) { + return new Document(obj, schema, fields, skipId, skipInit); + } - if (this.hasWriteStage) { - this.readPreference = ReadPreference.primary; - } + if (isObject(schema) && !schema.instanceOfSchema) { + schema = new Schema(schema); + } - if (this.explain && this.writeConcern) { - throw new MongoError( - '"explain" cannot be used on an aggregate call with writeConcern' - ); - } + // When creating EmbeddedDocument, it already has the schema and he doesn't need the _id + schema = this.schema || schema; - if (options.cursor != null && typeof options.cursor !== "object") { - throw new MongoError("cursor options must be an object"); - } - } + // Generate ObjectId if it is missing, but it requires a scheme + if (!this.schema && schema.options._id) { + obj = obj || {}; - get canRetryRead() { - return !this.hasWriteStage; - } + if (obj._id === undefined) { + obj._id = new ObjectId(); + } + } - addToPipeline(stage) { - this.pipeline.push(stage); - } + if (!schema) { + throw new MongooseError.MissingSchemaError(); + } - execute(server, callback) { - const options = this.options; - const serverWireVersion = maxWireVersion(server); - const command = { aggregate: this.target, pipeline: this.pipeline }; + this.$__setSchema(schema); - if ( - this.hasWriteStage && - serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT - ) { - this.readConcern = null; - } + NodeJSDocument.call(this, obj, fields, skipId, skipInit); - if (serverWireVersion >= 5) { - if (this.hasWriteStage && this.writeConcern) { - Object.assign(command, { writeConcern: this.writeConcern }); - } - } + applyHooks(this, schema, { decorateDoc: true }); - if (options.bypassDocumentValidation === true) { - command.bypassDocumentValidation = options.bypassDocumentValidation; - } + // apply methods + for (const m in schema.methods) { + this[m] = schema.methods[m]; + } + // apply statics + for (const s in schema.statics) { + this[s] = schema.statics[s]; + } +} - if (typeof options.allowDiskUse === "boolean") { - command.allowDiskUse = options.allowDiskUse; - } +/*! + * Inherit from the NodeJS document + */ - if (options.hint) { - command.hint = options.hint; - } +Document.prototype = Object.create(NodeJSDocument.prototype); +Document.prototype.constructor = Document; - if (this.explain) { - options.full = false; - } +/*! + * ignore + */ - command.cursor = options.cursor || {}; - if (options.batchSize && !this.hasWriteStage) { - command.cursor.batchSize = options.batchSize; - } +Document.events = new EventEmitter(); - super.executeCommand(server, command, callback); - } - } +/*! + * Browser doc exposes the event emitter API + */ - defineAspects(AggregateOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION, - Aspect.EXPLAINABLE, - ]); +Document.$emitter = new EventEmitter(); - module.exports = AggregateOperation; +['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', + 'removeAllListeners', 'addListener'].forEach(function(emitterFn) { + Document[emitterFn] = function() { + return Document.$emitter[emitterFn].apply(Document.$emitter, arguments); + }; +}); - /***/ - }, +/*! + * Module exports. + */ - /***/ 6976: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +Document.ValidationError = ValidationError; +module.exports = exports = Document; - const applyRetryableWrites = - __nccwpck_require__(1371).applyRetryableWrites; - const applyWriteConcern = __nccwpck_require__(1371).applyWriteConcern; - const MongoError = __nccwpck_require__(3994).MongoError; - const OperationBase = __nccwpck_require__(1018).OperationBase; - class BulkWriteOperation extends OperationBase { - constructor(collection, operations, options) { - super(options); +/***/ }), - this.collection = collection; - this.operations = operations; - } +/***/ 9179: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - execute(callback) { - const coll = this.collection; - const operations = this.operations; - let options = this.options; +"use strict"; - // 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); +/*! + * Module dependencies. + */ + +const CastError = __nccwpck_require__(2798); +const StrictModeError = __nccwpck_require__(5328); +const Types = __nccwpck_require__(2987); +const castTextSearch = __nccwpck_require__(8807); +const get = __nccwpck_require__(8730); +const getConstructorName = __nccwpck_require__(7323); +const getSchemaDiscriminatorByValue = __nccwpck_require__(6250); +const isOperator = __nccwpck_require__(3342); +const util = __nccwpck_require__(1669); +const isObject = __nccwpck_require__(273); +const isMongooseObject = __nccwpck_require__(7104); + +const ALLOWED_GEOWITHIN_GEOJSON_TYPES = ['Polygon', 'MultiPolygon']; + +/** + * Handles internal casting for query filters. + * + * @param {Schema} schema + * @param {Object} obj Object to cast + * @param {Object} options the query options + * @param {Query} context passed to setters + * @api private + */ +module.exports = function cast(schema, obj, options, context) { + if (Array.isArray(obj)) { + throw new Error('Query filter must be an object, got an array ', util.inspect(obj)); + } - // Do we have a collation - let collation = false; + if (obj == null) { + return obj; + } - // 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; - } + // bson 1.x has the unfortunate tendency to remove filters that have a top-level + // `_bsontype` property. But we should still allow ObjectIds because + // `Collection#find()` has a special case to support `find(objectid)`. + // Should remove this when we upgrade to bson 4.x. See gh-8222, gh-8268 + if (obj.hasOwnProperty('_bsontype') && obj._bsontype !== 'ObjectID') { + delete obj._bsontype; + } - // Pass to the raw bulk - bulk.raw(operations[i]); - } - } catch (err) { - return callback(err, null); - } + if (schema != null && schema.discriminators != null && obj[schema.options.discriminatorKey] != null) { + schema = getSchemaDiscriminatorByValue(schema, obj[schema.options.discriminatorKey]) || schema; + } - // 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 paths = Object.keys(obj); + let i = paths.length; + let _keys; + let any$conditionals; + let schematype; + let nested; + let path; + let type; + let val; - 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") - ); - } + options = options || {}; - // Execute the bulk - bulk.execute(writeCon, finalOptions, (err, r) => { - // We have connection level error - if (!r && err) { - return callback(err, null); - } + while (i--) { + path = paths[i]; + val = obj[path]; - // Return the results - callback(null, r); - }); + if (path === '$or' || path === '$nor' || path === '$and') { + if (!Array.isArray(val)) { + throw new CastError('Array', val, path); + } + for (let k = 0; k < val.length; ++k) { + if (val[k] == null || typeof val[k] !== 'object') { + throw new CastError('Object', val[k], path + '.' + k); } + val[k] = cast(schema, val[k], options, context); } + } else if (path === '$where') { + type = typeof val; - module.exports = BulkWriteOperation; - - /***/ - }, + if (type !== 'string' && type !== 'function') { + throw new Error('Must have a string or function for $where'); + } - /***/ 6716: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const applyWriteConcern = __nccwpck_require__(1371).applyWriteConcern; - const Code = __nccwpck_require__(3994).BSON.Code; - const createIndexDb = __nccwpck_require__(2226).createIndex; - const decorateWithCollation = - __nccwpck_require__(1371).decorateWithCollation; - const decorateWithReadConcern = - __nccwpck_require__(1371).decorateWithReadConcern; - const ensureIndexDb = __nccwpck_require__(2226).ensureIndex; - const evaluate = __nccwpck_require__(2226).evaluate; - const executeCommand = __nccwpck_require__(2226).executeCommand; - const handleCallback = __nccwpck_require__(1371).handleCallback; - const indexInformationDb = __nccwpck_require__(2226).indexInformation; - const Long = __nccwpck_require__(3994).BSON.Long; - const MongoError = __nccwpck_require__(3994).MongoError; - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const insertDocuments = __nccwpck_require__(2296).insertDocuments; - const updateDocuments = __nccwpck_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 - ); + if (type === 'function') { + obj[path] = val.toString(); } - /** - * 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(); + continue; + } else if (path === '$expr') { + if (typeof val !== 'object' || val == null) { + throw new Error('`$expr` must be an object'); + } + continue; + } else if (path === '$elemMatch') { + val = cast(schema, val, options, context); + } else if (path === '$text') { + val = castTextSearch(val, path); + } else { + if (!schema) { + // no casting for Mixed types + continue; + } - // 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 = []; + schematype = schema.path(path); - // 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" - ) - ); - } + // Check for embedded discriminator paths + if (!schematype) { + const split = path.split('.'); + let j = split.length; + while (j--) { + const pathFirstHalf = split.slice(0, j).join('.'); + const pathLastHalf = split.slice(j).join('.'); + const _schematype = schema.path(pathFirstHalf); + const discriminatorKey = get(_schematype, 'schema.options.discriminatorKey'); - for (let name in indexSpecs[i].key) { - keys.push(`${name}_${indexSpecs[i].key[name]}`); + // gh-6027: if we haven't found the schematype but this path is + // underneath an embedded discriminator and the embedded discriminator + // key is in the query, use the embedded discriminator schema + if (_schematype != null && + get(_schematype, 'schema.discriminators') != null && + discriminatorKey != null && + pathLastHalf !== discriminatorKey) { + const discriminatorVal = get(obj, pathFirstHalf + '.' + discriminatorKey); + if (discriminatorVal != null) { + schematype = _schematype.schema.discriminators[discriminatorVal]. + path(pathLastHalf); } - - // 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 - ); - } + if (!schematype) { + // Handle potential embedded array queries + const split = path.split('.'); + let j = split.length; + let pathFirstHalf; + let pathLastHalf; + let remainingConds; - /** - * 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", - }, - }; + // Find the part of the var path that is a path of the Schema + while (j--) { + pathFirstHalf = split.slice(0, j).join('.'); + schematype = schema.path(pathFirstHalf); + if (schematype) { + break; + } + } - // 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); + // If a substring of the input path resolves to an actual real path... + if (schematype) { + // Apply the casting; similar code for $elemMatch in schema/array.js + if (schematype.caster && schematype.caster.schema) { + remainingConds = {}; + pathLastHalf = split.slice(j).join('.'); + remainingConds[pathLastHalf] = val; + obj[path] = cast(schematype.caster.schema, remainingConds, options, context)[pathLastHalf]; } else { - const hash = {}; - keys.forEach((key) => { - hash[key] = 1; - }); - selector.group.key = hash; + obj[path] = val; } + continue; + } - 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); + if (isObject(val)) { + // handle geo schemas that use object notation + // { loc: { long: Number, lat: Number } - // Have we specified collation - try { - decorateWithCollation(selector, coll, options); - } catch (err) { - return callback(err, null); + let geo = ''; + if (val.$near) { + geo = '$near'; + } else if (val.$nearSphere) { + geo = '$nearSphere'; + } else if (val.$within) { + geo = '$within'; + } else if (val.$geoIntersects) { + geo = '$geoIntersects'; + } else if (val.$geoWithin) { + geo = '$geoWithin'; } - // 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() + ";" - ); + if (geo) { + const numbertype = new Types.Number('__QueryCasting__'); + let value = val[geo]; - 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); + if (val.$maxDistance != null) { + val.$maxDistance = numbertype.castForQueryWrapper({ + val: val.$maxDistance, + context: context + }); } - ); - } - } - - /** - * 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); + if (val.$minDistance != null) { + val.$minDistance = numbertype.castForQueryWrapper({ + val: val.$minDistance, + context: context + }); } - } - // All keys found return true - return handleCallback(callback, null, true); - }); - } + if (geo === '$within') { + const withinType = value.$center + || value.$centerSphere + || value.$box + || value.$polygon; + + if (!withinType) { + throw new Error('Bad $within parameter: ' + JSON.stringify(val)); + } + + value = withinType; + } else if (geo === '$near' && + typeof value.type === 'string' && Array.isArray(value.coordinates)) { + // geojson; cast the coordinates + value = value.coordinates; + } else if ((geo === '$near' || geo === '$nearSphere' || geo === '$geoIntersects') && + value.$geometry && typeof value.$geometry.type === 'string' && + Array.isArray(value.$geometry.coordinates)) { + if (value.$maxDistance != null) { + value.$maxDistance = numbertype.castForQueryWrapper({ + val: value.$maxDistance, + context: context + }); + } + if (value.$minDistance != null) { + value.$minDistance = numbertype.castForQueryWrapper({ + val: value.$minDistance, + context: context + }); + } + if (isMongooseObject(value.$geometry)) { + value.$geometry = value.$geometry.toObject({ + transform: false, + virtuals: false + }); + } + value = value.$geometry.coordinates; + } else if (geo === '$geoWithin') { + if (value.$geometry) { + if (isMongooseObject(value.$geometry)) { + value.$geometry = value.$geometry.toObject({ virtuals: false }); + } + const geoWithinType = value.$geometry.type; + if (ALLOWED_GEOWITHIN_GEOJSON_TYPES.indexOf(geoWithinType) === -1) { + throw new Error('Invalid geoJSON type for $geoWithin "' + + geoWithinType + '", must be "Polygon" or "MultiPolygon"'); + } + value = value.$geometry.coordinates; + } else { + value = value.$box || value.$polygon || value.$center || + value.$centerSphere; + if (isMongooseObject(value)) { + value = value.toObject({ virtuals: false }); + } + } + } - /** - * 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, - }; + _cast(value, numbertype, context); + continue; + } + } - // Do we have a readConcern specified - decorateWithReadConcern(commandObject, coll, options); + if (schema.nested[path]) { + continue; + } + if (options.upsert && options.strict) { + if (options.strict === 'throw') { + throw new StrictModeError(path); + } + throw new StrictModeError(path, 'Path "' + path + '" is not in ' + + 'schema, strict mode is `true`, and upsert is `true`.'); + } if (options.strictQuery === 'throw') { + throw new StrictModeError(path, 'Path "' + path + '" is not in ' + + 'schema and strictQuery is \'throw\'.'); + } else if (options.strictQuery) { + delete obj[path]; + } + } else if (val == null) { + continue; + } else if (getConstructorName(val) === 'Object') { + any$conditionals = Object.keys(val).some(isOperator); - // Store the raw value - const raw = options.raw; - delete options["raw"]; + if (!any$conditionals) { + obj[path] = schematype.castForQueryWrapper({ + val: val, + context: context + }); + } else { + const ks = Object.keys(val); + let $cond; - // 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 - ); + let k = ks.length; - 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) - ); + while (k--) { + $cond = ks[k]; + nested = val[$cond]; + + if ($cond === '$not') { + if (nested && schematype) { + _keys = Object.keys(nested); + if (_keys.length && isOperator(_keys[0])) { + for (const key in nested) { + nested[key] = schematype.castForQueryWrapper({ + $conditional: key, + val: nested[key], + context: context + }); + } + } else { + val[$cond] = schematype.castForQueryWrapper({ + $conditional: $cond, + val: nested, + context: context + }); + } + continue; + } + } else { + val[$cond] = schematype.castForQueryWrapper({ + $conditional: $cond, + val: nested, + context: context + }); + } } + } + } else if (Array.isArray(val) && ['Buffer', 'Array'].indexOf(schematype.instance) === -1) { + const casted = []; + const valuesArray = val; - 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 - ); + for (const _val of valuesArray) { + casted.push(schematype.castForQueryWrapper({ + val: _val, + context: context + })); } - // 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); + obj[path] = { $in: casted }; + } else { + obj[path] = schematype.castForQueryWrapper({ + val: val, + context: context }); } + } + } - module.exports = { - createIndex, - createIndexes, - ensureIndex, - group, - indexes, - indexExists, - indexInformation, - parallelCollectionScan, - save, - }; - - /***/ - }, - - /***/ 286: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const OperationBase = __nccwpck_require__(1018).OperationBase; - const handleCallback = __nccwpck_require__(1371).handleCallback; + return obj; +}; - let collection; - function loadCollection() { - if (!collection) { - collection = __nccwpck_require__(5193); - } - return collection; +function _cast(val, numbertype, context) { + if (Array.isArray(val)) { + val.forEach(function(item, i) { + if (Array.isArray(item) || isObject(item)) { + return _cast(item, numbertype, context); + } + val[i] = numbertype.castForQueryWrapper({ val: item, context: context }); + }); + } else { + const nearKeys = Object.keys(val); + let nearLen = nearKeys.length; + while (nearLen--) { + const nkey = nearKeys[nearLen]; + const item = val[nkey]; + if (Array.isArray(item) || isObject(item)) { + _cast(item, numbertype, context); + val[nkey] = item; + } else { + val[nkey] = numbertype.castForQuery({ val: item, context: context }); } + } + } +} - class CollectionsOperation extends OperationBase { - constructor(db, options) { - super(options); +/***/ }), - this.db = db; - } +/***/ 66: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - execute(callback) { - const db = this.db; - let options = this.options; +"use strict"; - 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; - }); +const CastError = __nccwpck_require__(2798); - // 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 - ); - }) - ); - }); - } - } +/*! + * Given a value, cast it to a boolean, or throw a `CastError` if the value + * cannot be casted. `null` and `undefined` are considered valid. + * + * @param {Any} value + * @param {String} [path] optional the path to set on the CastError + * @return {Boolean|null|undefined} + * @throws {CastError} if `value` is not one of the allowed values + * @api private + */ - module.exports = CollectionsOperation; +module.exports = function castBoolean(value, path) { + if (module.exports.convertToTrue.has(value)) { + return true; + } + if (module.exports.convertToFalse.has(value)) { + return false; + } - /***/ - }, + if (value == null) { + return value; + } - /***/ 499: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Aspect = __nccwpck_require__(1018).Aspect; - const OperationBase = __nccwpck_require__(1018).OperationBase; - const applyWriteConcern = __nccwpck_require__(1371).applyWriteConcern; - const debugOptions = __nccwpck_require__(1371).debugOptions; - const handleCallback = __nccwpck_require__(1371).handleCallback; - const MongoError = __nccwpck_require__(3994).MongoError; - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const MongoDBNamespace = __nccwpck_require__(1371).MongoDBNamespace; - const extractCommand = __nccwpck_require__(7703).extractCommand; - - const debugFields = [ - "authSource", - "w", - "wtimeout", - "j", - "native_parser", - "forceServerObjectId", - "serializeFunctions", - "raw", - "promoteLongs", - "promoteValues", - "promoteBuffers", - "bsonRegExp", - "bufferMaxEntries", - "numberOfRetries", - "retryMiliSeconds", - "readPreference", - "pkFactory", - "parentDb", - "promiseLibrary", - "noListener", - ]; + throw new CastError('boolean', value, path); +}; - class CommandOperation extends OperationBase { - constructor(db, options, collection, command) { - super(options); +module.exports.convertToTrue = new Set([true, 'true', 1, '1', 'yes']); +module.exports.convertToFalse = new Set([false, 'false', 0, '0', 'no']); - 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; - } +/***/ 1001: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (collection != null) { - this.collection = collection; - } - } +"use strict"; - _buildCommand() { - if (this.command != null) { - return this.command; - } - } - execute(callback) { - const db = this.db; - const options = Object.assign({}, this.options); +const assert = __nccwpck_require__(2357); - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError("topology was destroyed")); - } +module.exports = function castDate(value) { + // Support empty string because of empty form values. Originally introduced + // in https://github.com/Automattic/mongoose/commit/efc72a1898fc3c33a319d915b8c5463a22938dfe + if (value == null || value === '') { + return null; + } - let command; - try { - command = this._buildCommand(); - } catch (e) { - return callback(e); - } + if (value instanceof Date) { + assert.ok(!isNaN(value.valueOf())); - // Get the db name we are executing against - const dbName = options.dbName || options.authdb || db.databaseName; + return value; + } - // 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; - } - } + let date; + + assert.ok(typeof value !== 'boolean'); + + if (value instanceof Number || typeof value === 'number') { + date = new Date(value); + } else if (typeof value === 'string' && !isNaN(Number(value)) && (Number(value) >= 275761 || Number(value) < -271820)) { + // string representation of milliseconds take this path + date = new Date(Number(value)); + } else if (typeof value.valueOf === 'function') { + // support for moment.js. This is also the path strings will take because + // strings have a `valueOf()` + date = new Date(value.valueOf()); + } else { + // fallback + date = new Date(value); + } - // Debug information - if (db.s.logger.isDebug()) { - const extractedCommand = extractCommand(command); - db.s.logger.debug( - `executing command ${JSON.stringify( - extractedCommand.shouldRedact - ? `${extractedCommand.name} details REDACTED` - : command - )} against ${dbName}.$cmd with options [${JSON.stringify( - debugOptions(debugFields, options) - )}]` - ); - } + if (!isNaN(date.valueOf())) { + return date; + } - const namespace = - this.namespace != null - ? this.namespace - : new MongoDBNamespace(dbName, "$cmd"); + assert.ok(false); +}; - // 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; +/***/ 8748: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /***/ - }, +"use strict"; - /***/ 1189: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Aspect = __nccwpck_require__(1018).Aspect; - const OperationBase = __nccwpck_require__(1018).OperationBase; - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const ReadConcern = __nccwpck_require__(7289); - const WriteConcern = __nccwpck_require__(2481); - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const decorateWithExplain = __nccwpck_require__(1371).decorateWithExplain; - const commandSupportsReadConcern = - __nccwpck_require__(5474).commandSupportsReadConcern; - const MongoError = __nccwpck_require__(3111).MongoError; - const extractCommand = __nccwpck_require__(7703).extractCommand; - - 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 = this.hasAspect(Aspect.WRITE_OPERATION) - ? ReadPreference.primary - : ReadPreference.resolve(propertyProvider, this.options); - this.readConcern = resolveReadConcern(propertyProvider, this.options); - this.writeConcern = resolveWriteConcern( - propertyProvider, - this.options - ); - if ( - operationOptions && - typeof operationOptions.fullResponse === "boolean" - ) { - this.fullResponse = true; - } +const Decimal128Type = __nccwpck_require__(8319); +const assert = __nccwpck_require__(2357); - // TODO: 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; +module.exports = function castDecimal128(value) { + if (value == null) { + return value; + } - // 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; - } - } + if (typeof value === 'object' && typeof value.$numberDecimal === 'string') { + return Decimal128Type.fromString(value.$numberDecimal); + } - executeCommand(server, cmd, callback) { - // TODO: consider making this a non-enumerable property - this.server = server; + if (value instanceof Decimal128Type) { + return value; + } - const options = this.options; - const serverWireVersion = maxWireVersion(server); - const inTransaction = this.session && this.session.inTransaction(); + if (typeof value === 'string') { + return Decimal128Type.fromString(value); + } - if ( - this.readConcern && - commandSupportsReadConcern(cmd) && - !inTransaction - ) { - Object.assign(cmd, { readConcern: this.readConcern }); - } + if (Buffer.isBuffer(value)) { + return new Decimal128Type(value); + } - 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 (typeof value === 'number') { + return Decimal128Type.fromString(String(value)); + } - if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) { - if (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION)) { - Object.assign(cmd, { writeConcern: this.writeConcern }); - } + if (typeof value.valueOf === 'function' && typeof value.valueOf() === 'string') { + return Decimal128Type.fromString(value.valueOf()); + } - if (options.collation && typeof options.collation === "object") { - Object.assign(cmd, { collation: options.collation }); - } - } + assert.ok(false); +}; - if (typeof options.maxTimeMS === "number") { - cmd.maxTimeMS = options.maxTimeMS; - } +/***/ }), - if (typeof options.comment === "string") { - cmd.comment = options.comment; - } +/***/ 1582: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this.hasAspect(Aspect.EXPLAINABLE) && this.explain) { - if (serverWireVersion < 6 && cmd.aggregate) { - // Prior to 3.6, with aggregate, verbosity is ignored, and we must pass in "explain: true" - cmd.explain = true; - } else { - cmd = decorateWithExplain(cmd, this.explain); - } - } +"use strict"; - if (this.logger && this.logger.isDebug()) { - const extractedCommand = extractCommand(cmd); - this.logger.debug( - `executing command ${JSON.stringify( - extractedCommand.shouldRedact - ? `${extractedCommand.name} details REDACTED` - : cmd - )} against ${this.ns}` - ); - } - server.command( - this.ns.toString(), - cmd, - this.options, - (err, result) => { - if (err) { - callback(err, null); - return; - } +const assert = __nccwpck_require__(2357); - if (this.fullResponse) { - callback(null, result); - return; - } +/*! + * Given a value, cast it to a number, or throw a `CastError` if the value + * cannot be casted. `null` and `undefined` are considered valid. + * + * @param {Any} value + * @param {String} [path] optional the path to set on the CastError + * @return {Boolean|null|undefined} + * @throws {Error} if `value` is not one of the allowed values + * @api private + */ - callback(null, result.result); - } - ); - } - } +module.exports = function castNumber(val) { + if (val == null) { + return val; + } + if (val === '') { + return null; + } - function resolveWriteConcern(parent, options) { - return ( - WriteConcern.fromOptions(options) || (parent && parent.writeConcern) - ); - } + if (typeof val === 'string' || typeof val === 'boolean') { + val = Number(val); + } - function resolveReadConcern(parent, options) { - return ( - ReadConcern.fromOptions(options) || (parent && parent.readConcern) - ); - } + assert.ok(!isNaN(val)); + if (val instanceof Number) { + return val.valueOf(); + } + if (typeof val === 'number') { + return val; + } + if (!Array.isArray(val) && typeof val.valueOf === 'function') { + return Number(val.valueOf()); + } + if (val.toString && !Array.isArray(val) && val.toString() == Number(val)) { + return Number(val); + } - module.exports = CommandOperationV2; + assert.ok(false); +}; - /***/ - }, - /***/ 2296: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const applyRetryableWrites = - __nccwpck_require__(1371).applyRetryableWrites; - const applyWriteConcern = __nccwpck_require__(1371).applyWriteConcern; - const decorateWithCollation = - __nccwpck_require__(1371).decorateWithCollation; - const decorateWithReadConcern = - __nccwpck_require__(1371).decorateWithReadConcern; - const executeCommand = __nccwpck_require__(2226).executeCommand; - const formattedOrderClause = - __nccwpck_require__(1371).formattedOrderClause; - const handleCallback = __nccwpck_require__(1371).handleCallback; - const MongoError = __nccwpck_require__(3994).MongoError; - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const toError = __nccwpck_require__(1371).toError; - const CursorState = __nccwpck_require__(4847).CursorState; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - - /** - * 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, - }; +/***/ 5552: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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); - } +"use strict"; - // 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; - } - - /** - * 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, - }; +const ObjectId = __nccwpck_require__(2324).get().ObjectId; +const assert = __nccwpck_require__(2357); - sort = formattedOrderClause(sort); - if (sort) { - queryObject.sort = sort; - } +module.exports = function castObjectId(value) { + if (value == null) { + return value; + } - queryObject.new = options.new ? true : false; - queryObject.remove = options.remove ? true : false; - queryObject.upsert = options.upsert ? true : false; + if (value instanceof ObjectId) { + return value; + } - const projection = options.projection || options.fields; + if (value._id) { + if (value._id instanceof ObjectId) { + return value._id; + } + if (value._id.toString instanceof Function) { + return new ObjectId(value._id.toString()); + } + } - if (projection) { - queryObject.fields = projection; - } + if (value.toString instanceof Function) { + return new ObjectId(value.toString()); + } - if (options.arrayFilters) { - queryObject.arrayFilters = options.arrayFilters; - delete options.arrayFilters; - } + assert.ok(false); +}; - if (doc && !options.remove) { - queryObject.update = doc; - } +/***/ }), - if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; +/***/ 1318: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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; +"use strict"; - // 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 - ); +const CastError = __nccwpck_require__(2798); - // Decorate the findAndModify command with the write Concern - if (finalOptions.writeConcern) { - queryObject.writeConcern = finalOptions.writeConcern; - } +/*! + * Given a value, cast it to a string, or throw a `CastError` if the value + * cannot be casted. `null` and `undefined` are considered valid. + * + * @param {Any} value + * @param {String} [path] optional the path to set on the CastError + * @return {string|null|undefined} + * @throws {CastError} + * @api private + */ - // Have we specified bypassDocumentValidation - if (finalOptions.bypassDocumentValidation === true) { - queryObject.bypassDocumentValidation = - finalOptions.bypassDocumentValidation; - } +module.exports = function castString(value, path) { + // If null or undefined + if (value == null) { + return value; + } - finalOptions.readPreference = ReadPreference.primary; + // handle documents being passed + if (value._id && typeof value._id === 'string') { + return value._id; + } - // Have we specified collation - try { - decorateWithCollation(queryObject, coll, finalOptions); - } catch (err) { - return callback(err, null); - } + // Re: gh-647 and gh-3030, we're ok with casting using `toString()` + // **unless** its the default Object.toString, because "[object Object]" + // doesn't really qualify as useful data + if (value.toString && + value.toString !== Object.prototype.toString && + !Array.isArray(value)) { + return value.toString(); + } - // Execute the command - executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => { - if (err) return handleCallback(callback, err, null); + throw new CastError('string', value, path); +}; - 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; - } +/***/ 6798: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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)); - }); - } +"use strict"; - 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; - } +/*! + * Module dependencies. + */ - return docs.map((doc) => { - if (forceServerObjectId !== true && doc._id == null) { - doc._id = coll.s.pkFactory.createPk(); - } +const EventEmitter = __nccwpck_require__(8614).EventEmitter; +const STATES = __nccwpck_require__(932); +const immediate = __nccwpck_require__(4830); - return doc; - }); - } +/** + * Abstract Collection constructor + * + * This is the base class that drivers inherit from and implement. + * + * @param {String} name name of the collection + * @param {Connection} conn A MongooseConnection instance + * @param {Object} opts optional collection options + * @api public + */ - // 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 }) - ); - } +function Collection(name, conn, opts) { + if (opts === void 0) { + opts = {}; + } + if (opts.capped === void 0) { + opts.capped = {}; + } - 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); - } - } + if (typeof opts.capped === 'number') { + opts.capped = { size: opts.capped }; + } - // Get the next object - cursor._next((err, doc) => { - cursor.s.state = CursorState.OPEN; - if (err) return handleCallback(callback, err); - handleCallback(callback, null, doc); - }); - } + this.opts = opts; + this.name = name; + this.collectionName = name; + this.conn = conn; + this.queue = []; + this.buffer = true; + this.emitter = new EventEmitter(); - 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]; + if (STATES.connected === this.conn.readyState) { + this.onOpen(); + } +} - // 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 - ); +/** + * The collection name + * + * @api public + * @property name + */ - // 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); - } - ); - } +Collection.prototype.name; - function removeDocuments(coll, selector, options, callback) { - if (typeof options === "function") { - (callback = options), (options = {}); - } else if (typeof selector === "function") { - callback = selector; - options = {}; - selector = {}; - } +/** + * The collection name + * + * @api public + * @property collectionName + */ - // Create an empty options object if the provided one is null - options = options || {}; +Collection.prototype.collectionName; - // 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 - ); +/** + * The Connection instance + * + * @api public + * @property conn + */ - // If selector is null set empty - if (selector == null) selector = {}; +Collection.prototype.conn; - // 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; - } +/** + * Called when the database connects + * + * @api private + */ - // Have we specified collation - try { - decorateWithCollation(finalOptions, coll, options); - } catch (err) { - return callback(err, null); - } +Collection.prototype.onOpen = function() { + this.buffer = false; + immediate(() => this.doQueue()); +}; - if ( - options.explain !== undefined && - maxWireVersion(coll.s.topology) < 3 - ) { - return callback - ? callback( - new MongoError(`server does not support explain on remove`) - ) - : undefined; - } - - // 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]) - ); - } +/** + * Called when the database disconnects + * + * @api private + */ - // Return the results - handleCallback(callback, null, result); - } - ); - } +Collection.prototype.onClose = function() {}; - 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; +/** + * Queues a method for later execution when its + * database connection opens. + * + * @param {String} name name of the method to queue + * @param {Array} args arguments to pass to the method when executed + * @api private + */ - // 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") - ); +Collection.prototype.addQueue = function(name, args) { + this.queue.push([name, args]); + return this; +}; - // 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 - ); +/** + * Removes a queued method + * + * @param {String} name name of the method to queue + * @param {Array} args arguments to pass to the method when executed + * @api private + */ - // 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; +Collection.prototype.removeQueue = function(name, args) { + const index = this.queue.findIndex(v => v[0] === name && v[1] === args); + if (index === -1) { + return false; + } + this.queue.splice(index, 1); + return true; +}; - // 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; +/** + * Executes all queued methods and clears the queue. + * + * @api private + */ - if (options.hint) { - op.hint = options.hint; - } +Collection.prototype.doQueue = function() { + for (const method of this.queue) { + if (typeof method[0] === 'function') { + method[0].apply(this, method[1]); + } else { + this[method[0]].apply(this, method[1]); + } + } + this.queue = []; + const _this = this; + immediate(function() { + _this.emitter.emit('queue'); + }); + return this; +}; + +/** + * Abstract method that drivers must implement. + */ - if (finalOptions.arrayFilters) { - op.arrayFilters = finalOptions.arrayFilters; - delete finalOptions.arrayFilters; - } +Collection.prototype.ensureIndex = function() { + throw new Error('Collection#ensureIndex unimplemented by driver'); +}; - if (finalOptions.retryWrites && op.multi) { - finalOptions.retryWrites = false; - } +/** + * Abstract method that drivers must implement. + */ - // Have we specified collation - try { - decorateWithCollation(finalOptions, coll, options); - } catch (err) { - return callback(err, null); - } +Collection.prototype.createIndex = function() { + throw new Error('Collection#createIndex unimplemented by driver'); +}; - if ( - options.explain !== undefined && - maxWireVersion(coll.s.topology) < 3 - ) { - return callback - ? callback( - new MongoError(`server does not support explain on update`) - ) - : undefined; - } - - // 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); - } - ); - } +/** + * Abstract method that drivers must implement. + */ - module.exports = { - buildCountCommand, - findAndModify, - indexInformation, - nextObject, - prepareDocs, - insertDocuments, - removeDocuments, - updateDocuments, - }; +Collection.prototype.findAndModify = function() { + throw new Error('Collection#findAndModify unimplemented by driver'); +}; - /***/ - }, +/** + * Abstract method that drivers must implement. + */ - /***/ 5210: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const deprecate = __nccwpck_require__(1669).deprecate; - const Logger = __nccwpck_require__(3994).Logger; - const MongoCredentials = __nccwpck_require__(3994).MongoCredentials; - const MongoError = __nccwpck_require__(3994).MongoError; - const Mongos = __nccwpck_require__(2048); - const NativeTopology = __nccwpck_require__(2632); - const parse = __nccwpck_require__(3994).parseConnectionString; - const ReadConcern = __nccwpck_require__(7289); - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const ReplSet = __nccwpck_require__(382); - const Server = __nccwpck_require__(8421); - const ServerSessionPool = - __nccwpck_require__(3994).Sessions.ServerSessionPool; - const emitDeprecationWarning = - __nccwpck_require__(1371).emitDeprecationWarning; - const emitWarningOnce = __nccwpck_require__(1371).emitWarningOnce; - const fs = __nccwpck_require__(5747); - const WriteConcern = __nccwpck_require__(2481); - const CMAP_EVENT_NAMES = __nccwpck_require__(897).CMAP_EVENT_NAMES; - - let client; - function loadClient() { - if (!client) { - client = __nccwpck_require__(1545); - } - return client; - } - - const legacyParse = deprecate( - __nccwpck_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." - ); +Collection.prototype.findOneAndUpdate = function() { + throw new Error('Collection#findOneAndUpdate unimplemented by driver'); +}; - 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", - }; +/** + * Abstract method that drivers must implement. + */ - const monitoringEvents = [ - "timeout", - "close", - "serverOpening", - "serverDescriptionChanged", - "serverHeartbeatStarted", - "serverHeartbeatSucceeded", - "serverHeartbeatFailed", - "serverClosed", - "topologyOpening", - "topologyClosed", - "topologyDescriptionChanged", - "commandStarted", - "commandSucceeded", - "commandFailed", - "joined", - "left", - "ping", - "ha", - "all", - "fullsetup", - "open", - ]; +Collection.prototype.findOneAndDelete = function() { + throw new Error('Collection#findOneAndDelete unimplemented by driver'); +}; - 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", - "writeConcern", - "forceServerObjectId", - "serializeFunctions", - "ignoreUndefined", - "raw", - "bufferMaxEntries", - "readPreference", - "pkFactory", - "promiseLibrary", - "readConcern", - "maxStalenessSeconds", - "loggerLevel", - "logger", - "promoteValues", - "promoteBuffers", - "promoteLongs", - "bsonRegExp", - "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", - ]; +/** + * Abstract method that drivers must implement. + */ - const ignoreOptionNames = ["native_parser"]; - const legacyOptionNames = [ - "server", - "replset", - "replSet", - "mongos", - "db", - ]; +Collection.prototype.findOneAndReplace = function() { + throw new Error('Collection#findOneAndReplace unimplemented by driver'); +}; - // Validate options object - function validOptions(options) { - const _validOptions = validOptionNames.concat(legacyOptionNames); +/** + * Abstract method that drivers must implement. + */ - for (const name in options) { - if (ignoreOptionNames.indexOf(name) !== -1) { - continue; - } +Collection.prototype.findOne = function() { + throw new Error('Collection#findOne unimplemented by driver'); +}; - if (_validOptions.indexOf(name) === -1) { - if (options.validateOptions) { - return new MongoError(`option ${name} is not supported`); - } else { - emitWarningOnce(`the options [${name}] is not supported`); - } - } +/** + * Abstract method that drivers must implement. + */ - if (legacyOptionNames.indexOf(name) !== -1) { - emitWarningOnce( - `the server/replset/mongos/db options are deprecated, ` + - `all their options are supported at the top level of the options object [${validOptionNames}]` - ); - } - } - } +Collection.prototype.find = function() { + throw new Error('Collection#find unimplemented by driver'); +}; - const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => { - obj[name.toLowerCase()] = name; - return obj; - }, {}); +/** + * Abstract method that drivers must implement. + */ - 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 - ); - } - } +Collection.prototype.insert = function() { + throw new Error('Collection#insert unimplemented by driver'); +}; - // Clear out all events - function clearAllEvents(topology) { - monitoringEvents.forEach((event) => topology.removeAllListeners(event)); - } +/** + * Abstract method that drivers must implement. + */ - // Collect all events in order from SDAM - function collectEvents(mongoClient, topology) { - let MongoClient = loadClient(); - const collectedEvents = []; +Collection.prototype.insertOne = function() { + throw new Error('Collection#insertOne unimplemented by driver'); +}; - 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, - }); - } - }); - }); - } +/** + * Abstract method that drivers must implement. + */ - return collectedEvents; - } +Collection.prototype.insertMany = function() { + throw new Error('Collection#insertMany unimplemented by driver'); +}; - function resolveTLSOptions(options) { - if (options.tls == null) { - return; - } +/** + * Abstract method that drivers must implement. + */ - ["sslCA", "sslKey", "sslCert"].forEach((optionName) => { - if (options[optionName]) { - options[optionName] = fs.readFileSync(options[optionName]); - } - }); - } +Collection.prototype.save = function() { + throw new Error('Collection#save unimplemented by driver'); +}; - function connect(mongoClient, url, options, callback) { - options = Object.assign({}, options); +/** + * Abstract method that drivers must implement. + */ - // If callback is null throw an exception - if (callback == null) { - throw new Error("no callback function provided"); - } +Collection.prototype.update = function() { + throw new Error('Collection#update unimplemented by driver'); +}; - let didRequestAuthentication = false; - const logger = Logger("MongoClient", options); +/** + * Abstract method that drivers must implement. + */ - // Did we pass in a Server/ReplSet/Mongos - if ( - url instanceof Server || - url instanceof ReplSet || - url instanceof Mongos - ) { - return connectWithUrl(mongoClient, url, options, connectCallback); - } +Collection.prototype.getIndexes = function() { + throw new Error('Collection#getIndexes unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ - const useNewUrlParser = options.useNewUrlParser !== false; +Collection.prototype.mapReduce = function() { + throw new Error('Collection#mapReduce unimplemented by driver'); +}; - const parseFn = useNewUrlParser ? parse : legacyParse; - const transform = useNewUrlParser - ? transformUrlOptions - : legacyTransformUrlOptions; +/** + * Abstract method that drivers must implement. + */ - parseFn(url, options, (err, _object) => { - // Do not attempt to connect if parsing error - if (err) return callback(err); +Collection.prototype.watch = function() { + throw new Error('Collection#watch unimplemented by driver'); +}; - // Flatten - const object = transform(_object); +/*! + * ignore + */ - // Parse the string - const _finalOptions = createUnifiedOptions(object, options); +Collection.prototype._shouldBufferCommands = function _shouldBufferCommands() { + const opts = this.opts; - // Check if we have connection and socket timeout set - if (_finalOptions.socketTimeoutMS == null) - _finalOptions.socketTimeoutMS = 0; - 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 (opts.bufferCommands != null) { + return opts.bufferCommands; + } + if (opts && opts.schemaUserProvidedOptions != null && opts.schemaUserProvidedOptions.bufferCommands != null) { + return opts.schemaUserProvidedOptions.bufferCommands; + } - if (_finalOptions.db_options && _finalOptions.db_options.auth) { - delete _finalOptions.db_options.auth; - } + return this.conn._shouldBufferCommands(); +}; - // resolve tls options if needed - resolveTLSOptions(_finalOptions); +/*! + * ignore + */ - // Store the merged options object - mongoClient.s.options = _finalOptions; +Collection.prototype._getBufferTimeoutMS = function _getBufferTimeoutMS() { + const conn = this.conn; + const opts = this.opts; - // Apply read and write concern from parsed url - mongoClient.s.readPreference = - ReadPreference.fromOptions(_finalOptions); - mongoClient.s.writeConcern = WriteConcern.fromOptions(_finalOptions); + if (opts.bufferTimeoutMS != null) { + return opts.bufferTimeoutMS; + } + if (opts && opts.schemaUserProvidedOptions != null && opts.schemaUserProvidedOptions.bufferTimeoutMS != null) { + return opts.schemaUserProvidedOptions.bufferTimeoutMS; + } + if (conn.config.bufferTimeoutMS != null) { + return conn.config.bufferTimeoutMS; + } + if (conn.base != null && conn.base.get('bufferTimeoutMS') != null) { + return conn.base.get('bufferTimeoutMS'); + } + return 10000; +}; - // Failure modes - if (object.servers.length === 0) { - return callback( - new Error("connection string must contain at least one seed host") - ); - } +/*! + * Module exports. + */ - if (_finalOptions.auth && !_finalOptions.credentials) { - try { - didRequestAuthentication = true; - _finalOptions.credentials = generateCredentials( - mongoClient, - _finalOptions.auth.user, - _finalOptions.auth.password, - _finalOptions - ); - } catch (err) { - return callback(err); - } - } +module.exports = Collection; - if (_finalOptions.useUnifiedTopology) { - return createTopology( - mongoClient, - "unified", - _finalOptions, - connectCallback - ); - } - emitWarningOnce( - "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." - ); +/***/ }), - // 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); - } - }); +/***/ 370: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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); - } +"use strict"; - // Return a more specific error message for MongoClient.connect - return callback(new MongoError(warningMessage)); - } - if (didRequestAuthentication) { - mongoClient.emit("authenticated", null, true); - } +/*! + * Module dependencies. + */ - // Return the error and db instance - callback(err, topology); - } - } +const ChangeStream = __nccwpck_require__(1662); +const EventEmitter = __nccwpck_require__(8614).EventEmitter; +const Schema = __nccwpck_require__(7606); +const Collection = __nccwpck_require__(2324).get().Collection; +const STATES = __nccwpck_require__(932); +const MongooseError = __nccwpck_require__(4327); +const PromiseProvider = __nccwpck_require__(5176); +const ServerSelectionError = __nccwpck_require__(3070); +const applyPlugins = __nccwpck_require__(6990); +const promiseOrCallback = __nccwpck_require__(4046); +const get = __nccwpck_require__(8730); +const immediate = __nccwpck_require__(4830); +const mongodb = __nccwpck_require__(8821); +const pkg = __nccwpck_require__(306); +const utils = __nccwpck_require__(9232); +const processConnectionOptions = __nccwpck_require__(2448); + +const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; +const sessionNewDocuments = __nccwpck_require__(3240).sessionNewDocuments; + +/*! + * A list of authentication mechanisms that don't require a password for authentication. + * This is used by the authMechanismDoesNotRequirePassword method. + * + * @api private + */ +const noPasswordAuthMechanisms = [ + 'MONGODB-X509' +]; - function connectWithUrl(mongoClient, url, options, connectCallback) { - // Set the topology - assignTopology(mongoClient, url); +/** + * Connection constructor + * + * For practical reasons, a Connection equals a Db. + * + * @param {Mongoose} base a mongoose instance + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `connecting`: Emitted when `connection.openUri()` is executed on this connection. + * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios. + * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connection's models. + * @event `disconnecting`: Emitted when `connection.close()` was executed. + * @event `disconnected`: Emitted after getting disconnected from the db. + * @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connection's models. + * @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successful connection. + * @event `error`: Emitted when an error occurs on this connection. + * @event `fullsetup`: Emitted after the driver has connected to primary and all secondaries if specified in the connection string. + * @api public + */ - // Add listeners - addListeners(mongoClient, url); +function Connection(base) { + this.base = base; + this.collections = {}; + this.models = {}; + this.config = {}; + this.replica = false; + this.options = null; + this.otherDbs = []; // FIXME: To be replaced with relatedDbs + this.relatedDbs = {}; // Hashmap of other dbs that share underlying connection + this.states = STATES; + this._readyState = STATES.disconnected; + this._closeCalled = false; + this._hasOpened = false; + this.plugins = []; + if (typeof base === 'undefined' || !base.connections.length) { + this.id = 0; + } else { + this.id = base.connections.length; + } + this._queue = []; +} - // Propagate the events to the client - relayEvents(mongoClient, url); +/*! + * Inherit from EventEmitter + */ - let finalOptions = Object.assign({}, options); +Connection.prototype.__proto__ = EventEmitter.prototype; - // 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 - ); - } +/** + * Connection ready state + * + * - 0 = disconnected + * - 1 = connected + * - 2 = connecting + * - 3 = disconnecting + * + * Each state change emits its associated event name. + * + * ####Example + * + * conn.on('connected', callback); + * conn.on('disconnected', callback); + * + * @property readyState + * @memberOf Connection + * @instance + * @api public + */ - 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); - } - } +Object.defineProperty(Connection.prototype, 'readyState', { + get: function() { + return this._readyState; + }, + set: function(val) { + if (!(val in STATES)) { + throw new Error('Invalid connection state: ' + val); + } - return url.connect(finalOptions, connectCallback); + if (this._readyState !== val) { + this._readyState = val; + // [legacy] loop over the otherDbs on this connection and change their state + for (const db of this.otherDbs) { + db.readyState = val; } - 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); - }; + if (STATES.connected === val) { + this._hasOpened = true; } - function createServer(mongoClient, options, callback) { - // Pass in the promise library - options.promiseLibrary = mongoClient.s.promiseLibrary; + this.emit(STATES[val]); + } + } +}); - // Set default options - const servers = translateOptions(options); +/** + * Gets the value of the option `key`. Equivalent to `conn.options[key]` + * + * ####Example: + * + * conn.get('test'); // returns the 'test' value + * + * @param {String} key + * @method get + * @api public + */ - const server = servers[0]; +Connection.prototype.get = function(key) { + if (this.config.hasOwnProperty(key)) { + return this.config[key]; + } - // Propagate the events to the client - const collectedEvents = collectEvents(mongoClient, server); + return get(this.options, key); +}; - // 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); - } +/** + * Sets the value of the option `key`. Equivalent to `conn.options[key] = val` + * + * Supported options include: + * + * - `maxTimeMS`: Set [`maxTimeMS`](/docs/api.html#query_Query-maxTimeMS) for all queries on this connection. + * + * ####Example: + * + * conn.set('test', 'foo'); + * conn.get('test'); // 'foo' + * conn.options.test; // 'foo' + * + * @param {String} key + * @param {Any} val + * @method set + * @api public + */ - // Fire all the events - replayEvents(mongoClient, collectedEvents); - // Otherwise callback - callback(err, topology); - }); - } +Connection.prototype.set = function(key, val) { + if (this.config.hasOwnProperty(key)) { + this.config[key] = val; + return val; + } - 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" - ); - } - }); - } + this.options = this.options || {}; + this.options[key] = val; + return val; +}; - function createTopology(mongoClient, topologyType, options, callback) { - // Pass in the promise library - options.promiseLibrary = mongoClient.s.promiseLibrary; +/** + * A hash of the collections associated with this connection + * + * @property collections + * @memberOf Connection + * @instance + * @api public + */ - const translationOptions = {}; - if (topologyType === "unified") - translationOptions.createServers = false; +Connection.prototype.collections; - // Set default options - const servers = translateOptions(options, translationOptions); +/** + * The name of the database this connection points to. + * + * ####Example + * + * mongoose.createConnection('mongodb://localhost:27017/mydb').name; // "mydb" + * + * @property name + * @memberOf Connection + * @instance + * @api public + */ - // determine CSFLE support - if (options.autoEncryption != null) { - const Encrypter = __nccwpck_require__(3012).Encrypter; - options.encrypter = new Encrypter(mongoClient, options); - options.autoEncrypter = options.encrypter.autoEncrypter; - } +Connection.prototype.name; - // 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); - } +/** + * A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing + * a map from model names to models. Contains all models that have been + * added to this connection using [`Connection#model()`](/docs/api/connection.html#connection_Connection-model). + * + * ####Example + * + * const conn = mongoose.createConnection(); + * const Test = conn.model('Test', mongoose.Schema({ name: String })); + * + * Object.keys(conn.models).length; // 1 + * conn.models.Test === Test; // true + * + * @property models + * @memberOf Connection + * @instance + * @api public + */ - // Add listeners - addListeners(mongoClient, topology); +Connection.prototype.models; - // Propagate the events to the client - relayEvents(mongoClient, topology); +/** + * A number identifier for this connection. Used for debugging when + * you have [multiple connections](/docs/connections.html#multiple_connections). + * + * ####Example + * + * // The default connection has `id = 0` + * mongoose.connection.id; // 0 + * + * // If you create a new connection, Mongoose increments id + * const conn = mongoose.createConnection(); + * conn.id; // 1 + * + * @property id + * @memberOf Connection + * @instance + * @api public + */ - // Open the connection - assignTopology(mongoClient, topology); +Connection.prototype.id; - // initialize CSFLE if requested - if (options.autoEncrypter) { - options.autoEncrypter.init((err) => { - if (err) { - callback(err); - return; - } +/** + * The plugins that will be applied to all models created on this connection. + * + * ####Example: + * + * const db = mongoose.createConnection('mongodb://localhost:27017/mydb'); + * db.plugin(() => console.log('Applied')); + * db.plugins.length; // 1 + * + * db.model('Test', new Schema({})); // Prints "Applied" + * + * @property plugins + * @memberOf Connection + * @instance + * @api public + */ - topology.connect(options, (err) => { - if (err) { - topology.close(true); - callback(err); - return; - } +Object.defineProperty(Connection.prototype, 'plugins', { + configurable: false, + enumerable: true, + writable: true +}); - options.encrypter.connectInternalClient((error) => { - if (error) return callback(error); - callback(undefined, topology); - }); - }); - }); +/** + * The host name portion of the URI. If multiple hosts, such as a replica set, + * this will contain the first host name in the URI + * + * ####Example + * + * mongoose.createConnection('mongodb://localhost:27017/mydb').host; // "localhost" + * + * @property host + * @memberOf Connection + * @instance + * @api public + */ - return; - } +Object.defineProperty(Connection.prototype, 'host', { + configurable: true, + enumerable: true, + writable: true +}); - // otherwise connect normally - topology.connect(options, (err) => { - if (err) { - topology.close(true); - return callback(err); - } +/** + * The port portion of the URI. If multiple hosts, such as a replica set, + * this will contain the port from the first host name in the URI. + * + * ####Example + * + * mongoose.createConnection('mongodb://localhost:27017/mydb').port; // 27017 + * + * @property port + * @memberOf Connection + * @instance + * @api public + */ - callback(undefined, topology); - return; - }); - } +Object.defineProperty(Connection.prototype, 'port', { + configurable: true, + enumerable: true, + writable: true +}); - function createUnifiedOptions(finalOptions, options) { - const childOptions = [ - "mongos", - "server", - "db", - "replset", - "db_options", - "server_options", - "rs_options", - "mongos_options", - ]; - const noMerge = ["readconcern", "compression", "autoencryption"]; - const skip = ["w", "wtimeout", "j", "journal", "fsync", "writeconcern"]; +/** + * The username specified in the URI + * + * ####Example + * + * mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').user; // "val" + * + * @property user + * @memberOf Connection + * @instance + * @api public + */ - for (const name in options) { - if (skip.indexOf(name.toLowerCase()) !== -1) { - continue; - } else 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]; - } - } - } +Object.defineProperty(Connection.prototype, 'user', { + configurable: true, + enumerable: true, + writable: true +}); - // Handle write concern keys separately, since `options` may have the keys at the top level or - // under `options.writeConcern`. The final merged keys will be under `finalOptions.writeConcern`. - // This way, `fromOptions` will warn once if `options` is using deprecated write concern options - const optionsWriteConcern = WriteConcern.fromOptions(options); - if (optionsWriteConcern) { - finalOptions.writeConcern = Object.assign( - {}, - finalOptions.writeConcern, - optionsWriteConcern - ); - } +/** + * The password specified in the URI + * + * ####Example + * + * mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').pass; // "psw" + * + * @property pass + * @memberOf Connection + * @instance + * @api public + */ - return finalOptions; - } +Object.defineProperty(Connection.prototype, 'pass', { + configurable: true, + enumerable: true, + writable: true +}); - function generateCredentials(client, username, password, options) { - options = Object.assign({}, options); +/** + * The mongodb.Db instance, set when the connection is opened + * + * @property db + * @memberOf Connection + * @instance + * @api public + */ - // 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; +Connection.prototype.db; - // authMechanism - const authMechanismRaw = options.authMechanism || "DEFAULT"; - const authMechanism = authMechanismRaw.toUpperCase(); - const mechanismProperties = options.authMechanismProperties; +/** + * The MongoClient instance this connection uses to talk to MongoDB. Mongoose automatically sets this property + * when the connection is opened. + * + * @property client + * @memberOf Connection + * @instance + * @api public + */ - if (!VALID_AUTH_MECHANISMS.has(authMechanism)) { - throw MongoError.create({ - message: `authentication mechanism ${authMechanismRaw} not supported', options.authMechanism`, - driver: true, - }); - } +Connection.prototype.client; - return new MongoCredentials({ - mechanism: AUTH_MECHANISM_INTERNAL_MAP[authMechanism], - mechanismProperties, - source, - username, - password, - }); - } +/** + * A hash of the global options that are associated with this connection + * + * @property config + * @memberOf Connection + * @instance + * @api public + */ - function legacyTransformUrlOptions(object) { - return mergeOptions(createUnifiedOptions({}, object), object, false); - } +Connection.prototype.config; - 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]; - } - } +/** + * Helper for `createCollection()`. Will explicitly create the given collection + * with specified options. Used to create [capped collections](https://docs.mongodb.com/manual/core/capped-collections/) + * and [views](https://docs.mongodb.com/manual/core/views/) from mongoose. + * + * Options are passed down without modification to the [MongoDB driver's `createCollection()` function](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection) + * + * @method createCollection + * @param {string} collection The collection to create + * @param {Object} [options] see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection) + * @param {Function} [callback] + * @return {Promise} + * @api public + */ - return target; - } +Connection.prototype.createCollection = _wrapConnHelper(function createCollection(collection, options, cb) { + if (typeof options === 'function') { + cb = options; + options = {}; + } + this.db.createCollection(collection, options, cb); +}); - 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); - }); - }); - } +/** + * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) + * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), + * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). + * + * ####Example: + * + * const session = await conn.startSession(); + * let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session }); + * await doc.remove(); + * // `doc` will always be null, even if reading from a replica set + * // secondary. Without causal consistency, it is possible to + * // get a doc back from the below query if the query reads from a + * // secondary that is experiencing replication lag. + * doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' }); + * + * + * @method startSession + * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) + * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency + * @param {Function} [callback] + * @return {Promise} promise that resolves to a MongoDB driver `ClientSession` + * @api public + */ - // - // 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 - ); - } - } +Connection.prototype.startSession = _wrapConnHelper(function startSession(options, cb) { + if (typeof options === 'function') { + cb = options; + options = null; + } + const session = this.client.startSession(options); + cb(null, session); +}); + +/** + * _Requires MongoDB >= 3.6.0._ Executes the wrapped async function + * in a transaction. Mongoose will commit the transaction if the + * async function executes successfully and attempt to retry if + * there was a retriable error. + * + * Calls the MongoDB driver's [`session.withTransaction()`](http://mongodb.github.io/node-mongodb-native/3.5/api/ClientSession.html#withTransaction), + * but also handles resetting Mongoose document state as shown below. + * + * ####Example: + * + * const doc = new Person({ name: 'Will Riker' }); + * await db.transaction(async function setRank(session) { + * doc.rank = 'Captain'; + * await doc.save({ session }); + * doc.isNew; // false + * + * // Throw an error to abort the transaction + * throw new Error('Oops!'); + * },{ readPreference: 'primary' }).catch(() => {}); + * + * // true, `transaction()` reset the document's state because the + * // transaction was aborted. + * doc.isNew; + * + * @method transaction + * @param {Function} fn Function to execute in a transaction + * @param {mongodb.TransactionOptions} [options] Optional settings for the transaction + * @return {Promise} promise that is fulfilled if Mongoose successfully committed the transaction, or rejects if the transaction was aborted or if Mongoose failed to commit the transaction. If fulfilled, the promise resolves to a MongoDB command result. + * @api public + */ - 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]; +Connection.prototype.transaction = function transaction(fn, options) { + return this.startSession().then(session => { + session[sessionNewDocuments] = new Map(); + return session.withTransaction(() => fn(session), options). + then(res => { + delete session[sessionNewDocuments]; + return res; + }). + catch(err => { + // If transaction was aborted, we need to reset newly + // inserted documents' `isNew`. + for (const doc of session[sessionNewDocuments].keys()) { + const state = session[sessionNewDocuments].get(doc); + if (state.hasOwnProperty('isNew')) { + doc.$isNew = state.$isNew; + } + if (state.hasOwnProperty('versionKey')) { + doc.set(doc.schema.options.versionKey, state.versionKey); } - } - 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; + for (const path of state.modifiedPaths) { + doc.$__.activePaths.paths[path] = 'modify'; + doc.$__.activePaths.states.modify[path] = true; } - if (object.auth.username) { - object.auth.user = object.auth.username; + for (const path of state.atomics.keys()) { + const val = doc.$__getValue(path); + if (val == null) { + continue; + } + val[arrayAtomicsSymbol] = state.atomics.get(path); } } + delete session[sessionNewDocuments]; + throw err; + }); + }); +}; - if (_object.defaultDatabase) { - object.dbName = _object.defaultDatabase; - } +/** + * Helper for `dropCollection()`. Will delete the given collection, including + * all documents and indexes. + * + * @method dropCollection + * @param {string} collection The collection to delete + * @param {Function} [callback] + * @return {Promise} + * @api public + */ - if (object.maxPoolSize) { - object.poolSize = object.maxPoolSize; - } +Connection.prototype.dropCollection = _wrapConnHelper(function dropCollection(collection, cb) { + this.db.dropCollection(collection, cb); +}); - if (object.readConcernLevel) { - object.readConcern = new ReadConcern(object.readConcernLevel); - } +/** + * Helper for `dropDatabase()`. Deletes the given database, including all + * collections, documents, and indexes. + * + * ####Example: + * + * const conn = mongoose.createConnection('mongodb://localhost:27017/mydb'); + * // Deletes the entire 'mydb' database + * await conn.dropDatabase(); + * + * @method dropDatabase + * @param {Function} [callback] + * @return {Promise} + * @api public + */ - if (object.wTimeoutMS) { - object.wtimeout = object.wTimeoutMS; - object.wTimeoutMS = undefined; - } +Connection.prototype.dropDatabase = _wrapConnHelper(function dropDatabase(cb) { + // If `dropDatabase()` is called, this model's collection will not be + // init-ed. It is sufficiently common to call `dropDatabase()` after + // `mongoose.connect()` but before creating models that we want to + // support this. See gh-6967 + for (const name of Object.keys(this.models)) { + delete this.models[name].$init; + } + this.db.dropDatabase(cb); +}); - if (_object.srvHost) { - object.srvHost = _object.srvHost; - } +/*! + * ignore + */ - // Any write concern options from the URL will be top-level, so we manually - // move them options under `object.writeConcern` to avoid warnings later - const wcKeys = ["w", "wtimeout", "j", "journal", "fsync"]; - for (const key of wcKeys) { - if (object[key] !== undefined) { - if (object.writeConcern === undefined) object.writeConcern = {}; - object.writeConcern[key] = object[key]; - object[key] = undefined; +function _wrapConnHelper(fn) { + return function() { + const cb = arguments.length > 0 ? arguments[arguments.length - 1] : null; + const argsWithoutCb = typeof cb === 'function' ? + Array.prototype.slice.call(arguments, 0, arguments.length - 1) : + Array.prototype.slice.call(arguments); + const disconnectedError = new MongooseError('Connection ' + this.id + + ' was disconnected when calling `' + fn.name + '`'); + + return promiseOrCallback(cb, cb => { + immediate(() => { + if ((this.readyState === STATES.connecting || this.readyState === STATES.disconnected) && this._shouldBufferCommands()) { + this._queue.push({ fn: fn, ctx: this, args: argsWithoutCb.concat([cb]) }); + } else if (this.readyState === STATES.disconnected && this.db == null) { + cb(disconnectedError); + } else { + try { + fn.apply(this, argsWithoutCb.concat([cb])); + } catch (err) { + return cb(err); } } + }); + }); + }; +} - return object; - } +/*! + * ignore + */ + +Connection.prototype._shouldBufferCommands = function _shouldBufferCommands() { + if (this.config.bufferCommands != null) { + return this.config.bufferCommands; + } + if (this.base.get('bufferCommands') != null) { + return this.base.get('bufferCommands'); + } + return true; +}; + +/** + * error + * + * Graceful error handling, passes error to callback + * if available, else emits error on the connection. + * + * @param {Error} err + * @param {Function} callback optional + * @api private + */ + +Connection.prototype.error = function(err, callback) { + if (callback) { + callback(err); + return null; + } + if (this.listeners('error').length > 0) { + this.emit('error', err); + } + return Promise.reject(err); +}; + +/** + * Called when the connection is opened + * + * @api private + */ + +Connection.prototype.onOpen = function() { + this.readyState = STATES.connected; + + for (const d of this._queue) { + d.fn.apply(d.ctx, d.args); + } + this._queue = []; + + // avoid having the collection subscribe to our event emitter + // to prevent 0.3 warning + for (const i in this.collections) { + if (utils.object.hasOwnProperty(this.collections, i)) { + this.collections[i].onOpen(); + } + } + + this.emit('open'); +}; + +/** + * Opens the connection with a URI using `MongoClient.connect()`. + * + * @param {String} uri The URI to connect with. + * @param {Object} [options] Passed on to http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect + * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. + * @param {Number} [options.bufferTimeoutMS=10000] Mongoose specific option. If `bufferCommands` is true, Mongoose will throw an error after `bufferTimeoutMS` if the operation is still buffered. + * @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string. + * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. + * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. + * @param {Number} [options.maxPoolSize=100] The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). + * @param {Number} [options.minPoolSize=0] The minimum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). + * @param {Number} [options.serverSelectionTimeoutMS] If `useUnifiedTopology = true`, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for `serverSelectionTimeoutMS` milliseconds before erroring out. If not set, the MongoDB driver defaults to using `30000` (30 seconds). + * @param {Number} [options.heartbeatFrequencyMS] If `useUnifiedTopology = true`, the MongoDB driver sends a heartbeat every `heartbeatFrequencyMS` to check on the status of the connection. A heartbeat is subject to `serverSelectionTimeoutMS`, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a `'disconnected'` event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits `'disconnected'`. We recommend you do **not** set this setting below 1000, too many heartbeats can lead to performance degradation. + * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. + * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html). + * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback). + * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes. + * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both. + * @param {Boolean} [options.autoCreate=false] Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. + * @param {Function} [callback] + * @returns {Connection} this + * @api public + */ - function translateOptions(options, translationOptions) { - translationOptions = Object.assign( - {}, - { createServers: true }, - translationOptions - ); +Connection.prototype.openUri = function(uri, options, callback) { + if (typeof options === 'function') { + callback = options; + options = null; + } - // 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 - ); - } + if (['string', 'number'].indexOf(typeof options) !== -1) { + throw new MongooseError('Mongoose 5.x no longer supports ' + + '`mongoose.connect(host, dbname, port)` or ' + + '`mongoose.createConnection(host, dbname, port)`. See ' + + 'http://mongoosejs.com/docs/connections.html for supported connection syntax'); + } - // 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; - } + if (typeof uri !== 'string') { + throw new MongooseError('The `uri` parameter to `openUri()` must be a ' + + `string, got "${typeof uri}". Make sure the first parameter to ` + + '`mongoose.connect()` or `mongoose.createConnection()` is a string.'); + } - // Do we have maxStalenessSeconds - if (options.maxStalenessSeconds) { - options.readPreference.maxStalenessSeconds = - options.maxStalenessSeconds; - } + if (callback != null && typeof callback !== 'function') { + throw new MongooseError('3rd parameter to `mongoose.connect()` or ' + + '`mongoose.createConnection()` must be a function, got "' + + typeof callback + '"'); + } - // Set the socket and connection timeouts - if (options.socketTimeoutMS == null) options.socketTimeoutMS = 0; - if (options.connectTimeoutMS == null) options.connectTimeoutMS = 10000; + if (this.readyState === STATES.connecting || this.readyState === STATES.connected) { + if (this._connectionString !== uri) { + throw new MongooseError('Can\'t call `openUri()` on an active connection with ' + + 'different connection strings. Make sure you aren\'t calling `mongoose.connect()` ' + + 'multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections'); + } - if (!translationOptions.createServers) { - return; - } + if (typeof callback === 'function') { + this.$initialConnection = this.$initialConnection.then( + () => callback(null, this), + err => callback(err) + ); + } + return this; + } - // 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); - }); - } + this._connectionString = uri; + this.readyState = STATES.connecting; + this._closeCalled = false; - module.exports = { validOptions, connect }; + const Promise = PromiseProvider.get(); + const _this = this; - /***/ - }, + options = processConnectionOptions(uri, options); - /***/ 7885: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + if (options) { + options = utils.clone(options); - const buildCountCommand = __nccwpck_require__(2296).buildCountCommand; - const OperationBase = __nccwpck_require__(1018).OperationBase; + const autoIndex = options.config && options.config.autoIndex != null ? + options.config.autoIndex : + options.autoIndex; + if (autoIndex != null) { + this.config.autoIndex = autoIndex !== false; + delete options.config; + delete options.autoIndex; + } - class CountOperation extends OperationBase { - constructor(cursor, applySkipLimit, options) { - super(options); + if ('autoCreate' in options) { + this.config.autoCreate = !!options.autoCreate; + delete options.autoCreate; + } - this.cursor = cursor; - this.applySkipLimit = applySkipLimit; - } + if ('sanitizeFilter' in options) { + this.config.sanitizeFilter = options.sanitizeFilter; + delete options.sanitizeFilter; + } - execute(callback) { - const cursor = this.cursor; - const applySkipLimit = this.applySkipLimit; - const options = this.options; + // Backwards compat + if (options.user || options.pass) { + options.auth = options.auth || {}; + options.auth.username = options.user; + options.auth.password = options.pass; - if (applySkipLimit) { - if (typeof cursor.cursorSkip() === "number") - options.skip = cursor.cursorSkip(); - if (typeof cursor.cursorLimit() === "number") - options.limit = cursor.cursorLimit(); - } + this.user = options.user; + this.pass = options.pass; + } + delete options.user; + delete options.pass; - // Ensure we have the right read preference inheritance - if (options.readPreference) { - cursor.setReadPreference(options.readPreference); - } + if (options.bufferCommands != null) { + this.config.bufferCommands = options.bufferCommands; + delete options.bufferCommands; + } + } else { + options = {}; + } - if ( - typeof options.maxTimeMS !== "number" && - cursor.cmd && - typeof cursor.cmd.maxTimeMS === "number" - ) { - options.maxTimeMS = cursor.cmd.maxTimeMS; - } + this._connectionOptions = options; + const dbName = options.dbName; + if (dbName != null) { + this.$dbName = dbName; + } + delete options.dbName; - let finalOptions = {}; - finalOptions.skip = options.skip; - finalOptions.limit = options.limit; - finalOptions.hint = options.hint; - finalOptions.maxTimeMS = options.maxTimeMS; + if (!utils.hasUserDefinedProperty(options, 'driverInfo')) { + options.driverInfo = { + name: 'Mongoose', + version: pkg.version + }; + } - // Command - finalOptions.collectionName = cursor.namespace.collection; + const promise = new Promise((resolve, reject) => { + let client; + try { + client = new mongodb.MongoClient(uri, options); + } catch (error) { + _this.readyState = STATES.disconnected; + return reject(error); + } + _this.client = client; + client.setMaxListeners(0); + client.connect((error) => { + if (error) { + return reject(error); + } - let command; - try { - command = buildCountCommand(cursor, cursor.cmd.query, finalOptions); - } catch (err) { - return callback(err); - } + _setClient(_this, client, options, dbName); - // Set cursor server to the same as the topology - cursor.server = cursor.topology.s.coreTopology; + resolve(_this); + }); + }); - // Execute the command - cursor.topology.command( - cursor.namespace.withCollection("$cmd"), - command, - cursor.options, - (err, result) => { - callback(err, result ? result.result.n : null); - } - ); - } + const serverSelectionError = new ServerSelectionError(); + this.$initialConnection = promise. + then(() => this). + catch(err => { + this.readyState = STATES.disconnected; + if (err != null && err.name === 'MongoServerSelectionError') { + err = serverSelectionError.assimilateError(err); } - module.exports = CountOperation; + if (this.listeners('error').length > 0) { + immediate(() => this.emit('error', err)); + } + throw err; + }); - /***/ - }, + if (callback != null) { + this.$initialConnection = this.$initialConnection.then( + () => { callback(null, this); return this; }, + err => callback(err) + ); + } - /***/ 5131: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + return this.$initialConnection; +}; - const AggregateOperation = __nccwpck_require__(1554); +/*! + * ignore + */ - class CountDocumentsOperation extends AggregateOperation { - constructor(collection, query, options) { - const pipeline = [{ $match: query }]; - if (typeof options.skip === "number") { - pipeline.push({ $skip: options.skip }); - } +function _setClient(conn, client, options, dbName) { + const db = dbName != null ? client.db(dbName) : client.db(); + conn.db = db; + conn.client = client; + conn.host = get(client, 's.options.hosts.0.host', void 0); + conn.port = get(client, 's.options.hosts.0.port', void 0); + conn.name = dbName != null ? dbName : get(client, 's.options.dbName', void 0); + conn._closeCalled = client._closeCalled; + + const _handleReconnect = () => { + // If we aren't disconnected, we assume this reconnect is due to a + // socket timeout. If there's no activity on a socket for + // `socketTimeoutMS`, the driver will attempt to reconnect and emit + // this event. + if (conn.readyState !== STATES.connected) { + conn.readyState = STATES.connected; + conn.emit('reconnect'); + conn.emit('reconnected'); + conn.onOpen(); + } + }; - if (typeof options.limit === "number") { - pipeline.push({ $limit: options.limit }); - } + const type = get(client, 'topology.description.type', ''); - pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); + if (type === 'Single') { + client.on('serverDescriptionChanged', ev => { + const newDescription = ev.newDescription; + if (newDescription.type === 'Unknown') { + conn.readyState = STATES.disconnected; + } else { + _handleReconnect(); + } + }); + } else if (type.startsWith('ReplicaSet')) { + client.on('topologyDescriptionChanged', ev => { + // Emit disconnected if we've lost connectivity to the primary + const description = ev.newDescription; + if (conn.readyState === STATES.connected && description.type !== 'ReplicaSetWithPrimary') { + // Implicitly emits 'disconnected' + conn.readyState = STATES.disconnected; + } else if (conn.readyState === STATES.disconnected && description.type === 'ReplicaSetWithPrimary') { + _handleReconnect(); + } + }); + } - super(collection, pipeline, options); - } + conn.onOpen(); - execute(server, callback) { - super.execute(server, (err, result) => { - if (err) { - callback(err, null); - return; - } + for (const i in conn.collections) { + if (utils.object.hasOwnProperty(conn.collections, i)) { + conn.collections[i].onOpen(); + } + } +} - // 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; - } +/** + * Closes the connection + * + * @param {Boolean} [force] optional + * @param {Function} [callback] optional + * @return {Promise} + * @api public + */ - const docs = response.cursor.firstBatch; - callback(null, docs.length ? docs[0].n : 0); - }); - } - } +Connection.prototype.close = function(force, callback) { + if (typeof force === 'function') { + callback = force; + force = false; + } - module.exports = CountDocumentsOperation; + this.$wasForceClosed = !!force; - /***/ - }, + return promiseOrCallback(callback, cb => { + this._close(force, cb); + }); +}; - /***/ 5561: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - const CommandOperation = __nccwpck_require__(499); - const applyWriteConcern = __nccwpck_require__(1371).applyWriteConcern; - const loadCollection = __nccwpck_require__(8275).loadCollection; - const MongoError = __nccwpck_require__(3994).MongoError; - const ReadPreference = __nccwpck_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]; - } +/** + * Handles closing the connection + * + * @param {Boolean} force + * @param {Function} callback + * @api private + */ +Connection.prototype._close = function(force, callback) { + const _this = this; + const closeCalled = this._closeCalled; + this._closeCalled = true; + if (this.client != null) { + this.client._closeCalled = true; + } + + switch (this.readyState) { + case STATES.disconnected: + if (closeCalled) { + callback(); + } else { + this.doClose(force, function(err) { + if (err) { + return callback(err); } + _this.onClose(force); + callback(null); + }); + } + break; - return cmd; + case STATES.connected: + this.readyState = STATES.disconnecting; + this.doClose(force, function(err) { + if (err) { + return callback(err); } + _this.onClose(force); + callback(null); + }); - execute(callback) { - const db = this.db; - const name = this.name; - const options = this.options; - const Collection = loadCollection(); + break; + case STATES.connecting: + this.once('open', function() { + _this.close(callback); + }); + break; - let listCollectionOptions = Object.assign( - { nameOnly: true, strict: false }, - options - ); - listCollectionOptions = applyWriteConcern( - listCollectionOptions, - { db }, - listCollectionOptions - ); + case STATES.disconnecting: + this.once('close', function() { + callback(); + }); + break; + } - function done(err) { - if (err) { - return callback(err); - } + return this; +}; - try { - callback( - null, - new Collection( - db, - db.s.topology, - db.databaseName, - name, - db.s.pkFactory, - options - ) - ); - } catch (err) { - callback(err); - } - } +/** + * Called when the connection closes + * + * @api private + */ - const strictMode = listCollectionOptions.strict; - if (strictMode) { - db.listCollections({ name }, listCollectionOptions) - .setReadPreference(ReadPreference.PRIMARY) - .toArray((err, collections) => { - if (err) { - return callback(err); - } +Connection.prototype.onClose = function(force) { + this.readyState = STATES.disconnected; - if (collections.length > 0) { - return callback( - new MongoError( - `Collection ${name} already exists. Currently in strict mode.` - ) - ); - } + // avoid having the collection subscribe to our event emitter + // to prevent 0.3 warning + for (const i in this.collections) { + if (utils.object.hasOwnProperty(this.collections, i)) { + this.collections[i].onClose(force); + } + } - super.execute(done); - }); + this.emit('close', force); - return; - } + for (const db of this.otherDbs) { + db.close(force); + } +}; - // otherwise just execute the command - super.execute(done); - } - } +/** + * Retrieves a collection, creating it if not cached. + * + * Not typically needed by applications. Just talk to your collection through your model. + * + * @param {String} name of the collection + * @param {Object} [options] optional collection options + * @return {Collection} collection instance + * @api public + */ - defineAspects(CreateCollectionOperation, Aspect.WRITE_OPERATION); - module.exports = CreateCollectionOperation; +Connection.prototype.collection = function(name, options) { + const defaultOptions = { + autoIndex: this.config.autoIndex != null ? this.config.autoIndex : this.base.options.autoIndex, + autoCreate: this.config.autoCreate != null ? this.config.autoCreate : this.base.options.autoCreate + }; + options = Object.assign({}, defaultOptions, options ? utils.clone(options) : {}); + options.$wasForceClosed = this.$wasForceClosed; + if (!(name in this.collections)) { + this.collections[name] = new Collection(name, this, options); + } + return this.collections[name]; +}; - /***/ - }, +/** + * Declares a plugin executed on all schemas you pass to `conn.model()` + * + * Equivalent to calling `.plugin(fn)` on each schema you create. + * + * ####Example: + * const db = mongoose.createConnection('mongodb://localhost:27017/mydb'); + * db.plugin(() => console.log('Applied')); + * db.plugins.length; // 1 + * + * db.model('Test', new Schema({})); // Prints "Applied" + * + * @param {Function} fn plugin callback + * @param {Object} [opts] optional options + * @return {Connection} this + * @see plugins ./plugins.html + * @api public + */ - /***/ 6394: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - const CommandOperationV2 = __nccwpck_require__(1189); - const MongoError = __nccwpck_require__(3994).MongoError; - const parseIndexOptions = __nccwpck_require__(1371).parseIndexOptions; - const maxWireVersion = __nccwpck_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: 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; - } +Connection.prototype.plugin = function(fn, opts) { + this.plugins.push([fn, opts]); + return this; +}; - this.indexes = indexes; - } +/** + * Defines or retrieves a model. + * + * const mongoose = require('mongoose'); + * const db = mongoose.createConnection(..); + * db.model('Venue', new Schema(..)); + * const Ticket = db.model('Ticket', new Schema(..)); + * const Venue = db.model('Venue'); + * + * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._ + * + * ####Example: + * + * const schema = new Schema({ name: String }, { collection: 'actor' }); + * + * // or + * + * schema.set('collection', 'actor'); + * + * // or + * + * const collectionName = 'actor' + * const M = conn.model('Actor', schema, collectionName) + * + * @param {String|Function} name the model name or class extending Model + * @param {Schema} [schema] a schema. necessary when defining a model + * @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name + * @param {Object} [options] + * @param {Boolean} [options.overwriteModels=false] If true, overwrite existing models with the same name to avoid `OverwriteModelError` + * @see Mongoose#model #index_Mongoose-model + * @return {Model} The compiled model + * @api public + */ - /** - * @ignore - */ - execute(server, callback) { - const options = this.options; - const indexes = this.indexes; +Connection.prototype.model = function(name, schema, collection, options) { + if (!(this instanceof Connection)) { + throw new MongooseError('`connection.model()` should not be run with ' + + '`new`. If you are doing `new db.model(foo)(bar)`, use ' + + '`db.model(foo)(bar)` instead'); + } - const serverWireVersion = maxWireVersion(server); + let fn; + if (typeof name === 'function') { + fn = name; + name = fn.name; + } - // 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; - } + // collection name discovery + if (typeof schema === 'string') { + collection = schema; + schema = false; + } - if (indexes[i].name == null) { - const keys = []; + if (utils.isObject(schema) && !(schema instanceof this.base.Schema)) { + schema = new Schema(schema); + } + if (schema && !schema.instanceOfSchema) { + throw new Error('The 2nd parameter to `mongoose.model()` should be a ' + + 'schema or a POJO'); + } - for (let name in indexes[i].key) { - keys.push(`${name}_${indexes[i].key[name]}`); - } + const defaultOptions = { cache: false, overwriteModels: this.base.options.overwriteModels }; + const opts = Object.assign(defaultOptions, options, { connection: this }); + if (this.models[name] && !collection && opts.overwriteModels !== true) { + // model exists but we are not subclassing with custom collection + if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) { + throw new MongooseError.OverwriteModelError(name); + } + return this.models[name]; + } - // Set the name - indexes[i].name = keys.join("_"); - } - } + let model; - const cmd = { createIndexes: this.collection, indexes }; + if (schema && schema.instanceOfSchema) { + applyPlugins(schema, this.plugins, null, '$connectionPluginsApplied'); - 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; - } + // compile a model + model = this.base._model(fn || name, schema, collection, opts); - // collation is set on each index, it should not be defined at the root - this.options.collation = undefined; + // only the first model with this name is cached to allow + // for one-offs with custom collection names etc. + if (!this.models[name]) { + this.models[name] = model; + } - super.executeCommand(server, cmd, (err, result) => { - if (err) { - callback(err); - return; - } + // Errors handled internally, so safe to ignore error + model.init(function $modelInitNoop() {}); - callback( - null, - this.onlyReturnNameOfCreatedIndex ? indexes[0].name : result - ); - }); - } - } + return model; + } - defineAspects(CreateIndexesOperation, [ - Aspect.WRITE_OPERATION, - Aspect.EXECUTE_WITH_SELECTION, - ]); + if (this.models[name] && collection) { + // subclassing current model with alternate collection + model = this.models[name]; + schema = model.prototype.schema; + const sub = model.__subclass(this, schema, collection); + // do not cache the sub model + return sub; + } - module.exports = CreateIndexesOperation; + if (!model) { + throw new MongooseError.MissingSchemaError(name); + } - /***/ - }, + if (this === model.prototype.db + && (!collection || collection === model.collection.name)) { + // model already uses this connection. - /***/ 3554: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const buildCountCommand = __nccwpck_require__(6716).buildCountCommand; - const handleCallback = __nccwpck_require__(1371).handleCallback; - const MongoError = __nccwpck_require__(3994).MongoError; - const push = Array.prototype.push; - const CursorState = __nccwpck_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); - } + // only the first model with this name is cached to allow + // for one-offs with custom collection names etc. + if (!this.models[name]) { + this.models[name] = model; + } - if ( - typeof opts.maxTimeMS !== "number" && - cursor.cmd && - typeof cursor.cmd.maxTimeMS === "number" - ) { - opts.maxTimeMS = cursor.cmd.maxTimeMS; - } + return model; + } + this.models[name] = model.__subclass(this, schema, collection); + return this.models[name]; +}; + +/** + * Removes the model named `name` from this connection, if it exists. You can + * use this function to clean up any models you created in your tests to + * prevent OverwriteModelErrors. + * + * ####Example: + * + * conn.model('User', new Schema({ name: String })); + * console.log(conn.model('User')); // Model object + * conn.deleteModel('User'); + * console.log(conn.model('User')); // undefined + * + * // Usually useful in a Mocha `afterEach()` hook + * afterEach(function() { + * conn.deleteModel(/.+/); // Delete every model + * }); + * + * @api public + * @param {String|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. + * @return {Connection} this + */ - let options = {}; - options.skip = opts.skip; - options.limit = opts.limit; - options.hint = opts.hint; - options.maxTimeMS = opts.maxTimeMS; +Connection.prototype.deleteModel = function(name) { + if (typeof name === 'string') { + const model = this.model(name); + if (model == null) { + return this; + } + const collectionName = model.collection.name; + delete this.models[name]; + delete this.collections[collectionName]; + + this.emit('deleteModel', model); + } else if (name instanceof RegExp) { + const pattern = name; + const names = this.modelNames(); + for (const name of names) { + if (pattern.test(name)) { + this.deleteModel(name); + } + } + } else { + throw new Error('First parameter to `deleteModel()` must be a string ' + + 'or regexp, got "' + name + '"'); + } - // Command - options.collectionName = cursor.namespace.collection; + return this; +}; - let command; - try { - command = buildCountCommand(cursor, cursor.cmd.query, options); - } catch (err) { - return callback(err); - } +/** + * Watches the entire underlying database for changes. Similar to + * [`Model.watch()`](/docs/api/model.html#model_Model.watch). + * + * This function does **not** trigger any middleware. In particular, it + * does **not** trigger aggregate middleware. + * + * The ChangeStream object is an event emitter that emits the following events: + * + * - 'change': A change occurred, see below example + * - 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow [this GitHub issue](https://github.com/Automattic/mongoose/issues/6799) for updates. + * - 'end': Emitted if the underlying stream is closed + * - 'close': Emitted if the underlying stream is closed + * + * ####Example: + * + * const User = conn.model('User', new Schema({ name: String })); + * + * const changeStream = conn.watch().on('change', data => console.log(data)); + * + * // Triggers a 'change' event on the change stream. + * await User.create({ name: 'test' }); + * + * @api public + * @param {Array} [pipeline] + * @param {Object} [options] passed without changes to [the MongoDB driver's `Db#watch()` function](https://mongodb.github.io/node-mongodb-native/3.4/api/Db.html#watch) + * @return {ChangeStream} mongoose-specific change stream wrapper, inherits from EventEmitter + */ - // Set cursor server to the same as the topology - cursor.server = cursor.topology.s.coreTopology; +Connection.prototype.watch = function(pipeline, options) { + const disconnectedError = new MongooseError('Connection ' + this.id + + ' was disconnected when calling `watch()`'); - // Execute the command - cursor.topology.command( - cursor.namespace.withCollection("$cmd"), - command, - cursor.options, - (err, result) => { - callback(err, result ? result.result.n : null); - } - ); + const changeStreamThunk = cb => { + immediate(() => { + if (this.readyState === STATES.connecting) { + this.once('open', function() { + const driverChangeStream = this.db.watch(pipeline, options); + cb(null, driverChangeStream); + }); + } else if (this.readyState === STATES.disconnected && this.db == null) { + cb(disconnectedError); + } else { + const driverChangeStream = this.db.watch(pipeline, options); + cb(null, driverChangeStream); } + }); + }; - /** - * 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 }) - ); - } + const changeStream = new ChangeStream(changeStreamThunk, pipeline, options); + return changeStream; +}; - if (cursor.s.state === CursorState.INIT) { - cursor.s.state = CursorState.OPEN; - } +/** + * Returns a promise that resolves when this connection + * successfully connects to MongoDB, or rejects if this connection failed + * to connect. + * + * ####Example: + * const conn = await mongoose.createConnection('mongodb://localhost:27017/test'). + * asPromise(); + * conn.readyState; // 1, means Mongoose is connected + * + * @api public + * @return {Promise} + */ - // 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) - ); - } +Connection.prototype.asPromise = function asPromise() { + return this.$initialConnection; +}; - if (handleCallback(callback, null, item) === false) return; - each(cursor, callback); - }); - } - } +/** + * Returns an array of model names created on this connection. + * @api public + * @return {Array} + */ + +Connection.prototype.modelNames = function() { + return Object.keys(this.models); +}; + +/** + * @brief Returns if the connection requires authentication after it is opened. Generally if a + * username and password are both provided than authentication is needed, but in some cases a + * password is not required. + * @api private + * @return {Boolean} true if the connection should be authenticated after it is opened, otherwise false. + */ +Connection.prototype.shouldAuthenticate = function() { + return this.user != null && + (this.pass != null || this.authMechanismDoesNotRequirePassword()); +}; + +/** + * @brief Returns a boolean value that specifies if the current authentication mechanism needs a + * password to authenticate according to the auth objects passed into the openUri methods. + * @api private + * @return {Boolean} true if the authentication mechanism specified in the options object requires + * a password, otherwise false. + */ +Connection.prototype.authMechanismDoesNotRequirePassword = function() { + if (this.options && this.options.auth) { + return noPasswordAuthMechanisms.indexOf(this.options.auth.authMechanism) >= 0; + } + return true; +}; + +/** + * @brief Returns a boolean value that specifies if the provided objects object provides enough + * data to authenticate with. Generally this is true if the username and password are both specified + * but in some authentication methods, a password is not required for authentication so only a username + * is required. + * @param {Object} [options] the options object passed into the openUri methods. + * @api private + * @return {Boolean} true if the provided options object provides enough data to authenticate with, + * otherwise false. + */ +Connection.prototype.optionsProvideAuthenticationData = function(options) { + return (options) && + (options.user) && + ((options.pass) || this.authMechanismDoesNotRequirePassword()); +}; + +/** + * Returns the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance + * that this connection uses to talk to MongoDB. + * + * ####Example: + * const conn = await mongoose.createConnection('mongodb://localhost:27017/test'); + * + * conn.getClient(); // MongoClient { ... } + * + * @api public + * @return {MongoClient} + */ - // 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; - } +Connection.prototype.getClient = function getClient() { + return this.client; +}; - /** - * 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 = []; +/** + * Set the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance + * that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to + * reuse it. + * + * ####Example: + * const client = await mongodb.MongoClient.connect('mongodb://localhost:27017/test'); + * + * const conn = mongoose.createConnection().setClient(client); + * + * conn.getClient(); // MongoClient { ... } + * conn.readyState; // 1, means 'CONNECTED' + * + * @api public + * @return {Connection} this + */ - // Reset cursor - cursor.rewind(); - cursor.s.state = CursorState.INIT; +Connection.prototype.setClient = function setClient(client) { + if (!(client instanceof mongodb.MongoClient)) { + throw new MongooseError('Must call `setClient()` with an instance of MongoClient'); + } + if (this.readyState !== STATES.disconnected) { + throw new MongooseError('Cannot call `setClient()` on a connection that is already connected.'); + } + if (client.topology == null) { + throw new MongooseError('Cannot call `setClient()` with a MongoClient that you have not called `connect()` on yet.'); + } - // Fetch all the documents - const fetchDocs = () => { - cursor._next((err, doc) => { - if (err) { - return handleCallback(callback, err); - } + this._connectionString = client.s.url; + _setClient(this, client, { useUnifiedTopology: client.s.options.useUnifiedTopology }, client.s.options.dbName); - if (doc == null) { - return cursor.close({ skipKillCursors: true }, () => - handleCallback(callback, null, items) - ); - } + return this; +}; - // Add doc to items - items.push(doc); +Connection.prototype.syncIndexes = async function syncIndexes() { + const result = {}; + for (const model in this.models) { + result[model] = await this.model(model).syncIndexes(); + } + return result; +}; - // Get all buffered objects - if (cursor.bufferedCount() > 0) { - let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); +/** + * Switches to a different database using the same connection pool. + * + * Returns a new connection object, with the new db. + * + * @method useDb + * @memberOf Connection + * @param {String} name The database name + * @param {Object} [options] + * @param {Boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object. + * @param {Boolean} [options.noListener=false] If true, the connection object will not make the db listen to events on the original connection. See [issue #9961](https://github.com/Automattic/mongoose/issues/9961). + * @return {Connection} New Connection Object + * @api public + */ - // Transform the doc if transform method added - if ( - cursor.s.transforms && - typeof cursor.s.transforms.doc === "function" - ) { - docs = docs.map(cursor.s.transforms.doc); - } +/*! + * Module exports. + */ - push.apply(items, docs); - } +Connection.STATES = STATES; +module.exports = Connection; - // Attempt a fetch - fetchDocs(); - }); - }; - fetchDocs(); - } +/***/ }), - module.exports = { count, each, toArray }; +/***/ 932: +/***/ ((module, exports) => { - /***/ - }, +"use strict"; - /***/ 2226: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const applyWriteConcern = __nccwpck_require__(1371).applyWriteConcern; - const Code = __nccwpck_require__(3994).BSON.Code; - const debugOptions = __nccwpck_require__(1371).debugOptions; - const handleCallback = __nccwpck_require__(1371).handleCallback; - const MongoError = __nccwpck_require__(3994).MongoError; - const parseIndexOptions = __nccwpck_require__(1371).parseIndexOptions; - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const toError = __nccwpck_require__(1371).toError; - const extractCommand = __nccwpck_require__(7703).extractCommand; - const CONSTANTS = __nccwpck_require__(147); - const MongoDBNamespace = __nccwpck_require__(1371).MongoDBNamespace; - - const debugFields = [ - "authSource", - "w", - "wtimeout", - "j", - "native_parser", - "forceServerObjectId", - "serializeFunctions", - "raw", - "promoteLongs", - "promoteValues", - "promoteBuffers", - "bsonRegExp", - "bufferMaxEntries", - "numberOfRetries", - "retryMiliSeconds", - "readPreference", - "pkFactory", - "parentDb", - "promiseLibrary", - "noListener", - ]; +/*! + * Connection states + */ - /** - * 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")); +const STATES = module.exports = exports = Object.create(null); - // Attempt to run using createIndexes command - createIndexUsingCreateIndexes( - db, - name, - fieldOrSpec, - finalOptions, - (err, result) => { - if (err == null) return handleCallback(callback, err, result); +const disconnected = 'disconnected'; +const connected = 'connected'; +const connecting = 'connecting'; +const disconnecting = 'disconnecting'; +const uninitialized = 'uninitialized'; - /** - * 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); - } - ); - } - ); - } +STATES[0] = disconnected; +STATES[1] = connected; +STATES[2] = connecting; +STATES[3] = disconnecting; +STATES[99] = uninitialized; - // Add listeners to topology - function createListener(db, e, object) { - function listener(err) { - if (object.listeners(e).length > 0) { - object.emit(e, err, db); +STATES[disconnected] = 0; +STATES[connected] = 1; +STATES[connecting] = 2; +STATES[disconnecting] = 3; +STATES[uninitialized] = 99; - // 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"]; - } +/***/ 3890: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Set primary read preference - options.readPreference = new ReadPreference(ReadPreference.PRIMARY); +"use strict"; +/*! + * Module dependencies. + */ - // 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()) { - const extractedCommand = extractCommand(command); - db.s.logger.debug( - `executing command ${JSON.stringify( - extractedCommand.shouldRedact - ? `${extractedCommand.name} details REDACTED` - : 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); - } - ); - } +const MongooseError = __nccwpck_require__(5953); +const Readable = __nccwpck_require__(2413).Readable; +const promiseOrCallback = __nccwpck_require__(4046); +const eachAsync = __nccwpck_require__(9893); +const immediate = __nccwpck_require__(4830); +const util = __nccwpck_require__(1669); - /** - * 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")); - } +/** + * An AggregationCursor is a concurrency primitive for processing aggregation + * results one document at a time. It is analogous to QueryCursor. + * + * An AggregationCursor fulfills the Node.js streams3 API, + * in addition to several other mechanisms for loading documents from MongoDB + * one at a time. + * + * Creating an AggregationCursor executes the model's pre aggregate hooks, + * but **not** the model's post aggregate hooks. + * + * Unless you're an advanced user, do **not** instantiate this class directly. + * Use [`Aggregate#cursor()`](/docs/api.html#aggregate_Aggregate-cursor) instead. + * + * @param {Aggregate} agg + * @param {Object} options + * @inherits Readable + * @event `cursor`: Emitted when the cursor is created + * @event `error`: Emitted when an error occurred + * @event `data`: Emitted when the stream is flowing and the next doc is ready + * @event `end`: Emitted when the stream is exhausted + * @api public + */ - if (err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); - } +function AggregationCursor(agg) { + // set autoDestroy=true because on node 12 it's by default false + // gh-10902 need autoDestroy to destroy correctly and emit 'close' event + Readable.call(this, { autoDestroy: true, objectMode: true }); - /** - * 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]]); - } - } + this.cursor = null; + this.agg = agg; + this._transforms = []; + const model = agg._model; + delete agg.options.cursor.useMongooseAggCursor; + this._mongooseOptions = {}; - return info; - } + _init(model, this, agg); +} - // 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)); - }); - } +util.inherits(AggregationCursor, Readable); - /** - * 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); - } - } +/*! + * ignore + */ - // 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, - }); - } - } +function _init(model, c, agg) { + if (!model.collection.buffer) { + model.hooks.execPre('aggregate', agg, function() { + c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {}); + c.emit('cursor', c.cursor); + }); + } else { + model.collection.emitter.once('queue', function() { + model.hooks.execPre('aggregate', agg, function() { + c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {}); + c.emit('cursor', c.cursor); + }); + }); + } +} - /** - * 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, - }; +/*! + * Necessary to satisfy the Readable API + */ - // 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]; - } +AggregationCursor.prototype._read = function() { + const _this = this; + _next(this, function(error, doc) { + if (error) { + return _this.emit('error', error); + } + if (!doc) { + _this.push(null); + _this.cursor.close(function(error) { + if (error) { + return _this.emit('error', error); } + }); + return; + } + _this.push(doc); + }); +}; - if (selector["unique"] == null) selector["unique"] = finalUnique; +if (Symbol.asyncIterator != null) { + const msg = 'Mongoose does not support using async iterators with an ' + + 'existing aggregation cursor. See http://bit.ly/mongoose-async-iterate-aggregation'; - // 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", - ]); + AggregationCursor.prototype[Symbol.asyncIterator] = function() { + throw new MongooseError(msg); + }; +} - for (let optionName in options) { - if (keysToOmit.indexOf(optionName) === -1) { - indexes[0][optionName] = options[optionName]; - } - } +/** + * Registers a transform function which subsequently maps documents retrieved + * via the streams interface or `.next()` + * + * ####Example + * + * // Map documents returned by `data` events + * Thing. + * find({ name: /^hello/ }). + * cursor(). + * map(function (doc) { + * doc.foo = "bar"; + * return doc; + * }) + * on('data', function(doc) { console.log(doc.foo); }); + * + * // Or map documents returned by `.next()` + * const cursor = Thing.find({ name: /^hello/ }). + * cursor(). + * map(function (doc) { + * doc.foo = "bar"; + * return doc; + * }); + * cursor.next(function(error, doc) { + * console.log(doc.foo); + * }); + * + * @param {Function} fn + * @return {AggregationCursor} + * @api public + * @method map + */ - // Get capabilities - const capabilities = db.s.topology.capabilities(); +AggregationCursor.prototype.map = function(fn) { + this._transforms.push(fn); + return this; +}; - // 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); - } +/*! + * Marks this cursor as errored + */ - // Create command, apply write concern to command - const cmd = applyWriteConcern( - { createIndexes: name, indexes }, - { db }, - options - ); +AggregationCursor.prototype._markError = function(error) { + this._error = error; + return this; +}; - // ReadPreference primary - options.readPreference = ReadPreference.PRIMARY; +/** + * Marks this cursor as closed. Will stop streaming and subsequent calls to + * `next()` will error. + * + * @param {Function} callback + * @return {Promise} + * @api public + * @method close + * @emits close + * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close + */ - // 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); - }); +AggregationCursor.prototype.close = function(callback) { + return promiseOrCallback(callback, cb => { + this.cursor.close(error => { + if (error) { + cb(error); + return this.listeners('error').length > 0 && this.emit('error', error); } + this.emit('close'); + cb(null); + }); + }); +}; - module.exports = { - createListener, - createIndex, - ensureIndex, - evaluate, - executeCommand, - executeDbAdminCommand, - indexInformation, - profilingInfo, - validateDatabaseName, - }; - - /***/ - }, +/** + * Get the next document from this cursor. Will return `null` when there are + * no documents left. + * + * @param {Function} callback + * @return {Promise} + * @api public + * @method next + */ - /***/ 323: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +AggregationCursor.prototype.next = function(callback) { + return promiseOrCallback(callback, cb => { + _next(this, cb); + }); +}; - const OperationBase = __nccwpck_require__(1018).OperationBase; - const removeDocuments = __nccwpck_require__(2296).removeDocuments; - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; +/** + * Execute `fn` for every document in the cursor. If `fn` returns a promise, + * will wait for the promise to resolve before iterating on to the next one. + * Returns a promise that resolves when done. + * + * @param {Function} fn + * @param {Object} [options] + * @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1. + * @param {Function} [callback] executed when all docs have been processed + * @return {Promise} + * @api public + * @method eachAsync + */ - class DeleteManyOperation extends OperationBase { - constructor(collection, filter, options) { - super(options); +AggregationCursor.prototype.eachAsync = function(fn, opts, callback) { + const _this = this; + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + opts = opts || {}; - this.collection = collection; - this.filter = filter; - } + return eachAsync(function(cb) { return _next(_this, cb); }, fn, opts, callback); +}; - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const options = this.options; +/** + * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js + * You do not need to call this function explicitly, the JavaScript runtime + * will call it for you. + * + * ####Example + * + * // Async iterator without explicitly calling `cursor()`. Mongoose still + * // creates an AggregationCursor instance internally. + * const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]); + * for await (const doc of agg) { + * console.log(doc.name); + * } + * + * // You can also use an AggregationCursor instance for async iteration + * const cursor = Model.aggregate([{ $match: { age: { $gte: 25 } } }]).cursor(); + * for await (const doc of cursor) { + * console.log(doc.name); + * } + * + * Node.js 10.x supports async iterators natively without any flags. You can + * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). + * + * **Note:** This function is not set if `Symbol.asyncIterator` is undefined. If + * `Symbol.asyncIterator` is undefined, that means your Node.js version does not + * support async iterators. + * + * @method Symbol.asyncIterator + * @memberOf AggregationCursor + * @instance + * @api public + */ - options.single = false; - removeDocuments(coll, filter, options, (err, r) => { - if (callback == null) return; - if (err && callback) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); +if (Symbol.asyncIterator != null) { + AggregationCursor.prototype[Symbol.asyncIterator] = function() { + return this.transformNull()._transformForAsyncIterator(); + }; +} - // If an explain operation was executed, don't process the server results - if (this.explain) return callback(undefined, r.result); +/*! + * ignore + */ - r.deletedCount = r.result.n; - callback(null, r); - }); - } - } +AggregationCursor.prototype._transformForAsyncIterator = function() { + if (this._transforms.indexOf(_transformForAsyncIterator) === -1) { + this.map(_transformForAsyncIterator); + } + return this; +}; - defineAspects(DeleteManyOperation, [Aspect.EXPLAINABLE]); +/*! + * ignore + */ - module.exports = DeleteManyOperation; +AggregationCursor.prototype.transformNull = function(val) { + if (arguments.length === 0) { + val = true; + } + this._mongooseOptions.transformNull = val; + return this; +}; - /***/ - }, +/*! + * ignore + */ - /***/ 6352: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +function _transformForAsyncIterator(doc) { + return doc == null ? { done: true } : { value: doc, done: false }; +} - const OperationBase = __nccwpck_require__(1018).OperationBase; - const removeDocuments = __nccwpck_require__(2296).removeDocuments; - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; +/** + * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag). + * Useful for setting the `noCursorTimeout` and `tailable` flags. + * + * @param {String} flag + * @param {Boolean} value + * @return {AggregationCursor} this + * @api public + * @method addCursorFlag + */ - class DeleteOneOperation extends OperationBase { - constructor(collection, filter, options) { - super(options); +AggregationCursor.prototype.addCursorFlag = function(flag, value) { + const _this = this; + _waitForCursor(this, function() { + _this.cursor.addCursorFlag(flag, value); + }); + return this; +}; - this.collection = collection; - this.filter = filter; - } +/*! + * ignore + */ - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const options = this.options; +function _waitForCursor(ctx, cb) { + if (ctx.cursor) { + return cb(); + } + ctx.once('cursor', function() { + cb(); + }); +} + +/*! + * Get the next doc from the underlying cursor and mongooseify it + * (populate, etc.) + */ - options.single = true; - removeDocuments(coll, filter, options, (err, r) => { - if (callback == null) return; - if (err && callback) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); +function _next(ctx, cb) { + let callback = cb; + if (ctx._transforms.length) { + callback = function(err, doc) { + if (err || (doc === null && !ctx._mongooseOptions.transformNull)) { + return cb(err, doc); + } + cb(err, ctx._transforms.reduce(function(doc, fn) { + return fn(doc); + }, doc)); + }; + } - // If an explain operation was executed, don't process the server results - if (this.explain) return callback(undefined, r.result); + if (ctx._error) { + return immediate(function() { + callback(ctx._error); + }); + } - r.deletedCount = r.result.n; - callback(null, r); - }); - } + if (ctx.cursor) { + return ctx.cursor.next(function(error, doc) { + if (error) { + return callback(error); + } + if (!doc) { + return callback(null, null); } - defineAspects(DeleteOneOperation, [Aspect.EXPLAINABLE]); + callback(null, doc); + }); + } else { + ctx.once('cursor', function() { + _next(ctx, cb); + }); + } +} - module.exports = DeleteOneOperation; +module.exports = AggregationCursor; - /***/ - }, - /***/ 6469: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - const CommandOperationV2 = __nccwpck_require__(1189); - const decorateWithCollation = - __nccwpck_require__(1371).decorateWithCollation; - const decorateWithReadConcern = - __nccwpck_require__(1371).decorateWithReadConcern; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const MongoError = __nccwpck_require__(9386).MongoError; - - /** - * 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; - } +/***/ 1662: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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, - }; +"use strict"; - // Add maxTimeMS if defined - if (typeof options.maxTimeMS === "number") { - cmd.maxTimeMS = options.maxTimeMS; - } - // Do we have a readConcern specified - decorateWithReadConcern(cmd, coll, options); +/*! + * Module dependencies. + */ - // Have we specified collation - try { - decorateWithCollation(cmd, coll, options); - } catch (err) { - return callback(err, null); - } +const EventEmitter = __nccwpck_require__(8614).EventEmitter; - if (this.explain && maxWireVersion(server) < 4) { - callback( - new MongoError(`server does not support explain on distinct`) - ); - return; - } +/*! + * ignore + */ - super.executeCommand(server, cmd, (err, result) => { - if (err) { - callback(err); - return; - } +class ChangeStream extends EventEmitter { + constructor(changeStreamThunk, pipeline, options) { + super(); - callback( - null, - this.options.full || this.explain ? result : result.values - ); - }); - } + this.driverChangeStream = null; + this.closed = false; + this.pipeline = pipeline; + this.options = options; + + // This wrapper is necessary because of buffering. + changeStreamThunk((err, driverChangeStream) => { + if (err != null) { + this.emit('error', err); + return; } - defineAspects(DistinctOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION, - Aspect.EXPLAINABLE, - ]); + this.driverChangeStream = driverChangeStream; + this._bindEvents(); + this.emit('ready'); + }); + } - module.exports = DistinctOperation; + _bindEvents() { + this.driverChangeStream.on('close', () => { + this.closed = true; + }); - /***/ - }, + ['close', 'change', 'end', 'error'].forEach(ev => { + this.driverChangeStream.on(ev, data => this.emit(ev, data)); + }); + } - /***/ 2360: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + _queue(cb) { + this.once('ready', () => cb()); + } - const Aspect = __nccwpck_require__(1018).Aspect; - const CommandOperation = __nccwpck_require__(499); - const defineAspects = __nccwpck_require__(1018).defineAspects; - const handleCallback = __nccwpck_require__(1371).handleCallback; + close() { + this.closed = true; + if (this.driverChangeStream) { + this.driverChangeStream.close(); + } + } +} - class DropOperation extends CommandOperation { - constructor(db, options) { - const finalOptions = Object.assign({}, options, db.s.options); +/*! + * ignore + */ - if (options.session) { - finalOptions.session = options.session; - } +module.exports = ChangeStream; - 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); +/***/ 3588: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - class DropCollectionOperation extends DropOperation { - constructor(db, name, options) { - super(db, options); +"use strict"; +/*! + * Module dependencies. + */ - this.name = name; - this.namespace = `${db.namespace}.${name}`; - } - _buildCommand() { - return { drop: this.name }; - } + +const Readable = __nccwpck_require__(2413).Readable; +const promiseOrCallback = __nccwpck_require__(4046); +const eachAsync = __nccwpck_require__(9893); +const helpers = __nccwpck_require__(5299); +const immediate = __nccwpck_require__(4830); +const util = __nccwpck_require__(1669); + +/** + * A QueryCursor is a concurrency primitive for processing query results + * one document at a time. A QueryCursor fulfills the Node.js streams3 API, + * in addition to several other mechanisms for loading documents from MongoDB + * one at a time. + * + * QueryCursors execute the model's pre `find` hooks before loading any documents + * from MongoDB, and the model's post `find` hooks after loading each document. + * + * Unless you're an advanced user, do **not** instantiate this class directly. + * Use [`Query#cursor()`](/docs/api.html#query_Query-cursor) instead. + * + * @param {Query} query + * @param {Object} options query options passed to `.find()` + * @inherits Readable + * @event `cursor`: Emitted when the cursor is created + * @event `error`: Emitted when an error occurred + * @event `data`: Emitted when the stream is flowing and the next doc is ready + * @event `end`: Emitted when the stream is exhausted + * @api public + */ + +function QueryCursor(query, options) { + // set autoDestroy=true because on node 12 it's by default false + // gh-10902 need autoDestroy to destroy correctly and emit 'close' event + Readable.call(this, { autoDestroy: true, objectMode: true }); + + this.cursor = null; + this.query = query; + const _this = this; + const model = query.model; + this._mongooseOptions = {}; + this._transforms = []; + this.model = model; + this.options = options || {}; + + model.hooks.execPre('find', query, (err) => { + if (err != null) { + _this._markError(err); + _this.listeners('error').length > 0 && _this.emit('error', err); + return; + } + this._transforms = this._transforms.concat(query._transforms.slice()); + if (this.options.transform) { + this._transforms.push(options.transform); + } + // Re: gh-8039, you need to set the `cursor.batchSize` option, top-level + // `batchSize` option doesn't work. + if (this.options.batchSize) { + this.options.cursor = options.cursor || {}; + this.options.cursor.batchSize = options.batchSize; + + // Max out the number of documents we'll populate in parallel at 5000. + this.options._populateBatchSize = Math.min(this.options.batchSize, 5000); + } + model.collection.find(query._conditions, this.options, (err, cursor) => { + if (err != null) { + _this._markError(err); + _this.listeners('error').length > 0 && _this.emit('error', _this._error); + return; } - class DropDatabaseOperation extends DropOperation { - _buildCommand() { - return { dropDatabase: 1 }; - } + if (_this._error) { + cursor.close(function() {}); + _this.listeners('error').length > 0 && _this.emit('error', _this._error); } + _this.cursor = cursor; + _this.emit('cursor', cursor); + }); + }); +} - module.exports = { - DropOperation, - DropCollectionOperation, - DropDatabaseOperation, - }; +util.inherits(QueryCursor, Readable); - /***/ - }, +/*! + * Necessary to satisfy the Readable API + */ - /***/ 3560: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +QueryCursor.prototype._read = function() { + const _this = this; + _next(this, function(error, doc) { + if (error) { + return _this.emit('error', error); + } + if (!doc) { + _this.push(null); + _this.cursor.close(function(error) { + if (error) { + return _this.emit('error', error); + } + }); + return; + } + _this.push(doc); + }); +}; - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - const CommandOperation = __nccwpck_require__(499); - const applyWriteConcern = __nccwpck_require__(1371).applyWriteConcern; - const handleCallback = __nccwpck_require__(1371).handleCallback; +/** + * Registers a transform function which subsequently maps documents retrieved + * via the streams interface or `.next()` + * + * ####Example + * + * // Map documents returned by `data` events + * Thing. + * find({ name: /^hello/ }). + * cursor(). + * map(function (doc) { + * doc.foo = "bar"; + * return doc; + * }) + * on('data', function(doc) { console.log(doc.foo); }); + * + * // Or map documents returned by `.next()` + * const cursor = Thing.find({ name: /^hello/ }). + * cursor(). + * map(function (doc) { + * doc.foo = "bar"; + * return doc; + * }); + * cursor.next(function(error, doc) { + * console.log(doc.foo); + * }); + * + * @param {Function} fn + * @return {QueryCursor} + * @api public + * @method map + */ - class DropIndexOperation extends CommandOperation { - constructor(collection, indexName, options) { - super(collection.s.db, options, collection); +QueryCursor.prototype.map = function(fn) { + this._transforms.push(fn); + return this; +}; - this.collection = collection; - this.indexName = indexName; - } +/*! + * Marks this cursor as errored + */ - _buildCommand() { - const collection = this.collection; - const indexName = this.indexName; - const options = this.options; +QueryCursor.prototype._markError = function(error) { + this._error = error; + return this; +}; - let cmd = { - dropIndexes: collection.collectionName, - index: indexName, - }; +/** + * Marks this cursor as closed. Will stop streaming and subsequent calls to + * `next()` will error. + * + * @param {Function} callback + * @return {Promise} + * @api public + * @method close + * @emits close + * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close + */ - // Decorate command with writeConcern if supported - cmd = applyWriteConcern( - cmd, - { db: collection.s.db, collection }, - options - ); +QueryCursor.prototype.close = function(callback) { + return promiseOrCallback(callback, cb => { + this.cursor.close(error => { + if (error) { + cb(error); + return this.listeners('error').length > 0 && this.emit('error', error); + } + this.emit('close'); + cb(null); + }); + }, this.model.events); +}; - return cmd; - } +/** + * Get the next document from this cursor. Will return `null` when there are + * no documents left. + * + * @param {Function} callback + * @return {Promise} + * @api public + * @method next + */ - execute(callback) { - // Execute command - super.execute((err, result) => { - if (typeof callback !== "function") return; - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); - } +QueryCursor.prototype.next = function(callback) { + return promiseOrCallback(callback, cb => { + _next(this, function(error, doc) { + if (error) { + return cb(error); } + cb(null, doc); + }); + }, this.model.events); +}; - defineAspects(DropIndexOperation, Aspect.WRITE_OPERATION); +/** + * Execute `fn` for every document in the cursor. If `fn` returns a promise, + * will wait for the promise to resolve before iterating on to the next one. + * Returns a promise that resolves when done. + * + * ####Example + * + * // Iterate over documents asynchronously + * Thing. + * find({ name: /^hello/ }). + * cursor(). + * eachAsync(async function (doc, i) { + * doc.foo = doc.bar + i; + * await doc.save(); + * }) + * + * @param {Function} fn + * @param {Object} [options] + * @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1. + * @param {Function} [callback] executed when all docs have been processed + * @return {Promise} + * @api public + * @method eachAsync + */ - module.exports = DropIndexOperation; +QueryCursor.prototype.eachAsync = function(fn, opts, callback) { + const _this = this; + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + opts = opts || {}; - /***/ - }, + return eachAsync(function(cb) { return _next(_this, cb); }, fn, opts, callback); +}; - /***/ 5328: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +/** + * The `options` passed in to the `QueryCursor` constructor. + * + * @api public + * @property options + */ - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - const DropIndexOperation = __nccwpck_require__(3560); - const handleCallback = __nccwpck_require__(1371).handleCallback; +QueryCursor.prototype.options; - class DropIndexesOperation extends DropIndexOperation { - constructor(collection, options) { - super(collection, "*", options); - } +/** + * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag). + * Useful for setting the `noCursorTimeout` and `tailable` flags. + * + * @param {String} flag + * @param {Boolean} value + * @return {AggregationCursor} this + * @api public + * @method addCursorFlag + */ - execute(callback) { - super.execute((err) => { - if (err) return handleCallback(callback, err, false); - handleCallback(callback, null, true); - }); - } - } +QueryCursor.prototype.addCursorFlag = function(flag, value) { + const _this = this; + _waitForCursor(this, function() { + _this.cursor.addCursorFlag(flag, value); + }); + return this; +}; - defineAspects(DropIndexesOperation, Aspect.WRITE_OPERATION); +/*! + * ignore + */ - module.exports = DropIndexesOperation; +QueryCursor.prototype.transformNull = function(val) { + if (arguments.length === 0) { + val = true; + } + this._mongooseOptions.transformNull = val; + return this; +}; - /***/ - }, +/*! + * ignore + */ - /***/ 4451: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - const CommandOperationV2 = __nccwpck_require__(1189); - - class EstimatedDocumentCountOperation extends CommandOperationV2 { - constructor(collection, query, options) { - if (typeof options === "undefined") { - options = query; - query = undefined; - } +QueryCursor.prototype._transformForAsyncIterator = function() { + if (this._transforms.indexOf(_transformForAsyncIterator) === -1) { + this.map(_transformForAsyncIterator); + } + return this; +}; - super(collection, options); - this.collectionName = collection.s.namespace.collection; - if (query) { - this.query = query; - } - } +/** + * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js). + * You do not need to call this function explicitly, the JavaScript runtime + * will call it for you. + * + * ####Example + * + * // Works without using `cursor()` + * for await (const doc of Model.find([{ $sort: { name: 1 } }])) { + * console.log(doc.name); + * } + * + * // Can also use `cursor()` + * for await (const doc of Model.find([{ $sort: { name: 1 } }]).cursor()) { + * console.log(doc.name); + * } + * + * Node.js 10.x supports async iterators natively without any flags. You can + * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). + * + * **Note:** This function is not if `Symbol.asyncIterator` is undefined. If + * `Symbol.asyncIterator` is undefined, that means your Node.js version does not + * support async iterators. + * + * @method Symbol.asyncIterator + * @memberOf Query + * @instance + * @api public + */ - execute(server, callback) { - const options = this.options; - const cmd = { count: this.collectionName }; +if (Symbol.asyncIterator != null) { + QueryCursor.prototype[Symbol.asyncIterator] = function() { + return this.transformNull()._transformForAsyncIterator(); + }; +} - if (this.query) { - cmd.query = this.query; - } +/*! + * ignore + */ - if (typeof options.skip === "number") { - cmd.skip = options.skip; - } +function _transformForAsyncIterator(doc) { + return doc == null ? { done: true } : { value: doc, done: false }; +} - if (typeof options.limit === "number") { - cmd.limit = options.limit; - } +/*! + * Get the next doc from the underlying cursor and mongooseify it + * (populate, etc.) + */ - if (options.hint) { - cmd.hint = options.hint; - } +function _next(ctx, cb) { + let callback = cb; + if (ctx._transforms.length) { + callback = function(err, doc) { + if (err || (doc === null && !ctx._mongooseOptions.transformNull)) { + return cb(err, doc); + } + cb(err, ctx._transforms.reduce(function(doc, fn) { + return fn.call(ctx, doc); + }, doc)); + }; + } - super.executeCommand(server, cmd, (err, response) => { - if (err) { - callback(err); - return; - } + if (ctx._error) { + return immediate(function() { + callback(ctx._error); + }); + } - callback(null, response.n); - }); - } + if (ctx.cursor) { + if (ctx.query._mongooseOptions.populate && !ctx._pop) { + ctx._pop = helpers.preparePopulationOptionsMQ(ctx.query, + ctx.query._mongooseOptions); + ctx._pop.__noPromise = true; + } + if (ctx.query._mongooseOptions.populate && ctx.options._populateBatchSize > 1) { + if (ctx._batchDocs && ctx._batchDocs.length) { + // Return a cached populated doc + return _nextDoc(ctx, ctx._batchDocs.shift(), ctx._pop, callback); + } else if (ctx._batchExhausted) { + // Internal cursor reported no more docs. Act the same here + return callback(null, null); + } else { + // Request as many docs as batchSize, to populate them also in batch + ctx._batchDocs = []; + return ctx.cursor.next(_onNext.bind({ ctx, callback })); } + } else { + return ctx.cursor.next(function(error, doc) { + if (error) { + return callback(error); + } + if (!doc) { + return callback(null, null); + } - defineAspects(EstimatedDocumentCountOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION, - ]); + if (!ctx.query._mongooseOptions.populate) { + return _nextDoc(ctx, doc, null, callback); + } - module.exports = EstimatedDocumentCountOperation; + ctx.query.model.populate(doc, ctx._pop, function(err, doc) { + if (err) { + return callback(err); + } + return _nextDoc(ctx, doc, ctx._pop, callback); + }); + }); + } + } else { + ctx.once('error', cb); - /***/ - }, + ctx.once('cursor', function(cursor) { + ctx.removeListener('error', cb); + if (cursor == null) { + return; + } + _next(ctx, cb); + }); + } +} - /***/ 1681: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +/*! + * ignore + */ - const OperationBase = __nccwpck_require__(1018).OperationBase; - const handleCallback = __nccwpck_require__(1371).handleCallback; - const MongoError = __nccwpck_require__(3994).MongoError; - const MongoDBNamespace = __nccwpck_require__(1371).MongoDBNamespace; +function _onNext(error, doc) { + if (error) { + return this.callback(error); + } + if (!doc) { + this.ctx._batchExhausted = true; + return _populateBatch.call(this); + } - class ExecuteDbAdminCommandOperation extends OperationBase { - constructor(db, selector, options) { - super(options); + this.ctx._batchDocs.push(doc); - this.db = db; - this.selector = selector; - } + if (this.ctx._batchDocs.length < this.ctx.options._populateBatchSize) { + // If both `batchSize` and `_populateBatchSize` are huge, calling `next()` repeatedly may + // cause a stack overflow. So make sure we clear the stack regularly. + if (this.ctx._batchDocs.length > 0 && this.ctx._batchDocs.length % 1000 === 0) { + return immediate(() => this.ctx.cursor.next(_onNext.bind(this))); + } + this.ctx.cursor.next(_onNext.bind(this)); + } else { + _populateBatch.call(this); + } +} - execute(callback) { - const db = this.db; - const selector = this.selector; - const options = this.options; +/*! + * ignore + */ - 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")); - } +function _populateBatch() { + if (!this.ctx._batchDocs.length) { + return this.callback(null, null); + } + const _this = this; + this.ctx.query.model.populate(this.ctx._batchDocs, this.ctx._pop, function(err) { + if (err) { + return _this.callback(err); + } - if (err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); - } - } + _nextDoc(_this.ctx, _this.ctx._batchDocs.shift(), _this.ctx._pop, _this.callback); + }); +} - module.exports = ExecuteDbAdminCommandOperation; +/*! + * ignore + */ - /***/ - }, +function _nextDoc(ctx, doc, pop, callback) { + if (ctx.query._mongooseOptions.lean) { + return ctx.model.hooks.execPost('find', ctx.query, [[doc]], err => { + if (err != null) { + return callback(err); + } + callback(null, doc); + }); + } - /***/ 2548: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const maybePromise = __nccwpck_require__(1371).maybePromise; - const MongoError = __nccwpck_require__(3111).MongoError; - const Aspect = __nccwpck_require__(1018).Aspect; - const OperationBase = __nccwpck_require__(1018).OperationBase; - const ReadPreference = __nccwpck_require__(4485); - const isRetryableError = __nccwpck_require__(3111).isRetryableError; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const isUnifiedTopology = __nccwpck_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, cb) { - if (topology == null) { - throw new TypeError("This method requires a valid topology instance"); - } + _create(ctx, doc, pop, (err, doc) => { + if (err != null) { + return callback(err); + } + ctx.model.hooks.execPost('find', ctx.query, [[doc]], err => { + if (err != null) { + return callback(err); + } + callback(null, doc); + }); + }); +} - if (!(operation instanceof OperationBase)) { - throw new TypeError( - "This method requires a valid operation instance" - ); - } +/*! + * ignore + */ - return maybePromise(topology, cb, (callback) => { - if ( - isUnifiedTopology(topology) && - topology.shouldCheckForSessionSupport() - ) { - // Recursive call to executeOperation after a server selection - return selectServerForSessionSupport(topology, operation, callback); - } +function _waitForCursor(ctx, cb) { + if (ctx.cursor) { + return cb(); + } + ctx.once('cursor', function(cursor) { + if (cursor == null) { + return; + } + cb(); + }); +} - // 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) { - return callback( - new MongoError("Use of expired sessions is not permitted") - ); - } - } else if (operation.session) { - // If the user passed an explicit session and we are still, after server selection, - // trying to run against a topology that doesn't support sessions we error out. - return callback( - new MongoError("Current topology does not support sessions") - ); - } +/*! + * Convert a raw doc into a full mongoose doc. + */ - function executeCallback(err, result) { - if (session && session.owner === owner) { - session.endSession(); - if (operation.session === session) { - operation.clearSession(); - } - } +function _create(ctx, doc, populatedIds, cb) { + const instance = helpers.createModel(ctx.query.model, doc, ctx.query._fields); + const opts = populatedIds ? + { populated: populatedIds } : + undefined; - callback(err, result); - } + instance.$init(doc, opts, function(err) { + if (err) { + return cb(err); + } + cb(null, instance); + }); +} - try { - if (operation.hasAspect(Aspect.EXECUTE_WITH_SELECTION)) { - executeWithServerSelection(topology, operation, executeCallback); - } else { - operation.execute(executeCallback); - } - } catch (error) { - if (session && session.owner === owner) { - session.endSession(); - if (operation.session === session) { - operation.clearSession(); - } - } +module.exports = QueryCursor; - callback(error); - } - }); - } - 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(); +/***/ 6717: +/***/ ((module, exports, __nccwpck_require__) => { - if (inTransaction && !readPreference.equals(ReadPreference.primary)) { - callback( - new MongoError( - `Read preference in a transaction must be primary, not: ${readPreference.mode}` - ) - ); +"use strict"; - return; - } - const serverSelectionOptions = { - readPreference, - session: operation.session, - }; +/*! + * Module dependencies. + */ - function callbackWithRetry(err, result) { - if (err == null) { - return callback(null, result); - } +const EventEmitter = __nccwpck_require__(8614).EventEmitter; +const InternalCache = __nccwpck_require__(5963); +const MongooseError = __nccwpck_require__(4327); +const MixedSchema = __nccwpck_require__(7495); +const ObjectExpectedError = __nccwpck_require__(2293); +const ObjectParameterError = __nccwpck_require__(3456); +const ParallelValidateError = __nccwpck_require__(3897); +const Schema = __nccwpck_require__(7606); +const StrictModeError = __nccwpck_require__(5328); +const ValidationError = __nccwpck_require__(8460); +const ValidatorError = __nccwpck_require__(6345); +const VirtualType = __nccwpck_require__(1423); +const promiseOrCallback = __nccwpck_require__(4046); +const cleanModifiedSubpaths = __nccwpck_require__(7958); +const compile = __nccwpck_require__(2096)/* .compile */ .M; +const defineKey = __nccwpck_require__(2096)/* .defineKey */ .c; +const flatten = __nccwpck_require__(3719)/* .flatten */ .x; +const flattenObjectWithDottedPaths = __nccwpck_require__(5842); +const get = __nccwpck_require__(8730); +const getEmbeddedDiscriminatorPath = __nccwpck_require__(509); +const getKeysInSchemaOrder = __nccwpck_require__(6000); +const handleSpreadDoc = __nccwpck_require__(5232); +const immediate = __nccwpck_require__(4830); +const isDefiningProjection = __nccwpck_require__(1903); +const isExclusive = __nccwpck_require__(3522); +const inspect = __nccwpck_require__(1669).inspect; +const internalToObjectOptions = __nccwpck_require__(5684)/* .internalToObjectOptions */ .h; +const markArraySubdocsPopulated = __nccwpck_require__(3515); +const mpath = __nccwpck_require__(8586); +const queryhelpers = __nccwpck_require__(5299); +const utils = __nccwpck_require__(9232); +const isPromise = __nccwpck_require__(224); + +const clone = utils.clone; +const deepEqual = utils.deepEqual; +const isMongooseObject = utils.isMongooseObject; + +const arrayAtomicsBackupSymbol = __nccwpck_require__(3240).arrayAtomicsBackupSymbol; +const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; +const documentArrayParent = __nccwpck_require__(3240).documentArrayParent; +const documentIsModified = __nccwpck_require__(3240).documentIsModified; +const documentModifiedPaths = __nccwpck_require__(3240).documentModifiedPaths; +const documentSchemaSymbol = __nccwpck_require__(3240).documentSchemaSymbol; +const getSymbol = __nccwpck_require__(3240).getSymbol; +const populateModelSymbol = __nccwpck_require__(3240).populateModelSymbol; +const scopeSymbol = __nccwpck_require__(3240).scopeSymbol; +const schemaMixedSymbol = __nccwpck_require__(1205).schemaMixedSymbol; +const parentPaths = __nccwpck_require__(8123); +let DocumentArray; +let MongooseArray; +let Embedded; + +const specialProperties = utils.specialProperties; + +/** + * The core Mongoose document constructor. You should not call this directly, + * the Mongoose [Model constructor](./api.html#Model) calls this for you. + * + * @param {Object} obj the values to set + * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data + * @param {Object} [options] various configuration options for the document + * @param {Boolean} [options.defaults=true] if `false`, skip applying default values to this document. + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `init`: Emitted on a document after it has been retrieved from the db and fully hydrated by Mongoose. + * @event `save`: Emitted when the document is successfully saved + * @api private + */ - if (!isRetryableError(err)) { - return callback(err); - } +function Document(obj, fields, skipId, options) { + if (typeof skipId === 'object' && skipId != null) { + options = skipId; + skipId = options.skipId; + } + options = Object.assign({}, options); + + // Support `browserDocument.js` syntax + if (this.$__schema == null) { + const _schema = utils.isObject(fields) && !fields.instanceOfSchema ? + new Schema(fields) : + fields; + this.$__setSchema(_schema); + fields = skipId; + skipId = options; + options = arguments[4] || {}; + } - // select a new server, and attempt to retry the operation - topology.selectServer(serverSelectionOptions, (err, server) => { - if (err || !supportsRetryableReads(server)) { - callback(err, null); - return; - } + this.$__ = new InternalCache; + this.$__.emitter = new EventEmitter(); + this.$isNew = 'isNew' in options ? options.isNew : true; - operation.execute(server, callback); - }); - } + if ('priorDoc' in options) { + this.$__.priorDoc = options.priorDoc; + } - // 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; - } + if (obj != null && typeof obj !== 'object') { + throw new ObjectParameterError(obj, 'obj', 'Document'); + } - operation.execute(server, callback); - }); - } + let defaults = true; + if (options.defaults !== undefined) { + this.$__.defaults = options.defaults; + defaults = options.defaults; + } - // The Unified Topology runs serverSelection before executing every operation - // Session support is determined by the result of a monitoring check triggered by this selection - function selectServerForSessionSupport(topology, operation, callback) { - topology.selectServer(ReadPreference.primaryPreferred, (err) => { - if (err) { - return callback(err); - } + const schema = this.$__schema; - executeOperation(topology, operation, callback); - }); - } + if (typeof fields === 'boolean' || fields === 'throw') { + this.$__.strictMode = fields; + fields = undefined; + } else { + this.$__.strictMode = schema.options.strict; + if (fields !== undefined) { + this.$__.selected = fields; + } + } - module.exports = executeOperation; + const requiredPaths = schema.requiredPaths(true); + for (const path of requiredPaths) { + this.$__.activePaths.require(path); + } - /***/ - }, + this.$__.emitter.setMaxListeners(0); - /***/ 9961: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const OperationBase = __nccwpck_require__(1018).OperationBase; - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const MongoError = __nccwpck_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 - ); - } + let exclude = null; - execute(server, callback) { - // copied from `CommandOperationV2`, to be subclassed in the future - this.server = server; + // determine if this doc is a result of a query with + // excluded fields + if (utils.isPOJO(fields)) { + exclude = isExclusive(fields); + } - // updates readPreference if setReadPreference was called on the cursor - this.readPreference = ReadPreference.resolve(this, this.options); + const hasIncludedChildren = exclude === false && fields ? + $__hasIncludedChildren(fields) : + {}; - if ( - typeof this.cmd.allowDiskUse !== "undefined" && - maxWireVersion(server) < 4 - ) { - callback( - new MongoError( - "The `allowDiskUse` option is not supported on MongoDB < 3.2" - ) - ); - return; - } + if (this._doc == null) { + this.$__buildDoc(obj, fields, skipId, exclude, hasIncludedChildren, false); - if (this.explain) { - // We need to manually ensure explain is in the options. - this.options.explain = this.explain.verbosity; - } + // By default, defaults get applied **before** setting initial values + // Re: gh-6155 + if (defaults) { + $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, true, { + isNew: this.$isNew + }); + } + } + if (obj) { + // Skip set hooks + if (this.$__original_set) { + this.$__original_set(obj, undefined, true); + } else { + this.$set(obj, undefined, true); + } - // TOOD: use `MongoDBNamespace` through and through - const cursorState = this.cursorState || {}; - server.query( - this.ns.toString(), - this.cmd, - cursorState, - this.options, - callback - ); - } - } + if (obj instanceof Document) { + this.$isNew = obj.$isNew; + } + } - defineAspects(FindOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION, - Aspect.EXPLAINABLE, - ]); + // Function defaults get applied **after** setting initial values so they + // see the full doc rather than an empty one, unless they opt out. + // Re: gh-3781, gh-6155 + if (options.willInit && defaults) { + EventEmitter.prototype.once.call(this, 'init', () => { + $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, { + isNew: this.$isNew + }); + }); + } else if (defaults) { + $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, { + isNew: this.$isNew + }); + } - module.exports = FindOperation; + this.$__._id = this._id; - /***/ - }, + if (!this.$__.strictMode && obj) { + const _this = this; + const keys = Object.keys(this._doc); - /***/ 711: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const OperationBase = __nccwpck_require__(1018).OperationBase; - const applyRetryableWrites = - __nccwpck_require__(1371).applyRetryableWrites; - const applyWriteConcern = __nccwpck_require__(1371).applyWriteConcern; - const decorateWithCollation = - __nccwpck_require__(1371).decorateWithCollation; - const executeCommand = __nccwpck_require__(2226).executeCommand; - const formattedOrderClause = - __nccwpck_require__(1371).formattedOrderClause; - const handleCallback = __nccwpck_require__(1371).handleCallback; - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const MongoError = __nccwpck_require__(9386).MongoError; - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - const decorateWithExplain = __nccwpck_require__(1371).decorateWithExplain; - - 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 - let queryObject = { - findAndModify: coll.collectionName, - query: query, - }; + keys.forEach(function(key) { + // Avoid methods, virtuals, existing fields, and `$` keys. The latter is to avoid overwriting + // Mongoose internals. + if (!(key in schema.tree) && !(key in schema.methods) && !(key in schema.virtuals) && !key.startsWith('$')) { + defineKey({ prop: key, subprops: null, prototype: _this }); + } + }); + } - if (sort) { - queryObject.sort = sort; - } + applyQueue(this); +} - queryObject.new = options.new ? true : false; - queryObject.remove = options.remove ? true : false; - queryObject.upsert = options.upsert ? true : false; +Object.defineProperty(Document.prototype, 'isNew', { + get: function() { + return this.$isNew; + }, + set: function(value) { + this.$isNew = value; + } +}); + +Object.defineProperty(Document.prototype, 'errors', { + get: function() { + return this.$errors; + }, + set: function(value) { + this.$errors = value; + } +}); +/*! + * Document exposes the NodeJS event emitter API, so you can use + * `on`, `once`, etc. + */ +utils.each( + ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', + 'removeAllListeners', 'addListener'], + function(emitterFn) { + Document.prototype[emitterFn] = function() { + return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments); + }; + Document.prototype[`$${emitterFn}`] = Document.prototype[emitterFn]; + }); - const projection = options.projection || options.fields; +Document.prototype.constructor = Document; - if (projection) { - queryObject.fields = projection; - } +for (const i in EventEmitter.prototype) { + Document[i] = EventEmitter.prototype[i]; +} - if (options.arrayFilters) { - queryObject.arrayFilters = options.arrayFilters; - } +/** + * The document's internal schema. + * + * @api private + * @property schema + * @memberOf Document + * @instance + */ - if (doc && !options.remove) { - queryObject.update = doc; - } +Document.prototype.$__schema; - if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; +/** + * The document's schema. + * + * @api public + * @property schema + * @memberOf Document + * @instance + */ - // 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; +Document.prototype.schema; - // No check on the documents - options.checkKeys = false; +/** + * Empty object that you can use for storing properties on the document. This + * is handy for passing data to middleware without conflicting with Mongoose + * internals. + * + * ####Example: + * + * schema.pre('save', function() { + * // Mongoose will set `isNew` to `false` if `save()` succeeds + * this.$locals.wasNew = this.isNew; + * }); + * + * schema.post('save', function() { + * // Prints true if `isNew` was set before `save()` + * console.log(this.$locals.wasNew); + * }); + * + * @api public + * @property $locals + * @memberOf Document + * @instance + */ - // Final options for retryable writes and write concern - options = applyRetryableWrites(options, coll.s.db); - options = applyWriteConcern( - options, - { db: coll.s.db, collection: coll }, - options - ); +Object.defineProperty(Document.prototype, '$locals', { + configurable: false, + enumerable: false, + get: function() { + if (this.$__.locals == null) { + this.$__.locals = {}; + } + return this.$__.locals; + }, + set: function(v) { + this.$__.locals = v; + } +}); - // 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; - } +/** + * Boolean flag specifying if the document is new. + * + * @api public + * @property $isNew + * @memberOf Document + * @instance + */ - options.readPreference = ReadPreference.primary; +Document.prototype.$isNew; - // Have we specified collation - try { - decorateWithCollation(queryObject, coll, options); - } catch (err) { - return callback(err, null); - } +/** + * Boolean flag specifying if the document is new. + * + * @api public + * @property isNew + * @memberOf Document + * @instance + */ - if (options.hint) { - // TODO: 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" - ) - ); +Document.prototype.isNew; - return; - } +/** + * Set this property to add additional query filters when Mongoose saves this document and `isNew` is false. + * + * ####Example: + * + * // Make sure `save()` never updates a soft deleted document. + * schema.pre('save', function() { + * this.$where = { isDeleted: false }; + * }); + * + * @api public + * @property $where + * @memberOf Document + * @instance + */ - queryObject.hint = options.hint; - } +Object.defineProperty(Document.prototype, '$where', { + configurable: false, + enumerable: false, + writable: true +}); - if (this.explain) { - if (maxWireVersion(coll.s.topology) < 4) { - callback( - new MongoError( - `server does not support explain on findAndModify` - ) - ); - return; - } - queryObject = decorateWithExplain(queryObject, this.explain); - } +/** + * The string version of this documents _id. + * + * ####Note: + * + * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time. + * + * new Schema({ name: String }, { id: false }); + * + * @api public + * @see Schema options /docs/guide.html#options + * @property id + * @memberOf Document + * @instance + */ - // Execute the command - executeCommand(coll.s.db, queryObject, options, (err, result) => { - if (err) return handleCallback(callback, err, null); +Document.prototype.id; - return handleCallback(callback, null, result); - }); - } - } +/** + * Hash containing current validation $errors. + * + * @api public + * @property $errors + * @memberOf Document + * @instance + */ - defineAspects(FindAndModifyOperation, [Aspect.EXPLAINABLE]); +Document.prototype.$errors; - module.exports = FindAndModifyOperation; +/** + * Hash containing current validation errors. + * + * @api public + * @property errors + * @memberOf Document + * @instance + */ - /***/ - }, +Document.prototype.errors; - /***/ 4497: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +/** + * A string containing the current operation that Mongoose is executing + * on this document. May be `null`, `'save'`, `'validate'`, or `'remove'`. + * + * ####Example: + * + * const doc = new Model({ name: 'test' }); + * doc.$op; // null + * + * const promise = doc.save(); + * doc.$op; // 'save' + * + * await promise; + * doc.$op; // null + * + * @api public + * @property $op + * @memberOf Document + * @instance + */ - const handleCallback = __nccwpck_require__(1371).handleCallback; - const OperationBase = __nccwpck_require__(1018).OperationBase; - const toError = __nccwpck_require__(1371).toError; - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; +Object.defineProperty(Document.prototype, '$op', { + get: function() { + return this.$__.op || null; + }, + set: function(value) { + this.$__.op = value; + } +}); - class FindOneOperation extends OperationBase { - constructor(collection, query, options) { - super(options); +/*! + * ignore + */ - this.collection = collection; - this.query = query; - } +function $__hasIncludedChildren(fields) { + const hasIncludedChildren = {}; + const keys = Object.keys(fields); - execute(callback) { - const coll = this.collection; - const query = this.query; - const options = this.options; + for (const key of keys) { + const parts = key.split('.'); + const c = []; - try { - const cursor = coll.find(query, options).limit(-1).batchSize(1); + for (const part of parts) { + c.push(part); + hasIncludedChildren[c.join('.')] = 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); - } - } - } + return hasIncludedChildren; +} - defineAspects(FindOneOperation, [Aspect.EXPLAINABLE]); +/*! + * ignore + */ - module.exports = FindOneOperation; +function $__applyDefaults(doc, fields, skipId, exclude, hasIncludedChildren, isBeforeSetters, pathsToSkip) { + const paths = Object.keys(doc.$__schema.paths); + const plen = paths.length; - /***/ - }, + for (let i = 0; i < plen; ++i) { + let def; + let curPath = ''; + const p = paths[i]; - /***/ 5841: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const FindAndModifyOperation = __nccwpck_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"); - } + if (p === '_id' && skipId) { + continue; + } - super(collection, filter, finalOptions.sort, null, finalOptions); - } + const type = doc.$__schema.paths[p]; + const path = type.splitPath(); + const len = path.length; + let included = false; + let doc_ = doc._doc; + for (let j = 0; j < len; ++j) { + if (doc_ == null) { + break; } - module.exports = FindOneAndDeleteOperation; + const piece = path[j]; + curPath += (!curPath.length ? '' : '.') + piece; - /***/ - }, + if (exclude === true) { + if (curPath in fields) { + break; + } + } else if (exclude === false && fields && !included) { + if (curPath in fields) { + included = true; + } else if (!hasIncludedChildren[curPath]) { + break; + } + } - /***/ 4316: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const MongoError = __nccwpck_require__(3994).MongoError; - const FindAndModifyOperation = __nccwpck_require__(711); - const hasAtomicOperators = __nccwpck_require__(1371).hasAtomicOperators; - - class FindOneAndReplaceOperation extends FindAndModifyOperation { - constructor(collection, filter, replacement, options) { - if ("returnDocument" in options && "returnOriginal" in options) { - throw new MongoError( - "findOneAndReplace option returnOriginal is deprecated in favor of returnDocument and cannot be combined" - ); - } - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.update = true; - finalOptions.new = - options.returnDocument === "after" || - options.returnOriginal === false; - finalOptions.upsert = options.upsert === true; - - if (filter == null || typeof filter !== "object") { - throw new TypeError("Filter parameter must be an object"); - } + if (j === len - 1) { + if (doc_[piece] !== void 0) { + break; + } - if (replacement == null || typeof replacement !== "object") { - throw new TypeError("Replacement parameter must be an object"); + if (typeof type.defaultValue === 'function') { + if (!type.defaultValue.$runBeforeSetters && isBeforeSetters) { + break; } - - if (hasAtomicOperators(replacement)) { - throw new TypeError( - "Replacement document must not contain atomic operators" - ); + if (type.defaultValue.$runBeforeSetters && !isBeforeSetters) { + break; } + } else if (!isBeforeSetters) { + // Non-function defaults should always run **before** setters + continue; + } - super( - collection, - filter, - finalOptions.sort, - replacement, - finalOptions - ); + if (pathsToSkip && pathsToSkip[curPath]) { + break; } - } - module.exports = FindOneAndReplaceOperation; + if (fields && exclude !== null) { + if (exclude === true) { + // apply defaults to all non-excluded fields + if (p in fields) { + continue; + } - /***/ - }, + try { + def = type.getDefault(doc, false); + } catch (err) { + doc.invalidate(p, err); + break; + } - /***/ 1925: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const MongoError = __nccwpck_require__(3994).MongoError; - const FindAndModifyOperation = __nccwpck_require__(711); - const hasAtomicOperators = __nccwpck_require__(1371).hasAtomicOperators; - - class FindOneAndUpdateOperation extends FindAndModifyOperation { - constructor(collection, filter, update, options) { - if ("returnDocument" in options && "returnOriginal" in options) { - throw new MongoError( - "findOneAndUpdate option returnOriginal is deprecated in favor of returnDocument and cannot be combined" - ); - } - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.update = true; - finalOptions.new = - options.returnDocument === "after" || - options.returnOriginal === false; - finalOptions.upsert = options.upsert === true; - - if (filter == null || typeof filter !== "object") { - throw new TypeError("Filter parameter must be an object"); - } + if (typeof def !== 'undefined') { + doc_[piece] = def; + doc.$__.activePaths.default(p); + } + } else if (included) { + // selected field + try { + def = type.getDefault(doc, false); + } catch (err) { + doc.invalidate(p, err); + break; + } - if (update == null || typeof update !== "object") { - throw new TypeError("Update parameter must be an object"); + if (typeof def !== 'undefined') { + doc_[piece] = def; + doc.$__.activePaths.default(p); + } } - - if (!hasAtomicOperators(update)) { - throw new TypeError("Update document requires atomic operators"); + } else { + try { + def = type.getDefault(doc, false); + } catch (err) { + doc.invalidate(p, err); + break; } - super(collection, filter, finalOptions.sort, update, finalOptions); + if (typeof def !== 'undefined') { + doc_[piece] = def; + doc.$__.activePaths.default(p); + } } + } else { + doc_ = doc_[piece]; } + } + } +} - module.exports = FindOneAndUpdateOperation; +/*! + * ignore + */ - /***/ - }, +function $applyDefaultsToNested(val, path, doc) { + if (val == null) { + return; + } - /***/ 8169: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - const OperationBase = __nccwpck_require__(1018).OperationBase; - const decorateCommand = __nccwpck_require__(1371).decorateCommand; - const decorateWithReadConcern = - __nccwpck_require__(1371).decorateWithReadConcern; - const executeCommand = __nccwpck_require__(2226).executeCommand; - const handleCallback = __nccwpck_require__(1371).handleCallback; - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const toError = __nccwpck_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); + flattenObjectWithDottedPaths(val); - this.collection = collection; - this.x = x; - this.y = y; - } + const paths = Object.keys(doc.$__schema.paths); + const plen = paths.length; - /** - * 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], - }; + const pathPieces = path.indexOf('.') === -1 ? [path] : path.split('.'); - // 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); - }); - } - } + for (let i = 0; i < plen; ++i) { + let curPath = ''; + const p = paths[i]; - defineAspects(GeoHaystackSearchOperation, Aspect.READ_OPERATION); + if (!p.startsWith(path + '.')) { + continue; + } - module.exports = GeoHaystackSearchOperation; + const type = doc.$__schema.paths[p]; + const pieces = type.splitPath().slice(pathPieces.length); + const len = pieces.length; - /***/ - }, + if (type.defaultValue === void 0) { + continue; + } - /***/ 7809: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + let cur = val; - const OperationBase = __nccwpck_require__(1018).OperationBase; - const handleCallback = __nccwpck_require__(1371).handleCallback; - const indexInformationDb = __nccwpck_require__(2226).indexInformation; + for (let j = 0; j < len; ++j) { + if (cur == null) { + break; + } - class IndexExistsOperation extends OperationBase { - constructor(collection, indexes, options) { - super(options); + const piece = pieces[j]; - this.collection = collection; - this.indexes = indexes; + if (j === len - 1) { + if (cur[piece] !== void 0) { + break; } - 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); - } - ); + try { + const def = type.getDefault(doc, false); + if (def !== void 0) { + cur[piece] = def; + } + } catch (err) { + doc.invalidate(path + '.' + curPath, err); + break; } - } - module.exports = IndexExistsOperation; + break; + } - /***/ - }, + curPath += (!curPath.length ? '' : '.') + piece; - /***/ 4245: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + cur[piece] = cur[piece] || {}; + cur = cur[piece]; + } + } +} - const OperationBase = __nccwpck_require__(1018).OperationBase; - const indexInformation = __nccwpck_require__(2296).indexInformation; +/** + * Builds the default doc structure + * + * @param {Object} obj + * @param {Object} [fields] + * @param {Boolean} [skipId] + * @api private + * @method $__buildDoc + * @memberOf Document + * @instance + */ - class IndexInformationOperation extends OperationBase { - constructor(db, name, options) { - super(options); +Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasIncludedChildren) { + const doc = {}; - this.db = db; - this.name = name; - } + const paths = Object.keys(this.$__schema.paths). + // Don't build up any paths that are underneath a map, we don't know + // what the keys will be + filter(p => !p.includes('$*')); + const plen = paths.length; + let ii = 0; - execute(callback) { - const db = this.db; - const name = this.name; - const options = this.options; + for (; ii < plen; ++ii) { + const p = paths[ii]; - indexInformation(db, name, options, callback); - } + if (p === '_id') { + if (skipId) { + continue; } + if (obj && '_id' in obj) { + continue; + } + } - module.exports = IndexInformationOperation; + const path = this.$__schema.paths[p].splitPath(); + const len = path.length; + const last = len - 1; + let curPath = ''; + let doc_ = doc; + let included = false; - /***/ - }, + for (let i = 0; i < len; ++i) { + const piece = path[i]; + + curPath += (!curPath.length ? '' : '.') + piece; - /***/ 4218: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + // support excluding intermediary levels + if (exclude === true) { + if (curPath in fields) { + break; + } + } else if (exclude === false && fields && !included) { + if (curPath in fields) { + included = true; + } else if (!hasIncludedChildren[curPath]) { + break; + } + } - const OperationBase = __nccwpck_require__(1018).OperationBase; - const indexInformation = __nccwpck_require__(2296).indexInformation; + if (i < last) { + doc_ = doc_[piece] || (doc_[piece] = {}); + } + } + } - class IndexesOperation extends OperationBase { - constructor(collection, options) { - super(options); + this._doc = doc; +}; - this.collection = collection; - } +/*! + * Converts to POJO when you use the document for querying + */ - execute(callback) { - const coll = this.collection; - let options = this.options; +Document.prototype.toBSON = function() { + return this.toObject(internalToObjectOptions); +}; - options = Object.assign({}, { full: true }, options); - indexInformation(coll.s.db, coll.collectionName, options, callback); - } - } +/** + * Initializes the document without setters or marking anything modified. + * + * Called internally after a document is returned from mongodb. Normally, + * you do **not** need to call this function on your own. + * + * This function triggers `init` [middleware](/docs/middleware.html). + * Note that `init` hooks are [synchronous](/docs/middleware.html#synchronous). + * + * @param {Object} doc document returned by mongo + * @api public + * @memberOf Document + * @instance + */ - module.exports = IndexesOperation; +Document.prototype.init = function(doc, opts, fn) { + if (typeof opts === 'function') { + fn = opts; + opts = null; + } - /***/ - }, + this.$__init(doc, opts); - /***/ 3592: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const OperationBase = __nccwpck_require__(1018).OperationBase; - const BulkWriteOperation = __nccwpck_require__(6976); - const MongoError = __nccwpck_require__(3994).MongoError; - const prepareDocs = __nccwpck_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 (fn) { + fn(null, this); + } - // If keep going set unordered - options["serializeFunctions"] = - options["serializeFunctions"] || coll.s.serializeFunctions; + return this; +}; - docs = prepareDocs(coll, docs, options); +Document.prototype.$init = function() { + return this.constructor.prototype.init.apply(this, arguments); +}; - // Generate the bulk write operations - const operations = docs.map((document) => ({ - insertOne: { document }, - })); +/*! + * ignore + */ - const bulkWriteOperation = new BulkWriteOperation( - coll, - operations, - options - ); +Document.prototype.$__init = function(doc, opts) { + this.$isNew = false; + opts = opts || {}; + + // handle docs with populated paths + // If doc._id is not null or undefined + if (doc._id != null && opts.populated && opts.populated.length) { + const id = String(doc._id); + for (const item of opts.populated) { + if (item.isVirtual) { + this.$populated(item.path, utils.getValue(item.path, doc), item); + } else { + this.$populated(item.path, item._docs[id], item); + } - bulkWriteOperation.execute((err, result) => { - if (err) return callback(err, null); - callback(null, mapInsertManyResults(docs, result)); - }); + if (item._childDocs == null) { + continue; + } + for (const child of item._childDocs) { + if (child == null || child.$__ == null) { + continue; } + child.$__.parent = this; } + item._childDocs = []; + } + } - function mapInsertManyResults(docs, r) { - const finalResult = { - result: { ok: 1, n: r.insertedCount }, - ops: docs, - insertedCount: r.insertedCount, - insertedIds: r.insertedIds, - }; + init(this, doc, this._doc, opts); - if (r.getLastOp()) { - finalResult.result.opTime = r.getLastOp(); - } + markArraySubdocsPopulated(this, opts.populated); - return finalResult; - } + this.$emit('init', this); + this.constructor.emit('init', this); - module.exports = InsertManyOperation; + this.$__._id = this._id; + return this; +}; - /***/ - }, +/*! + * Init helper. + * + * @param {Object} self document instance + * @param {Object} obj raw mongodb doc + * @param {Object} doc object we are initializing + * @api private + */ - /***/ 9915: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +function init(self, obj, doc, opts, prefix) { + prefix = prefix || ''; - const MongoError = __nccwpck_require__(3994).MongoError; - const OperationBase = __nccwpck_require__(1018).OperationBase; - const insertDocuments = __nccwpck_require__(2296).insertDocuments; + const keys = Object.keys(obj); + const len = keys.length; + let schema; + let path; + let i; + let index = 0; + const strict = self.$__.strictMode; - class InsertOneOperation extends OperationBase { - constructor(collection, doc, options) { - super(options); + while (index < len) { + _init(index++); + } - this.collection = collection; - this.doc = doc; - } + function _init(index) { + i = keys[index]; + path = prefix + i; + schema = self.$__schema.path(path); - execute(callback) { - const coll = this.collection; - const doc = this.doc; - const options = this.options; + // Should still work if not a model-level discriminator, but should not be + // necessary. This is *only* to catch the case where we queried using the + // base model and the discriminated model has a projection + if (self.$__schema.$isRootDiscriminator && !self.$__isSelected(path)) { + return; + } - if (Array.isArray(doc)) { - return callback( - MongoError.create({ - message: "doc parameter must be an object", - driver: true, - }) - ); + if (!schema && utils.isPOJO(obj[i])) { + // assume nested object + if (!doc[i]) { + doc[i] = {}; + } + init(self, obj[i], doc[i], opts, path + '.'); + } else if (!schema) { + doc[i] = obj[i]; + if (!strict && !prefix) { + // Set top-level properties that aren't in the schema if strict is false + self[i] = obj[i]; + } + } else { + // Retain order when overwriting defaults + if (doc.hasOwnProperty(i) && obj[i] !== void 0) { + delete doc[i]; + } + if (obj[i] === null) { + doc[i] = schema._castNullish(null); + } else if (obj[i] !== undefined) { + const intCache = obj[i].$__ || {}; + const wasPopulated = intCache.wasPopulated || null; + + if (schema && !wasPopulated) { + try { + doc[i] = schema.cast(obj[i], self, true); + } catch (e) { + self.invalidate(e.path, new ValidatorError({ + path: e.path, + message: e.message, + type: 'cast', + value: e.value, + reason: e + })); } - - 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); - }); + } else { + doc[i] = obj[i]; } } + // mark as hydrated + if (!self.$isModified(path)) { + self.$__.activePaths.init(path); + } + } + } +} - module.exports = InsertOneOperation; - - /***/ - }, - - /***/ 4956: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const OptionsOperation = __nccwpck_require__(43); - const handleCallback = __nccwpck_require__(1371).handleCallback; +/** + * Sends an update command with this document `_id` as the query selector. + * + * ####Example: + * + * weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback); + * + * ####Valid options: + * + * - same as in [Model.update](#model_Model.update) + * + * @see Model.update #model_Model.update + * @param {Object} doc + * @param {Object} options + * @param {Function} callback + * @return {Query} + * @api public + * @memberOf Document + * @instance + */ - class IsCappedOperation extends OptionsOperation { - constructor(collection, options) { - super(collection, options); - } +Document.prototype.update = function update() { + const args = utils.args(arguments); + args.unshift({ _id: this._id }); + const query = this.constructor.update.apply(this.constructor, args); - execute(callback) { - super.execute((err, document) => { - if (err) return handleCallback(callback, err); - handleCallback(callback, null, !!(document && document.capped)); - }); - } - } + if (this.$session() != null) { + if (!('session' in query.options)) { + query.options.session = this.$session(); + } + } - module.exports = IsCappedOperation; + return query; +}; - /***/ - }, +/** + * Sends an updateOne command with this document `_id` as the query selector. + * + * ####Example: + * + * weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback); + * + * ####Valid options: + * + * - same as in [Model.updateOne](#model_Model.updateOne) + * + * @see Model.updateOne #model_Model.updateOne + * @param {Object} doc + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Function} callback + * @return {Query} + * @api public + * @memberOf Document + * @instance + */ - /***/ 840: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +Document.prototype.updateOne = function updateOne(doc, options, callback) { + const query = this.constructor.updateOne({ _id: this._id }, doc, options); + query.pre(cb => { + this.constructor._middleware.execPre('updateOne', this, [this], cb); + }); + query.post(cb => { + this.constructor._middleware.execPost('updateOne', this, [this], {}, cb); + }); + + if (this.$session() != null) { + if (!('session' in query.options)) { + query.options.session = this.$session(); + } + } - const CommandOperationV2 = __nccwpck_require__(1189); - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const CONSTANTS = __nccwpck_require__(147); + if (callback != null) { + return query.exec(callback); + } - const LIST_COLLECTIONS_WIRE_VERSION = 3; + return query; +}; - function listCollectionsTransforms(databaseName) { - const matching = `${databaseName}.`; +/** + * Sends a replaceOne command with this document `_id` as the query selector. + * + * ####Valid options: + * + * - same as in [Model.replaceOne](https://mongoosejs.com/docs/api/model.html#model_Model.replaceOne) + * + * @see Model.replaceOne #model_Model.replaceOne + * @param {Object} doc + * @param {Object} options + * @param {Function} callback + * @return {Query} + * @api public + * @memberOf Document + * @instance + */ - 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); - } +Document.prototype.replaceOne = function replaceOne() { + const args = utils.args(arguments); + args.unshift({ _id: this._id }); + return this.constructor.replaceOne.apply(this.constructor, args); +}; - return doc; - }, - }; - } +/** + * Getter/setter around the session associated with this document. Used to + * automatically set `session` if you `save()` a doc that you got from a + * query with an associated session. + * + * ####Example: + * + * const session = MyModel.startSession(); + * const doc = await MyModel.findOne().session(session); + * doc.$session() === session; // true + * doc.$session(null); + * doc.$session() === null; // true + * + * If this is a top-level document, setting the session propagates to all child + * docs. + * + * @param {ClientSession} [session] overwrite the current session + * @return {ClientSession} + * @method $session + * @api public + * @memberOf Document + */ - class ListCollectionsOperation extends CommandOperationV2 { - constructor(db, filter, options) { - super(db, options, { fullResponse: true }); +Document.prototype.$session = function $session(session) { + if (arguments.length === 0) { + if (this.$__.session != null && this.$__.session.hasEnded) { + this.$__.session = null; + return null; + } + return this.$__.session; + } - this.db = db; - this.filter = filter; - this.nameOnly = !!this.options.nameOnly; + if (session != null && session.hasEnded) { + throw new MongooseError('Cannot set a document\'s session to a session that has ended. Make sure you haven\'t ' + + 'called `endSession()` on the session you are passing to `$session()`.'); + } - if (typeof this.options.batchSize === "number") { - this.batchSize = this.options.batchSize; - } - } + if (session == null && this.$__.session == null) { + return; + } - execute(server, callback) { - if (maxWireVersion(server) < LIST_COLLECTIONS_WIRE_VERSION) { - let filter = this.filter; - const databaseName = this.db.s.namespace.db; + this.$__.session = session; - // 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(); - } + if (!this.$isSubdocument) { + const subdocs = this.$getAllSubdocs(); + for (const child of subdocs) { + child.$session(session); + } + } - // No filter, filter by current database - if (filter == null) { - filter.name = `/${databaseName}/`; - } + return session; +}; - // 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 - ); - } +/** + * Overwrite all values in this document with the values of `obj`, except + * for immutable properties. Behaves similarly to `set()`, except for it + * unsets all properties that aren't in `obj`. + * + * @param {Object} obj the object to overwrite this document with + * @method overwrite + * @name overwrite + * @memberOf Document + * @instance + * @api public + */ - callback(err, result); - } - ); +Document.prototype.overwrite = function overwrite(obj) { + const keys = Array.from(new Set(Object.keys(this._doc).concat(Object.keys(obj)))); - return; - } + for (const key of keys) { + if (key === '_id') { + continue; + } + // Explicitly skip version key + if (this.$__schema.options.versionKey && key === this.$__schema.options.versionKey) { + continue; + } + if (this.$__schema.options.discriminatorKey && key === this.$__schema.options.discriminatorKey) { + continue; + } + this.$set(key, obj[key]); + } - const command = { - listCollections: 1, - filter: this.filter, - cursor: this.batchSize ? { batchSize: this.batchSize } : {}, - nameOnly: this.nameOnly, - }; + return this; +}; - return super.executeCommand(server, command, callback); - } - } +/** + * Alias for `set()`, used internally to avoid conflicts + * + * @param {String|Object} path path or object of key/vals to set + * @param {Any} val the value to set + * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes + * @param {Object} [options] optionally specify options that modify the behavior of the set + * @method $set + * @name $set + * @memberOf Document + * @instance + * @api public + */ - defineAspects(ListCollectionsOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION, - ]); +Document.prototype.$set = function $set(path, val, type, options) { + if (utils.isPOJO(type)) { + options = type; + type = undefined; + } - module.exports = ListCollectionsOperation; + options = options || {}; + const merge = options.merge; + const adhoc = type && type !== true; + const constructing = type === true; + const typeKey = this.$__schema.options.typeKey; + let adhocs; + let keys; + let i = 0; + let pathtype; + let key; + let prefix; + + const strict = 'strict' in options + ? options.strict + : this.$__.strictMode; + + if (adhoc) { + adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); + adhocs[path] = this.$__schema.interpretAsType(path, type, this.$__schema.options); + } - /***/ - }, + if (path == null) { + [path, val] = [val, path]; + } else if (typeof path !== 'string') { + // new Document({ key: val }) + if (path instanceof Document) { + if (path.$__isNested) { + path = path.toObject(); + } else { + path = path._doc; + } + } + if (path == null) { + [path, val] = [val, path]; + } - /***/ 9929: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + prefix = val ? val + '.' : ''; + keys = getKeysInSchemaOrder(this.$__schema, path); - const CommandOperationV2 = __nccwpck_require__(1189); - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - const MongoDBNamespace = __nccwpck_require__(1371).MongoDBNamespace; + const len = keys.length; - class ListDatabasesOperation extends CommandOperationV2 { - constructor(db, options) { - super(db, options); - this.ns = new MongoDBNamespace("admin", "$cmd"); - } + // `_skipMinimizeTopLevel` is because we may have deleted the top-level + // nested key to ensure key order. + const _skipMinimizeTopLevel = get(options, '_skipMinimizeTopLevel', false); + if (len === 0 && _skipMinimizeTopLevel) { + delete options._skipMinimizeTopLevel; + if (val) { + this.$set(val, {}); + } + return this; + } - execute(server, callback) { - const cmd = { listDatabases: 1 }; - if (this.options.nameOnly) { - cmd.nameOnly = Number(cmd.nameOnly); - } + for (let i = 0; i < len; ++i) { + key = keys[i]; + const pathName = prefix + key; + pathtype = this.$__schema.pathType(pathName); + const valForKey = path[key]; + + // On initial set, delete any nested keys if we're going to overwrite + // them to ensure we keep the user's key order. + if (type === true && + !prefix && + path[key] != null && + pathtype === 'nested' && + this._doc[key] != null) { + delete this._doc[key]; + // Make sure we set `{}` back even if we minimize re: gh-8565 + options = Object.assign({}, options, { _skipMinimizeTopLevel: true }); + } else { + // Make sure we set `{_skipMinimizeTopLevel: false}` if don't have overwrite: gh-10441 + options = Object.assign({}, options, { _skipMinimizeTopLevel: false }); + } + + if (utils.isNonBuiltinObject(valForKey) && pathtype === 'nested') { + $applyDefaultsToNested(path[key], prefix + key, this); + this.$set(prefix + key, path[key], constructing, Object.assign({}, options, { _skipMarkModified: true })); + continue; + } else if (strict) { + // Don't overwrite defaults with undefined keys (gh-3981) (gh-9039) + if (constructing && path[key] === void 0 && + this.$get(pathName) !== void 0) { + continue; + } - if (this.options.filter) { - cmd.filter = this.options.filter; - } + if (pathtype === 'adhocOrUndefined') { + pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true }); + } - if (typeof this.options.authorizedDatabases === "boolean") { - cmd.authorizedDatabases = this.options.authorizedDatabases; + if (pathtype === 'real' || pathtype === 'virtual') { + const p = path[key]; + this.$set(prefix + key, p, constructing, options); + } else if (pathtype === 'nested' && path[key] instanceof Document) { + this.$set(prefix + key, + path[key].toObject({ transform: false }), constructing, options); + } else if (strict === 'throw') { + if (pathtype === 'nested') { + throw new ObjectExpectedError(key, path[key]); + } else { + throw new StrictModeError(key); } - - super.executeCommand(server, cmd, callback); } + } else if (path[key] !== void 0) { + this.$set(prefix + key, path[key], constructing, options); } + } - defineAspects(ListDatabasesOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION, - ]); - - module.exports = ListDatabasesOperation; + // Ensure all properties are in correct order by deleting and recreating every property. + for (const key of Object.keys(this.$__schema.tree)) { + if (this._doc.hasOwnProperty(key)) { + const val = this._doc[key]; + delete this._doc[key]; + this._doc[key] = val; + } + } - /***/ - }, + return this; + } - /***/ 28: /***/ (module, __unused_webpack_exports, __nccwpck_require__) => { - "use strict"; + let pathType = this.$__schema.pathType(path); + if (pathType === 'adhocOrUndefined') { + pathType = getEmbeddedDiscriminatorPath(this, path, { typeOnly: true }); + } - const CommandOperationV2 = __nccwpck_require__(1189); - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; + // Assume this is a Mongoose document that was copied into a POJO using + // `Object.assign()` or `{...doc}` + val = handleSpreadDoc(val); - const LIST_INDEXES_WIRE_VERSION = 3; + // if this doc is being constructed we should not trigger getters + const priorVal = (() => { + if (this.$__.priorDoc != null) { + return this.$__.priorDoc.$__getValue(path); + } + if (constructing) { + return void 0; + } + return this.$__getValue(path); + })(); - class ListIndexesOperation extends CommandOperationV2 { - constructor(collection, options) { - super(collection, options, { fullResponse: true }); + if (pathType === 'nested' && val) { + if (typeof val === 'object' && val != null) { + if (val.$__ != null) { + val = val.toObject(internalToObjectOptions); + } + if (val == null) { + this.invalidate(path, new MongooseError.CastError('Object', val, path)); + return this; + } + const hasInitialVal = this.$__.savedState != null && this.$__.savedState.hasOwnProperty(path); + if (this.$__.savedState != null && !this.$isNew && !this.$__.savedState.hasOwnProperty(path)) { + const initialVal = this.$__getValue(path); + this.$__.savedState[path] = initialVal; - this.collectionNamespace = collection.s.namespace; + const keys = Object.keys(initialVal || {}); + for (const key of keys) { + this.$__.savedState[path + '.' + key] = initialVal[key]; } + } - 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(); + if (!merge) { + this.$__setValue(path, null); + cleanModifiedSubpaths(this, path); + } else { + return this.$set(val, path, constructing); + } - server.query( - systemIndexesNS, - { query: { ns: collectionNS } }, - {}, - this.options, - callback - ); - return; - } + const keys = getKeysInSchemaOrder(this.$__schema, val, path); - const cursor = this.options.batchSize - ? { batchSize: this.options.batchSize } - : {}; - super.executeCommand( - server, - { listIndexes: this.collectionNamespace.collection, cursor }, - callback - ); - } + this.$__setValue(path, {}); + for (const key of keys) { + this.$set(path + '.' + key, val[key], constructing, options); + } + if (priorVal != null && utils.deepEqual(hasInitialVal ? this.$__.savedState[path] : priorVal, val)) { + this.unmarkModified(path); + } else { + this.markModified(path); } + cleanModifiedSubpaths(this, path, { skipDocArrays: true }); + return this; + } + this.invalidate(path, new MongooseError.CastError('Object', val, path)); + return this; + } - defineAspects(ListIndexesOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION, - ]); + let schema; + const parts = path.indexOf('.') === -1 ? [path] : path.split('.'); - module.exports = ListIndexesOperation; + // Might need to change path for top-level alias + if (typeof this.$__schema.aliases[parts[0]] == 'string') { + parts[0] = this.$__schema.aliases[parts[0]]; + } - /***/ - }, + if (pathType === 'adhocOrUndefined' && strict) { + // check for roots that are Mixed types + let mixed; - /***/ 2779: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const applyWriteConcern = __nccwpck_require__(1371).applyWriteConcern; - const Code = __nccwpck_require__(3994).BSON.Code; - const decorateWithCollation = - __nccwpck_require__(1371).decorateWithCollation; - const decorateWithReadConcern = - __nccwpck_require__(1371).decorateWithReadConcern; - const executeCommand = __nccwpck_require__(2226).executeCommand; - const handleCallback = __nccwpck_require__(1371).handleCallback; - const isObject = __nccwpck_require__(1371).isObject; - const loadDb = __nccwpck_require__(8275).loadDb; - const OperationBase = __nccwpck_require__(1018).OperationBase; - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const toError = __nccwpck_require__(1371).toError; - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - const decorateWithExplain = __nccwpck_require__(1371).decorateWithExplain; - const maxWireVersion = __nccwpck_require__(1178).maxWireVersion; - const MongoError = __nccwpck_require__(9386).MongoError; - - const exclusionList = [ - "explain", - "readPreference", - "session", - "bypassDocumentValidation", - "w", - "wtimeout", - "j", - "writeConcern", - ]; + for (i = 0; i < parts.length; ++i) { + const subpath = parts.slice(0, i + 1).join('.'); - /** - * 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); + // If path is underneath a virtual, bypass everything and just set it. + if (i + 1 < parts.length && this.$__schema.pathType(subpath) === 'virtual') { + mpath.set(path, val, this); + return this; + } - this.collection = collection; - this.map = map; - this.reduce = reduce; - } + schema = this.$__schema.path(subpath); + if (schema == null) { + continue; + } - /** - * 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; + if (schema instanceof MixedSchema) { + // allow changes to sub paths of mixed types + mixed = true; + break; + } + } - let mapCommandHash = { - mapReduce: coll.collectionName, - map: map, - reduce: reduce, - }; + if (schema == null) { + // Check for embedded discriminators + schema = getEmbeddedDiscriminatorPath(this, path); + } - // 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]; - } - } - } + if (!mixed && !schema) { + if (strict === 'throw') { + throw new StrictModeError(path); + } + return this; + } + } else if (pathType === 'virtual') { + schema = this.$__schema.virtualpath(path); + schema.applySetters(val, this); + return this; + } else { + schema = this.$__path(path); + } - options = Object.assign({}, options); + // gh-4578, if setting a deeply nested path that doesn't exist yet, create it + let cur = this._doc; + let curPath = ''; + for (i = 0; i < parts.length - 1; ++i) { + cur = cur[parts[i]]; + curPath += (curPath.length > 0 ? '.' : '') + parts[i]; + if (!cur) { + this.$set(curPath, {}); + // Hack re: gh-5800. If nested field is not selected, it probably exists + // so `MongoServerError: cannot use the part (nested of nested.num) to + // traverse the element ({nested: null})` is not likely. If user gets + // that error, its their fault for now. We should reconsider disallowing + // modifying not selected paths for 6.x + if (!this.$__isSelected(curPath)) { + this.unmarkModified(curPath); + } + cur = this.$__getValue(curPath); + } + } - // Ensure we have the right read preference inheritance - options.readPreference = ReadPreference.resolve(coll, options); + let pathToMark; - // 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); - } + // When using the $set operator the path to the field must already exist. + // Else mongodb throws: "LEFT_SUBFIELD only supports Object" - // Is bypassDocumentValidation specified - if (options.bypassDocumentValidation === true) { - mapCommandHash.bypassDocumentValidation = - options.bypassDocumentValidation; - } + if (parts.length <= 1) { + pathToMark = path; + } else { + for (i = 0; i < parts.length; ++i) { + const subpath = parts.slice(0, i + 1).join('.'); + if (this.$get(subpath, null, { getters: false }) === null) { + pathToMark = subpath; + break; + } + } - // Have we specified collation - try { - decorateWithCollation(mapCommandHash, coll, options); - } catch (err) { - return callback(err, null); - } + if (!pathToMark) { + pathToMark = path; + } + } - if (this.explain) { - if (maxWireVersion(coll.s.topology) < 9) { - callback( - new MongoError(`server does not support explain on mapReduce`) - ); - return; - } - mapCommandHash = decorateWithExplain(mapCommandHash, this.explain); - } + if (!schema) { + this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal); + return this; + } - // 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)); - } + // If overwriting a subdocument path, make sure to clear out + // any errors _before_ setting, so new errors that happen + // get persisted. Re: #9080 + if (schema.$isSingleNested || schema.$isMongooseArray) { + _markValidSubpaths(this, path); + } - // If an explain operation was executed, don't process the server results - if (this.explain) return callback(undefined, result); + if (schema.$isSingleNested && val != null && merge) { + if (val instanceof Document) { + val = val.toObject({ virtuals: false, transform: false }); + } + const keys = Object.keys(val); + for (const key of keys) { + this.$set(path + '.' + key, val[key], constructing, options); + } - // 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; + return this; + } - // invoked with inline? - if (result.results) { - // If we wish for no verbosity - if (options["verbose"] == null || !options["verbose"]) { - return handleCallback(callback, null, result.results); - } + let shouldSet = true; + try { + // If the user is trying to set a ref path to a document with + // the correct model name, treat it as populated + const refMatches = (() => { + if (schema.options == null) { + return false; + } + if (!(val instanceof Document)) { + return false; + } + const model = val.constructor; - return handleCallback(callback, null, { - results: result.results, - stats: stats, - }); - } + // Check ref + const ref = schema.options.ref; + if (ref != null && (ref === model.modelName || ref === model.baseModelName)) { + return true; + } - // The returned collection - let collection = null; + // Check refPath + const refPath = schema.options.refPath; + if (refPath == null) { + return false; + } + const modelName = val.get(refPath); + return modelName === model.modelName || modelName === model.baseModelName; + })(); - // 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); - } + let didPopulate = false; + if (refMatches && val instanceof Document) { + this.$populated(path, val._id, { [populateModelSymbol]: val.constructor }); + val.$__.wasPopulated = true; + didPopulate = true; + } - // If we wish for no verbosity - if (options["verbose"] == null || !options["verbose"]) { - return handleCallback(callback, err, collection); - } + let popOpts; + if (schema.options && + Array.isArray(schema.options[typeKey]) && + schema.options[typeKey].length && + schema.options[typeKey][0].ref && + _isManuallyPopulatedArray(val, schema.options[typeKey][0].ref)) { + popOpts = { [populateModelSymbol]: val[0].constructor }; + this.$populated(path, val.map(function(v) { return v._id; }), popOpts); - // Return stats as third set of values - handleCallback(callback, err, { - collection: collection, - stats: stats, - }); - }); - } + for (const doc of val) { + doc.$__.wasPopulated = true; } + didPopulate = true; + } - /** - * 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; - } + if (this.$__schema.singleNestedPaths[path] == null && (!refMatches || !schema.$isSingleNested || !val.$__)) { + // If this path is underneath a single nested schema, we'll call the setter + // later in `$__set()` because we don't take `_doc` when we iterate through + // a single nested doc. That's to make sure we get the correct context. + // Otherwise we would double-call the setter, see gh-7196. + val = schema.applySetters(val, this, false, priorVal); + } - const keys = Object.keys(scope); - let key; - const new_scope = {}; + if (schema.$isMongooseDocumentArray && + Array.isArray(val) && + val.length > 0 && + val[0] != null && + val[0].$__ != null && + val[0].$__.populated != null) { + const populatedPaths = Object.keys(val[0].$__.populated); + for (const populatedPath of populatedPaths) { + this.$populated(path + '.' + populatedPath, + val.map(v => v.$populated(populatedPath)), + val[0].$__.populated[populatedPath].options); + } + didPopulate = true; + } - 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]); + if (!didPopulate && this.$__.populated) { + // If this array partially contains populated documents, convert them + // all to ObjectIds re: #8443 + if (Array.isArray(val) && this.$__.populated[path]) { + for (let i = 0; i < val.length; ++i) { + if (val[i] instanceof Document) { + val.set(i, val[i]._id, true); } } - - return new_scope; } + delete this.$__.populated[path]; + } - defineAspects(MapReduceOperation, [Aspect.EXPLAINABLE]); + if (schema.$isSingleNested && val != null) { + _checkImmutableSubpaths(val, schema, priorVal); + } - module.exports = MapReduceOperation; + this.$markValid(path); + } catch (e) { + if (e instanceof MongooseError.StrictModeError && e.isImmutableError) { + this.invalidate(path, e); + } else if (e instanceof MongooseError.CastError) { + this.invalidate(e.path, e); + if (e.$originalErrorPath) { + this.invalidate(path, + new MongooseError.CastError(schema.instance, val, path, e.$originalErrorPath)); + } + } else { + this.invalidate(path, + new MongooseError.CastError(schema.instance, val, path, e)); + } + shouldSet = false; + } - /***/ - }, + if (shouldSet) { + const doc = this.$isSubdocument ? this.ownerDocument() : this; + const savedState = doc.$__.savedState; + const savedStatePath = this.$isSubdocument ? this.$__.fullPath + '.' + path : path; + if (savedState != null) { + const firstDot = savedStatePath.indexOf('.'); + const topLevelPath = firstDot === -1 ? savedStatePath : savedStatePath.slice(0, firstDot); + if (!savedState.hasOwnProperty(topLevelPath)) { + savedState[topLevelPath] = utils.clone(doc.$__getValue(topLevelPath)); + } + } - /***/ 1018: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Explain = __nccwpck_require__(5293).Explain; - const MongoError = __nccwpck_require__(3111).MongoError; - - 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"), - EXPLAINABLE: Symbol("EXPLAINABLE"), - }; + this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal); - /** - * 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); - - if (this.hasAspect(Aspect.EXPLAINABLE)) { - this.explain = Explain.fromOptions(options); - } else if (this.options.explain !== undefined) { - throw new MongoError(`explain is not supported on this command`); - } - } + if (savedState != null && savedState.hasOwnProperty(savedStatePath) && utils.deepEqual(val, savedState[savedStatePath])) { + this.unmarkModified(path); + } + } - hasAspect(aspect) { - if (this.constructor.aspects == null) { - return false; - } - return this.constructor.aspects.has(aspect); - } + if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) { + cleanModifiedSubpaths(this, path); + } - set session(session) { - Object.assign(this.options, { session }); - } + return this; +}; - get session() { - return this.options.session; - } +/*! + * ignore + */ - clearSession() { - delete this.options.session; - } +function _isManuallyPopulatedArray(val, ref) { + if (!Array.isArray(val)) { + return false; + } + if (val.length === 0) { + return false; + } - get canRetryRead() { - return true; - } + for (const el of val) { + if (!(el instanceof Document)) { + return false; + } + const modelName = el.constructor.modelName; + if (modelName == null) { + return false; + } + if (el.constructor.modelName != ref && el.constructor.baseModelName != ref) { + return false; + } + } - execute() { - throw new TypeError( - "`execute` must be implemented for OperationBase subclasses" - ); - } - } + return true; +} - 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; - } +/** + * Sets the value of a path, or many paths. + * + * ####Example: + * + * // path, value + * doc.set(path, value) + * + * // object + * doc.set({ + * path : value + * , path2 : { + * path : value + * } + * }) + * + * // on-the-fly cast to number + * doc.set(path, value, Number) + * + * // on-the-fly cast to string + * doc.set(path, value, String) + * + * // changing strict mode behavior + * doc.set(path, value, { strict: false }); + * + * @param {String|Object} path path or object of key/vals to set + * @param {Any} val the value to set + * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes + * @param {Object} [options] optionally specify options that modify the behavior of the set + * @api public + * @method set + * @memberOf Document + * @instance + */ - module.exports = { - Aspect, - defineAspects, - OperationBase, - }; +Document.prototype.set = Document.prototype.$set; - /***/ - }, +/** + * Determine if we should mark this change as modified. + * + * @return {Boolean} + * @api private + * @method $__shouldModify + * @memberOf Document + * @instance + */ - /***/ 43: /***/ (module, __unused_webpack_exports, __nccwpck_require__) => { - "use strict"; +Document.prototype.$__shouldModify = function(pathToMark, path, options, constructing, parts, schema, val, priorVal) { + if (options._skipMarkModified) { + return false; + } + if (this.$isNew) { + return true; + } - const OperationBase = __nccwpck_require__(1018).OperationBase; - const handleCallback = __nccwpck_require__(1371).handleCallback; - const MongoError = __nccwpck_require__(3994).MongoError; + // Re: the note about gh-7196, `val` is the raw value without casting or + // setters if the full path is under a single nested subdoc because we don't + // want to double run setters. So don't set it as modified. See gh-7264. + if (this.$__schema.singleNestedPaths[path] != null) { + return false; + } - class OptionsOperation extends OperationBase { - constructor(collection, options) { - super(options); + if (val === void 0 && !this.$__isSelected(path)) { + // when a path is not selected in a query, its initial + // value will be undefined. + return true; + } - this.collection = collection; - } + if (val === void 0 && path in this.$__.activePaths.states.default) { + // we're just unsetting the default value which was never saved + return false; + } - execute(callback) { - const coll = this.collection; - const opts = this.options; + // gh-3992: if setting a populated field to a doc, don't mark modified + // if they have the same _id + if (this.$populated(path) && + val instanceof Document && + deepEqual(val._id, priorVal)) { + return false; + } - 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, - }) - ); - } + if (!deepEqual(val, priorVal || utils.getValue(path, this))) { + return true; + } - handleCallback(callback, err, collections[0].options || null); - }); - } - } + if (!constructing && + val !== null && + val !== undefined && + path in this.$__.activePaths.states.default && + deepEqual(val, schema.getDefault(this, constructing))) { + // a path with a default was $unset on the server + // and the user is setting it to the same value again + return true; + } + return false; +}; - module.exports = OptionsOperation; +/** + * Handles the actual setting of the value and marking the path modified if appropriate. + * + * @api private + * @method $__set + * @memberOf Document + * @instance + */ - /***/ - }, +Document.prototype.$__set = function(pathToMark, path, options, constructing, parts, schema, val, priorVal) { + Embedded = Embedded || __nccwpck_require__(9999); - /***/ 3969: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + const shouldModify = this.$__shouldModify(pathToMark, path, options, constructing, parts, + schema, val, priorVal); + const _this = this; - const CommandOperation = __nccwpck_require__(499); + if (shouldModify) { + this.markModified(pathToMark); - class ProfilingLevelOperation extends CommandOperation { - constructor(db, command, options) { - super(db, options); - } + // handle directly setting arrays (gh-1126) + MongooseArray || (MongooseArray = __nccwpck_require__(1089)); + if (val && val.isMongooseArray) { + val._registerAtomic('$set', val); - _buildCommand() { - const command = { profile: -1 }; + // Update embedded document parent references (gh-5189) + if (val.isMongooseDocumentArray) { + val.forEach(function(item) { + item && item.__parentArray && (item.__parentArray = val); + }); + } - return command; + // Small hack for gh-1638: if we're overwriting the entire array, ignore + // paths that were modified before the array overwrite + this.$__.activePaths.forEach(function(modifiedPath) { + if (modifiedPath.startsWith(path + '.')) { + _this.$__.activePaths.ignore(modifiedPath); } + }); + } + } else if (Array.isArray(val) && val.isMongooseArray && Array.isArray(priorVal) && priorVal.isMongooseArray) { + val[arrayAtomicsSymbol] = priorVal[arrayAtomicsSymbol]; + val[arrayAtomicsBackupSymbol] = priorVal[arrayAtomicsBackupSymbol]; + } - 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); - } - }); - } + let obj = this._doc; + let i = 0; + const l = parts.length; + let cur = ''; + + for (; i < l; i++) { + const next = i + 1; + const last = next === l; + cur += (cur ? '.' + parts[i] : parts[i]); + if (specialProperties.has(parts[i])) { + return; + } + + if (last) { + if (obj instanceof Map) { + obj.set(parts[i], val); + } else { + obj[parts[i]] = val; + } + } else { + if (utils.isPOJO(obj[parts[i]])) { + obj = obj[parts[i]]; + } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) { + obj = obj[parts[i]]; + } else if (obj[parts[i]] && obj[parts[i]].$isSingleNested) { + obj = obj[parts[i]]; + } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) { + obj = obj[parts[i]]; + } else { + obj[parts[i]] = obj[parts[i]] || {}; + obj = obj[parts[i]]; } + } + } +}; - module.exports = ProfilingLevelOperation; +/** + * Gets a raw value from a path (no getters) + * + * @param {String} path + * @api private + */ - /***/ - }, +Document.prototype.$__getValue = function(path) { + return utils.getValue(path, this._doc); +}; - /***/ 6331: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - const CommandOperationV2 = __nccwpck_require__(1189); - const serverType = __nccwpck_require__(2291).serverType; - const ServerType = __nccwpck_require__(2291).ServerType; - const MongoError = __nccwpck_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); - } - ); - } - } +/** + * Sets a raw value for a path (no casting, setters, transformations) + * + * @param {String} path + * @param {Object} value + * @api private + */ + +Document.prototype.$__setValue = function(path, val) { + utils.setValue(path, val, this._doc); + return this; +}; + +/** + * Returns the value of a path. + * + * ####Example + * + * // path + * doc.get('age') // 47 + * + * // dynamic casting to a string + * doc.get('age', String) // "47" + * + * @param {String} path + * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for on-the-fly attributes + * @param {Object} [options] + * @param {Boolean} [options.virtuals=false] Apply virtuals before getting this path + * @param {Boolean} [options.getters=true] If false, skip applying getters and just get the raw value + * @api public + */ - defineAspects(ReIndexOperation, [Aspect.EXECUTE_WITH_SELECTION]); +Document.prototype.get = function(path, type, options) { + let adhoc; + options = options || {}; + if (type) { + adhoc = this.$__schema.interpretAsType(path, type, this.$__schema.options); + } + + let schema = this.$__path(path); + if (schema == null) { + schema = this.$__schema.virtualpath(path); + } + if (schema instanceof MixedSchema) { + const virtual = this.$__schema.virtualpath(path); + if (virtual != null) { + schema = virtual; + } + } + const pieces = path.indexOf('.') === -1 ? [path] : path.split('.'); + let obj = this._doc; - module.exports = ReIndexOperation; + if (schema instanceof VirtualType) { + return schema.applyGetters(void 0, this); + } - /***/ - }, + // Might need to change path for top-level alias + if (typeof this.$__schema.aliases[pieces[0]] == 'string') { + pieces[0] = this.$__schema.aliases[pieces[0]]; + } - /***/ 1969: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Aspect = __nccwpck_require__(1018).Aspect; - const CommandOperation = __nccwpck_require__(499); - const defineAspects = __nccwpck_require__(1018).defineAspects; - const handleCallback = __nccwpck_require__(1371).handleCallback; - const WriteConcern = __nccwpck_require__(2481); - - class RemoveUserOperation extends CommandOperation { - constructor(db, username, options) { - const commandOptions = {}; - - const writeConcern = WriteConcern.fromOptions(options); - if (writeConcern != null) { - commandOptions.writeConcern = writeConcern; - } + for (let i = 0, l = pieces.length; i < l; i++) { + if (obj && obj._doc) { + obj = obj._doc; + } - if (options.dbName) { - commandOptions.dbName = options.dbName; - } + if (obj == null) { + obj = void 0; + } else if (obj instanceof Map) { + obj = obj.get(pieces[i], { getters: false }); + } else if (i === l - 1) { + obj = utils.getValue(pieces[i], obj); + } else { + obj = obj[pieces[i]]; + } + } - // Add maxTimeMS to options if set - if (typeof options.maxTimeMS === "number") { - commandOptions.maxTimeMS = options.maxTimeMS; - } + if (adhoc) { + obj = adhoc.cast(obj); + } - super(db, commandOptions); + if (schema != null && options.getters !== false) { + obj = schema.applyGetters(obj, this); + } else if (this.$__schema.nested[path] && options.virtuals) { + // Might need to apply virtuals if this is a nested path + return applyVirtuals(this, utils.clone(obj) || {}, { path: path }); + } - this.username = username; - } + return obj; +}; - _buildCommand() { - const username = this.username; +/*! + * ignore + */ - // Build the command to execute - const command = { dropUser: username }; +Document.prototype[getSymbol] = Document.prototype.get; +Document.prototype.$get = Document.prototype.get; +/** + * Returns the schematype for the given `path`. + * + * @param {String} path + * @api private + * @method $__path + * @memberOf Document + * @instance + */ - return command; - } +Document.prototype.$__path = function(path) { + const adhocs = this.$__.adhocPaths; + const adhocType = adhocs && adhocs.hasOwnProperty(path) ? adhocs[path] : null; - execute(callback) { - // Attempt to execute command - super.execute((err, result) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, err, result.ok ? true : false); - }); - } - } + if (adhocType) { + return adhocType; + } + return this.$__schema.path(path); +}; - defineAspects(RemoveUserOperation, Aspect.WRITE_OPERATION); +/** + * Marks the path as having pending changes to write to the db. + * + * _Very helpful when using [Mixed](https://mongoosejs.com/docs/schematypes.html#mixed) types._ + * + * ####Example: + * + * doc.mixed.type = 'changed'; + * doc.markModified('mixed.type'); + * doc.save() // changes to mixed.type are now persisted + * + * @param {String} path the path to mark modified + * @param {Document} [scope] the scope to run validators with + * @api public + */ - module.exports = RemoveUserOperation; +Document.prototype.markModified = function(path, scope) { + this.$__.activePaths.modify(path); + if (scope != null && !this.$isSubdocument) { + this.$__.pathsToScopes = this.$__pathsToScopes || {}; + this.$__.pathsToScopes[path] = scope; + } +}; - /***/ - }, +/** + * Clears the modified state on the specified path. + * + * ####Example: + * + * doc.foo = 'bar'; + * doc.unmarkModified('foo'); + * doc.save(); // changes to foo will not be persisted + * + * @param {String} path the path to unmark modified + * @api public + */ - /***/ 2808: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const OperationBase = __nccwpck_require__(1018).OperationBase; - const applyWriteConcern = __nccwpck_require__(1371).applyWriteConcern; - const checkCollectionName = __nccwpck_require__(1371).checkCollectionName; - const executeDbAdminCommand = - __nccwpck_require__(2226).executeDbAdminCommand; - const handleCallback = __nccwpck_require__(1371).handleCallback; - const loadCollection = __nccwpck_require__(8275).loadCollection; - const toError = __nccwpck_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, - }; +Document.prototype.unmarkModified = function(path) { + this.$__.activePaths.init(path); + if (this.$__.pathsToScopes != null) { + delete this.$__.pathsToScopes[path]; + } +}; - // Decorate command with writeConcern if supported - applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); +/** + * Don't run validation on this path or persist changes to this path. + * + * ####Example: + * + * doc.foo = null; + * doc.$ignore('foo'); + * doc.save(); // changes to foo will not be persisted and validators won't be run + * + * @memberOf Document + * @instance + * @method $ignore + * @param {String} path the path to ignore + * @api public + */ - // 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); - } - } - ); - } - } +Document.prototype.$ignore = function(path) { + this.$__.activePaths.ignore(path); +}; - module.exports = RenameOperation; +/** + * Returns the list of paths that have been directly modified. A direct + * modified path is a path that you explicitly set, whether via `doc.foo = 'bar'`, + * `Object.assign(doc, { foo: 'bar' })`, or `doc.set('foo', 'bar')`. + * + * A path `a` may be in `modifiedPaths()` but not in `directModifiedPaths()` + * because a child of `a` was directly modified. + * + * ####Example + * const schema = new Schema({ foo: String, nested: { bar: String } }); + * const Model = mongoose.model('Test', schema); + * await Model.create({ foo: 'original', nested: { bar: 'original' } }); + * + * const doc = await Model.findOne(); + * doc.nested.bar = 'modified'; + * doc.directModifiedPaths(); // ['nested.bar'] + * doc.modifiedPaths(); // ['nested', 'nested.bar'] + * + * @return {Array} + * @api public + */ - /***/ - }, +Document.prototype.directModifiedPaths = function() { + return Object.keys(this.$__.activePaths.states.modify); +}; - /***/ 2508: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +/** + * Returns true if the given path is nullish or only contains empty objects. + * Useful for determining whether this subdoc will get stripped out by the + * [minimize option](/docs/guide.html#minimize). + * + * ####Example: + * const schema = new Schema({ nested: { foo: String } }); + * const Model = mongoose.model('Test', schema); + * const doc = new Model({}); + * doc.$isEmpty('nested'); // true + * doc.nested.$isEmpty(); // true + * + * doc.nested.foo = 'bar'; + * doc.$isEmpty('nested'); // false + * doc.nested.$isEmpty(); // false + * + * @memberOf Document + * @instance + * @api public + * @method $isEmpty + * @return {Boolean} + */ - const OperationBase = __nccwpck_require__(1018).OperationBase; - const updateDocuments = __nccwpck_require__(2296).updateDocuments; - const hasAtomicOperators = __nccwpck_require__(1371).hasAtomicOperators; +Document.prototype.$isEmpty = function(path) { + const isEmptyOptions = { + minimize: true, + virtuals: false, + getters: false, + transform: false + }; - class ReplaceOneOperation extends OperationBase { - constructor(collection, filter, replacement, options) { - super(options); + if (arguments.length > 0) { + const v = this.$get(path); + if (v == null) { + return true; + } + if (typeof v !== 'object') { + return false; + } + if (utils.isPOJO(v)) { + return _isEmpty(v); + } + return Object.keys(v.toObject(isEmptyOptions)).length === 0; + } - if (hasAtomicOperators(replacement)) { - throw new TypeError( - "Replacement document must not contain atomic operators" - ); - } + return Object.keys(this.toObject(isEmptyOptions)).length === 0; +}; - this.collection = collection; - this.filter = filter; - this.replacement = replacement; - } +function _isEmpty(v) { + if (v == null) { + return true; + } + if (typeof v !== 'object' || Array.isArray(v)) { + return false; + } + for (const key of Object.keys(v)) { + if (!_isEmpty(v[key])) { + return false; + } + } + return true; +} - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const replacement = this.replacement; - const options = this.options; +/** + * Returns the list of paths that have been modified. + * + * @param {Object} [options] + * @param {Boolean} [options.includeChildren=false] if true, returns children of modified paths as well. For example, if false, the list of modified paths for `doc.colors = { primary: 'blue' };` will **not** contain `colors.primary`. If true, `modifiedPaths()` will return an array that contains `colors.primary`. + * @return {Array} + * @api public + */ - // Set single document update - options.multi = false; +Document.prototype.modifiedPaths = function(options) { + options = options || {}; + const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); + const _this = this; + return directModifiedPaths.reduce(function(list, path) { + const parts = path.split('.'); + list = list.concat(parts.reduce(function(chains, part, i) { + return chains.concat(parts.slice(0, i).concat(part).join('.')); + }, []).filter(function(chain) { + return (list.indexOf(chain) === -1); + })); + + if (!options.includeChildren) { + return list; + } - // Execute update - updateDocuments(coll, filter, replacement, options, (err, r) => - replaceCallback(err, r, replacement, callback) - ); + let cur = _this.$get(path); + if (cur != null && typeof cur === 'object') { + if (cur._doc) { + cur = cur._doc; + } + if (Array.isArray(cur)) { + const len = cur.length; + for (let i = 0; i < len; ++i) { + if (list.indexOf(path + '.' + i) === -1) { + list.push(path + '.' + i); + if (cur[i] != null && cur[i].$__) { + const modified = cur[i].modifiedPaths(); + for (const childPath of modified) { + list.push(path + '.' + i + '.' + childPath); + } + } + } } + } else { + Object.keys(cur). + filter(function(key) { + return list.indexOf(path + '.' + key) === -1; + }). + forEach(function(key) { + list.push(path + '.' + key); + }); } + } - 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 } }); + return list; + }, []); +}; - 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); - } +Document.prototype[documentModifiedPaths] = Document.prototype.modifiedPaths; - module.exports = ReplaceOneOperation; +/** + * Returns true if any of the given paths is modified, else false. If no arguments, returns `true` if any path + * in this document is modified. + * + * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified. + * + * ####Example + * + * doc.set('documents.0.title', 'changed'); + * doc.isModified() // true + * doc.isModified('documents') // true + * doc.isModified('documents.0.title') // true + * doc.isModified('documents otherProp') // true + * doc.isDirectModified('documents') // false + * + * @param {String} [path] optional + * @return {Boolean} + * @api public + */ - /***/ - }, +Document.prototype.isModified = function(paths, modifiedPaths) { + if (paths) { + if (!Array.isArray(paths)) { + paths = paths.split(' '); + } + const modified = modifiedPaths || this[documentModifiedPaths](); + const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); + const isModifiedChild = paths.some(function(path) { + return !!~modified.indexOf(path); + }); - /***/ 1363: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + return isModifiedChild || paths.some(function(path) { + return directModifiedPaths.some(function(mod) { + return mod === path || path.startsWith(mod + '.'); + }); + }); + } - const CommandOperationV2 = __nccwpck_require__(1189); - const defineAspects = __nccwpck_require__(1018).defineAspects; - const Aspect = __nccwpck_require__(1018).Aspect; + return this.$__.activePaths.some('modify'); +}; - 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, - ]); +Document.prototype.$isModified = Document.prototype.isModified; - module.exports = RunCommandOperation; +Document.prototype[documentIsModified] = Document.prototype.isModified; - /***/ - }, +/** + * Checks if a path is set to its default. + * + * ####Example + * + * MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} }); + * const m = new MyModel(); + * m.$isDefault('name'); // true + * + * @memberOf Document + * @instance + * @method $isDefault + * @param {String} [path] + * @return {Boolean} + * @api public + */ - /***/ 6301: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const CommandOperation = __nccwpck_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; - } +Document.prototype.$isDefault = function(path) { + if (path == null) { + return this.$__.activePaths.some('default'); + } - super(db, options); - this.level = level; - this.profile = profile; - } + if (typeof path === 'string' && path.indexOf(' ') === -1) { + return this.$__.activePaths.states.default.hasOwnProperty(path); + } - _buildCommand() { - const profile = this.profile; + let paths = path; + if (!Array.isArray(paths)) { + paths = paths.split(' '); + } - // Set up the profile number - const command = { profile }; + return paths.some(path => this.$__.activePaths.states.default.hasOwnProperty(path)); +}; - return command; - } +/** + * Getter/setter, determines whether the document was removed or not. + * + * ####Example: + * const product = await product.remove(); + * product.$isDeleted(); // true + * product.remove(); // no-op, doesn't send anything to the db + * + * product.$isDeleted(false); + * product.$isDeleted(); // false + * product.remove(); // will execute a remove against the db + * + * + * @param {Boolean} [val] optional, overrides whether mongoose thinks the doc is deleted + * @return {Boolean} whether mongoose thinks this doc is deleted. + * @method $isDeleted + * @memberOf Document + * @instance + * @api public + */ - execute(callback) { - const level = this.level; +Document.prototype.$isDeleted = function(val) { + if (arguments.length === 0) { + return !!this.$__.isDeleted; + } - if (!levelValues.has(level)) { - return callback( - new Error("Error: illegal profiling level value " + level) - ); - } + this.$__.isDeleted = !!val; + return this; +}; - 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); - }); - } - } +/** + * Returns true if `path` was directly set and modified, else false. + * + * ####Example + * + * doc.set('documents.0.title', 'changed'); + * doc.isDirectModified('documents.0.title') // true + * doc.isDirectModified('documents') // false + * + * @param {String|Array} path + * @return {Boolean} + * @api public + */ - module.exports = SetProfilingLevelOperation; +Document.prototype.isDirectModified = function(path) { + if (path == null) { + return this.$__.activePaths.some('modify'); + } - /***/ - }, + if (typeof path === 'string' && path.indexOf(' ') === -1) { + return this.$__.activePaths.states.modify.hasOwnProperty(path); + } - /***/ 968: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Aspect = __nccwpck_require__(1018).Aspect; - const CommandOperation = __nccwpck_require__(499); - const defineAspects = __nccwpck_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); - } + let paths = path; + if (!Array.isArray(paths)) { + paths = paths.split(' '); + } - _buildCommand() { - const collection = this.collection; - const options = this.options; + return paths.some(path => this.$__.activePaths.states.modify.hasOwnProperty(path)); +}; - // Build command object - const command = { - collStats: collection.collectionName, - }; +/** + * Checks if `path` is in the `init` state, that is, it was set by `Document#init()` and not modified since. + * + * @param {String} path + * @return {Boolean} + * @api public + */ - // Check if we have the scale value - if (options["scale"] != null) { - command["scale"] = options["scale"]; - } +Document.prototype.isInit = function(path) { + if (path == null) { + return this.$__.activePaths.some('init'); + } - return command; - } - } + if (typeof path === 'string' && path.indexOf(' ') === -1) { + return this.$__.activePaths.states.init.hasOwnProperty(path); + } - defineAspects(StatsOperation, Aspect.READ_OPERATION); + let paths = path; + if (!Array.isArray(paths)) { + paths = paths.split(' '); + } - module.exports = StatsOperation; + return paths.some(path => this.$__.activePaths.states.init.hasOwnProperty(path)); +}; - /***/ - }, +/** + * Checks if `path` was selected in the source query which initialized this document. + * + * ####Example + * + * const doc = await Thing.findOne().select('name'); + * doc.isSelected('name') // true + * doc.isSelected('age') // false + * + * @param {String|Array} path + * @return {Boolean} + * @api public + */ - /***/ 9350: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const OperationBase = __nccwpck_require__(1018).OperationBase; - const updateDocuments = __nccwpck_require__(2296).updateDocuments; - const hasAtomicOperators = __nccwpck_require__(1371).hasAtomicOperators; - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - - class UpdateManyOperation extends OperationBase { - constructor(collection, filter, update, options) { - super(options); - - if (!hasAtomicOperators(update)) { - throw new TypeError("Update document requires atomic operators"); - } +Document.prototype.isSelected = function isSelected(path) { + if (this.$__.selected == null) { + return true; + } - 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) => { - if (callback == null) return; - if (err) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - - // If an explain operation was executed, don't process the server results - if (this.explain) return callback(undefined, r.result); - - 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); - }); - } - } + if (path === '_id') { + return this.$__.selected._id !== 0; + } - defineAspects(UpdateManyOperation, [Aspect.EXPLAINABLE]); + if (path.indexOf(' ') !== -1) { + path = path.split(' '); + } + if (Array.isArray(path)) { + return path.some(p => this.$__isSelected(p)); + } - module.exports = UpdateManyOperation; + const paths = Object.keys(this.$__.selected); + let inclusive = null; - /***/ - }, + if (paths.length === 1 && paths[0] === '_id') { + // only _id was selected. + return this.$__.selected._id === 0; + } - /***/ 9068: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const OperationBase = __nccwpck_require__(1018).OperationBase; - const updateDocuments = __nccwpck_require__(2296).updateDocuments; - const hasAtomicOperators = __nccwpck_require__(1371).hasAtomicOperators; - const Aspect = __nccwpck_require__(1018).Aspect; - const defineAspects = __nccwpck_require__(1018).defineAspects; - - class UpdateOneOperation extends OperationBase { - constructor(collection, filter, update, options) { - super(options); - - if (!hasAtomicOperators(update)) { - throw new TypeError("Update document requires atomic operators"); - } + for (const cur of paths) { + if (cur === '_id') { + continue; + } + if (!isDefiningProjection(this.$__.selected[cur])) { + continue; + } + inclusive = !!this.$__.selected[cur]; + break; + } - 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) => { - if (callback == null) return; - if (err) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - - // If an explain operation was executed, don't process the server results - if (this.explain) return callback(undefined, r.result); - - 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); - }); - } - } + if (inclusive === null) { + return true; + } - defineAspects(UpdateOneOperation, [Aspect.EXPLAINABLE]); + if (path in this.$__.selected) { + return inclusive; + } - module.exports = UpdateOneOperation; + const pathDot = path + '.'; - /***/ - }, + for (const cur of paths) { + if (cur === '_id') { + continue; + } - /***/ 9263: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const CommandOperation = __nccwpck_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 ( - Object.prototype.hasOwnProperty.call(options, keys[i]) && - keys[i] !== "session" - ) { - command[keys[i]] = options[keys[i]]; - } - } + if (cur.startsWith(pathDot)) { + return inclusive || cur !== pathDot; + } - super(admin.s.db, options, null, command); - this.collectionName = collectionName; - } + if (pathDot.startsWith(cur + '.')) { + return inclusive; + } + } - execute(callback) { - const collectionName = this.collectionName; + return !inclusive; +}; - super.execute((err, doc) => { - if (err != null) return callback(err, null); +Document.prototype.$__isSelected = Document.prototype.isSelected; - 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 - ); +/** + * Checks if `path` was explicitly selected. If no projection, always returns + * true. + * + * ####Example + * + * Thing.findOne().select('nested.name').exec(function (err, doc) { + * doc.isDirectSelected('nested.name') // true + * doc.isDirectSelected('nested.otherName') // false + * doc.isDirectSelected('nested') // false + * }) + * + * @param {String} path + * @return {Boolean} + * @api public + */ - return callback(null, doc); - }); - } - } +Document.prototype.isDirectSelected = function isDirectSelected(path) { + if (this.$__.selected == null) { + return true; + } - module.exports = ValidateCollectionOperation; + if (path === '_id') { + return this.$__.selected._id !== 0; + } - /***/ - }, + if (path.indexOf(' ') !== -1) { + path = path.split(' '); + } + if (Array.isArray(path)) { + return path.some(p => this.isDirectSelected(p)); + } - /***/ 7289: /***/ (module) => { - "use strict"; + const paths = Object.keys(this.$__.selected); + let inclusive = null; - /** - * 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; - } - } + if (paths.length === 1 && paths[0] === '_id') { + // only _id was selected. + return this.$__.selected._id === 0; + } - /** - * 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; - } + for (const cur of paths) { + if (cur === '_id') { + continue; + } + if (!isDefiningProjection(this.$__.selected[cur])) { + continue; + } + inclusive = !!this.$__.selected[cur]; + break; + } - if (options.readConcern) { - if (options.readConcern instanceof ReadConcern) { - return options.readConcern; - } + if (inclusive === null) { + return true; + } - return new ReadConcern(options.readConcern.level); - } + if (this.$__.selected.hasOwnProperty(path)) { + return inclusive; + } - if (options.level) { - return new ReadConcern(options.level); - } - } + return !inclusive; +}; - static get MAJORITY() { - return "majority"; - } +/** + * Executes registered validation rules for this document. + * + * ####Note: + * + * This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`. + * + * ####Example: + * + * doc.validate(function (err) { + * if (err) handleError(err); + * else // validation passed + * }); + * + * @param {Array|String} [pathsToValidate] list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list. + * @param {Object} [options] internal options + * @param {Boolean} [options.validateModifiedOnly=false] if `true` mongoose validates only modified paths. + * @param {Array|string} [options.pathsToSkip] list of paths to skip. If set, Mongoose will validate every modified path that is not in this list. + * @param {Function} [callback] optional callback called after validation completes, passing an error if one occurred + * @return {Promise} Promise + * @api public + */ - static get AVAILABLE() { - return "available"; - } +Document.prototype.validate = function(pathsToValidate, options, callback) { + let parallelValidate; + this.$op = 'validate'; - static get LINEARIZABLE() { - return "linearizable"; - } + if (this.$isSubdocument != null) { + // Skip parallel validate check for subdocuments + } else if (this.$__.validating) { + parallelValidate = new ParallelValidateError(this, { + parentStack: options && options.parentStack, + conflictStack: this.$__.validating.stack + }); + } else { + this.$__.validating = new ParallelValidateError(this, { parentStack: options && options.parentStack }); + } - static get SNAPSHOT() { - return "snapshot"; - } - } + if (arguments.length === 1) { + if (typeof arguments[0] === 'object' && !Array.isArray(arguments[0])) { + options = arguments[0]; + callback = null; + pathsToValidate = null; + } else if (typeof arguments[0] === 'function') { + callback = arguments[0]; + options = null; + pathsToValidate = null; + } + } else if (typeof pathsToValidate === 'function') { + callback = pathsToValidate; + options = null; + pathsToValidate = null; + } else if (typeof options === 'function') { + callback = options; + options = pathsToValidate; + pathsToValidate = null; + } + if (options && typeof options.pathsToSkip === 'string') { + const isOnePathOnly = options.pathsToSkip.indexOf(' ') === -1; + options.pathsToSkip = isOnePathOnly ? [options.pathsToSkip] : options.pathsToSkip.split(' '); + } - module.exports = ReadConcern; + return promiseOrCallback(callback, cb => { + if (parallelValidate != null) { + return cb(parallelValidate); + } - /***/ - }, + this.$__validate(pathsToValidate, options, (error) => { + this.$op = null; + cb(error); + }); + }, this.constructor.events); +}; - /***/ 2048: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const TopologyBase = __nccwpck_require__(8589) /* .TopologyBase */.oF; - const MongoError = __nccwpck_require__(3994).MongoError; - const CMongos = __nccwpck_require__(3994).Mongos; - const Cursor = __nccwpck_require__(7159); - const Server = __nccwpck_require__(8421); - const Store = __nccwpck_require__(8589) /* .Store */.yh; - const MAX_JS_INT = __nccwpck_require__(1371).MAX_JS_INT; - const translateOptions = __nccwpck_require__(1371).translateOptions; - const filterOptions = __nccwpck_require__(1371).filterOptions; - const mergeOptions = __nccwpck_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", - "bsonRegExp", - "promiseLibrary", - "monitorCommands", - ]; +Document.prototype.$validate = Document.prototype.validate; - /** - * 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=0] 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, - }); - } - } +/*! + * ignore + */ + +function _evaluateRequiredFunctions(doc) { + Object.keys(doc.$__.activePaths.states.require).forEach(path => { + const p = doc.$__schema.path(path); + + if (p != null && typeof p.originalRequiredValue === 'function') { + doc.$__.cachedRequired = doc.$__.cachedRequired || {}; + try { + doc.$__.cachedRequired[path] = p.originalRequiredValue.call(doc, doc); + } catch (err) { + doc.invalidate(path, err); + } + } + }); +} - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === "number" - ? options.bufferMaxEntries - : MAX_JS_INT, - }; +/*! + * ignore + */ - // Shared global store - var store = options.store || new Store(self, storeOptions); +function _getPathsToValidate(doc) { + const skipSchemaValidators = {}; - // Build seed list - var seedlist = servers.map(function (x) { - return { host: x.host, port: x.port }; - }); + _evaluateRequiredFunctions(doc); + // only validate required fields when necessary + let paths = new Set(Object.keys(doc.$__.activePaths.states.require).filter(function(path) { + if (!doc.$__isSelected(path) && !doc.$isModified(path)) { + return false; + } + if (doc.$__.cachedRequired != null && path in doc.$__.cachedRequired) { + return doc.$__.cachedRequired[path]; + } + return 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( - {}, - { - 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, - }; + Object.keys(doc.$__.activePaths.states.init).forEach(addToPaths); + Object.keys(doc.$__.activePaths.states.modify).forEach(addToPaths); + Object.keys(doc.$__.activePaths.states.default).forEach(addToPaths); + function addToPaths(p) { paths.add(p); } + + const subdocs = doc.$getAllSubdocs(); + const modifiedPaths = doc.modifiedPaths(); + for (const subdoc of subdocs) { + if (subdoc.$basePath) { + // Remove child paths for now, because we'll be validating the whole + // subdoc + for (const p of paths) { + if (p === null || p.startsWith(subdoc.$basePath + '.')) { + paths.delete(p); } + } - // 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); - }); + if (doc.$isModified(subdoc.$basePath, modifiedPaths) && + !doc.isDirectModified(subdoc.$basePath) && + !doc.$isDefault(subdoc.$basePath)) { + paths.add(subdoc.$basePath); - self.s.coreTopology.removeListener( - "connect", - connectErrorHandler - ); - // Force close the topology - self.close(true); + skipSchemaValidators[subdoc.$basePath] = true; + } + } + } - // Try to callback - try { - callback(err); - } catch (err) { - process.nextTick(function () { - throw err; - }); - } - }; - }; + // from here on we're not removing items from paths + + // gh-661: if a whole array is modified, make sure to run validation on all + // the children as well + for (const path of paths) { + const _pathType = doc.$__schema.path(path); + if (!_pathType || + !_pathType.$isMongooseArray || + // To avoid potential performance issues, skip doc arrays whose children + // are not required. `getPositionalPathType()` may be slow, so avoid + // it unless we have a case of #6364 + (_pathType.$isMongooseDocumentArray && !get(_pathType, 'schemaOptions.required'))) { + continue; + } - // Actual handler - var errorHandler = function (event) { - return function (err) { - if (event !== "error") { - self.emit(event, err); - } - }; - }; + const val = doc.$__getValue(path); + _pushNestedArrayPaths(val, paths, path); + } - // Error handler - var reconnectHandler = function () { - self.emit("reconnect"); - self.s.store.execute(); - }; + function _pushNestedArrayPaths(val, paths, path) { + if (val != null) { + const numElements = val.length; + for (let j = 0; j < numElements; ++j) { + if (Array.isArray(val[j])) { + _pushNestedArrayPaths(val[j], paths, path + '.' + j); + } else { + paths.add(path + '.' + j); + } + } + } + } - // relay the event - var relay = function (event) { - return function (t, server) { - self.emit(event, t, server); - }; - }; + const flattenOptions = { skipArrays: true }; + for (const pathToCheck of paths) { + if (doc.$__schema.nested[pathToCheck]) { + let _v = doc.$__getValue(pathToCheck); + if (isMongooseObject(_v)) { + _v = _v.toObject({ transform: false }); + } + const flat = flatten(_v, pathToCheck, flattenOptions, doc.$__schema); + Object.keys(flat).forEach(addToPaths); + } + } - // 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); - }); + for (const path of paths) { + // Single nested paths (paths embedded under single nested subdocs) will + // be validated on their own when we call `validate()` on the subdoc itself. + // Re: gh-8468 + if (doc.$__schema.singleNestedPaths.hasOwnProperty(path)) { + paths.delete(path); + continue; + } + const _pathType = doc.$__schema.path(path); + if (!_pathType || !_pathType.$isSchemaMap) { + continue; + } - // Set up listeners - self.s.coreTopology.on("timeout", errorHandler("timeout")); - self.s.coreTopology.on("error", errorHandler("error")); - self.s.coreTopology.on("close", errorHandler("close")); + const val = doc.$__getValue(path); + if (val == null) { + continue; + } + for (const key of val.keys()) { + paths.add(path + '.' + key); + } + } - // Set up serverConfig listeners - self.s.coreTopology.on("fullsetup", function () { - self.emit("fullsetup", self); - }); + paths = Array.from(paths); + return [paths, skipSchemaValidators]; +} - // Emit open event - self.emit("open", null, self); +/*! + * ignore + */ - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function () { - throw err; - }); - } - }; +Document.prototype.$__validate = function(pathsToValidate, options, callback) { + if (typeof pathsToValidate === 'function') { + callback = pathsToValidate; + options = null; + pathsToValidate = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } - // 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); - }); + const hasValidateModifiedOnlyOption = options && + (typeof options === 'object') && + ('validateModifiedOnly' in options); - // 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")); + const pathsToSkip = get(options, 'pathsToSkip', null); - // 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")); + let shouldValidateModifiedOnly; + if (hasValidateModifiedOnlyOption) { + shouldValidateModifiedOnly = !!options.validateModifiedOnly; + } else { + shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly; + } - // Reconnect server - self.s.coreTopology.on("reconnect", reconnectHandler); + const _this = this; + const _complete = () => { + let validationError = this.$__.validationError; + this.$__.validationError = undefined; - // Start connection - self.s.coreTopology.connect(_options); + if (shouldValidateModifiedOnly && validationError != null) { + // Remove any validation errors that aren't from modified paths + const errors = Object.keys(validationError.errors); + for (const errPath of errors) { + if (!this.$isModified(errPath)) { + delete validationError.errors[errPath]; } } + if (Object.keys(validationError.errors).length === 0) { + validationError = void 0; + } + } - Object.defineProperty(Mongos.prototype, "haInterval", { - enumerable: true, - get: function () { - return this.s.coreTopology.s.haInterval; - }, - }); + this.$__.cachedRequired = {}; + this.$emit('validate', _this); + this.constructor.emit('validate', _this); - /** - * 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; - - /***/ - }, + if (validationError) { + for (const key in validationError.errors) { + // Make sure cast errors persist + if (!this[documentArrayParent] && + validationError.errors[key] instanceof MongooseError.CastError) { + this.invalidate(key, validationError.errors[key]); + } + } - /***/ 2632: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Topology = __nccwpck_require__(3994).Topology; - const ServerCapabilities = - __nccwpck_require__(8589) /* .ServerCapabilities */.ug; - const Cursor = __nccwpck_require__(7159); - const translateOptions = __nccwpck_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, - } - ); + return validationError; + } + }; - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); + // only validate required fields when necessary + const pathDetails = _getPathsToValidate(this); + let paths = shouldValidateModifiedOnly ? + pathDetails[0].filter((path) => this.$isModified(path)) : + pathDetails[0]; + const skipSchemaValidators = pathDetails[1]; + if (typeof pathsToValidate === 'string') { + pathsToValidate = pathsToValidate.split(' '); + } + if (Array.isArray(pathsToValidate)) { + paths = _handlePathsToValidate(paths, pathsToValidate); + } else if (pathsToSkip) { + paths = _handlePathsToSkip(paths, pathsToSkip); + } + if (paths.length === 0) { + return immediate(function() { + const error = _complete(); + if (error) { + return _this.$__schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) { + callback(error); + }); + } + callback(null, _this); + }); + } - // Socket options - var socketOptions = - options.socketOptions && - Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; + const validated = {}; + let total = 0; - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); + for (const path of paths) { + validatePath(path); + } - super(servers, clonedOptions); - } + function validatePath(path) { + if (path == null || validated[path]) { + return; + } - 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; - } + validated[path] = true; + total++; - // Command - command(ns, cmd, options, callback) { - super.command(ns.toString(), cmd, options, callback); - } + immediate(function() { + const schemaType = _this.$__schema.path(path); - // Insert - insert(ns, ops, options, callback) { - super.insert(ns.toString(), ops, options, callback); - } + if (!schemaType) { + return --total || complete(); + } - // Update - update(ns, ops, options, callback) { - super.update(ns.toString(), ops, options, callback); - } + // If user marked as invalid or there was a cast error, don't validate + if (!_this.$isValid(path)) { + --total || complete(); + return; + } - // Remove - remove(ns, ops, options, callback) { - super.remove(ns.toString(), ops, options, callback); - } + // If setting a path under a mixed path, avoid using the mixed path validator (gh-10141) + if (schemaType[schemaMixedSymbol] != null && path !== schemaType.path) { + return --total || complete(); } - module.exports = NativeTopology; + let val = _this.$__getValue(path); - /***/ - }, + // If you `populate()` and get back a null value, required validators + // shouldn't fail (gh-8018). We should always fall back to the populated + // value. + let pop; + if ((pop = _this.$populated(path))) { + val = pop; + } else if (val != null && val.$__ != null && val.$__.wasPopulated) { + // Array paths, like `somearray.1`, do not show up as populated with `$populated()`, + // so in that case pull out the document's id + val = val._id; + } + const scope = _this.$__.pathsToScopes != null && path in _this.$__.pathsToScopes ? + _this.$__.pathsToScopes[path] : + _this; - /***/ 382: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Server = __nccwpck_require__(8421); - const Cursor = __nccwpck_require__(7159); - const MongoError = __nccwpck_require__(3994).MongoError; - const TopologyBase = __nccwpck_require__(8589) /* .TopologyBase */.oF; - const Store = __nccwpck_require__(8589) /* .Store */.yh; - const CReplSet = __nccwpck_require__(3994).ReplSet; - const MAX_JS_INT = __nccwpck_require__(1371).MAX_JS_INT; - const translateOptions = __nccwpck_require__(1371).translateOptions; - const filterOptions = __nccwpck_require__(1371).filterOptions; - const mergeOptions = __nccwpck_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", - "bsonRegExp", - "maxStalenessSeconds", - "promiseLibrary", - "minSize", - "monitorCommands", - ]; + const doValidateOptions = { + skipSchemaValidators: skipSchemaValidators[path], + path: path, + validateModifiedOnly: shouldValidateModifiedOnly + }; - /** - * 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, - }); - } + schemaType.doValidate(val, function(err) { + if (err) { + const isSubdoc = schemaType.$isSingleNested || + schemaType.$isArraySubdocument || + schemaType.$isMongooseDocumentArray; + if (isSubdoc && err instanceof ValidationError) { + return --total || complete(); } + _this.invalidate(path, err, undefined, true); + } + --total || complete(); + }, scope, doValidateOptions); + }); + } - // 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); + function complete() { + const error = _complete(); + if (error) { + return _this.$__schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) { + callback(error); + }); + } + callback(null, _this); + } - // 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, - } - ); +/*! + * ignore + */ - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); +function _handlePathsToValidate(paths, pathsToValidate) { + const _pathsToValidate = new Set(pathsToValidate); + const parentPaths = new Map([]); + for (const path of pathsToValidate) { + if (path.indexOf('.') === -1) { + continue; + } + const pieces = path.split('.'); + let cur = pieces[0]; + for (let i = 1; i < pieces.length; ++i) { + // Since we skip subpaths under single nested subdocs to + // avoid double validation, we need to add back the + // single nested subpath if the user asked for it (gh-8626) + parentPaths.set(cur, path); + cur = cur + '.' + pieces[i]; + } + } - // Socket options - var socketOptions = - options.socketOptions && - Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; + const ret = []; + for (const path of paths) { + if (_pathsToValidate.has(path)) { + ret.push(path); + } else if (parentPaths.has(path)) { + ret.push(parentPaths.get(path)); + } + } + return ret; +} - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); +/*! + * ignore + */ +function _handlePathsToSkip(paths, pathsToSkip) { + pathsToSkip = new Set(pathsToSkip); + paths = paths.filter(p => !pathsToSkip.has(p)); + return paths; +} + +/** + * Executes registered validation rules (skipping asynchronous validators) for this document. + * + * ####Note: + * + * This method is useful if you need synchronous validation. + * + * ####Example: + * + * const err = doc.validateSync(); + * if (err) { + * handleError(err); + * } else { + * // validation passed + * } + * + * @param {Array|string} pathsToValidate only validate the given paths + * @param {Object} [options] options for validation + * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths. + * @param {Array|string} [options.pathsToSkip] list of paths to skip. If set, Mongoose will validate every modified path that is not in this list. + * @return {ValidationError|undefined} ValidationError if there are errors during validation, or undefined if there is no error. + * @api public + */ - // Create the ReplSet - var coreTopology = new CReplSet(seedlist, clonedOptions); +Document.prototype.validateSync = function(pathsToValidate, options) { + const _this = this; - // Listen to reconnect event - coreTopology.on("reconnect", function () { - self.emit("reconnect"); - store.execute(); - }); + if (arguments.length === 1 && typeof arguments[0] === 'object' && !Array.isArray(arguments[0])) { + options = arguments[0]; + pathsToValidate = null; + } - // 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, - }; + const hasValidateModifiedOnlyOption = options && + (typeof options === 'object') && + ('validateModifiedOnly' in options); - // Debug - if (clonedOptions.debug) { - // Last ismaster - Object.defineProperty(this, "replset", { - enumerable: true, - get: function () { - return coreTopology; - }, - }); - } - } + let shouldValidateModifiedOnly; + if (hasValidateModifiedOnlyOption) { + shouldValidateModifiedOnly = !!options.validateModifiedOnly; + } else { + shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly; + } - // 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); - } - }; - }; + let pathsToSkip = options && options.pathsToSkip; - // 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); - }); + if (typeof pathsToValidate === 'string') { + const isOnePathOnly = pathsToValidate.indexOf(' ') === -1; + pathsToValidate = isOnePathOnly ? [pathsToValidate] : pathsToValidate.split(' '); + } else if (typeof pathsToSkip === 'string' && pathsToSkip.indexOf(' ') !== -1) { + pathsToSkip = pathsToSkip.split(' '); + } - // relay the event - var relay = function (event) { - return function (t, server) { - self.emit(event, t, server); - }; - }; + // only validate required fields when necessary + const pathDetails = _getPathsToValidate(this); + let paths = shouldValidateModifiedOnly ? + pathDetails[0].filter((path) => this.$isModified(path)) : + pathDetails[0]; + const skipSchemaValidators = pathDetails[1]; + + if (Array.isArray(pathsToValidate)) { + paths = _handlePathsToValidate(paths, pathsToValidate); + } else if (Array.isArray(pathsToSkip)) { + paths = _handlePathsToSkip(paths, pathsToSkip); + } + const validating = {}; - // Replset events relay - var replsetRelay = function (event) { - return function (t, server) { - self.emit(event, t, server.lastIsMaster(), server); - }; - }; + paths.forEach(function(path) { + if (validating[path]) { + return; + } - // Relay ha - var relayHa = function (t, state) { - self.emit("ha", t, state); + validating[path] = true; - if (t === "start") { - self.emit("ha_connect", t, state); - } else if (t === "end") { - self.emit("ha_ismaster", t, state); - } - }; + const p = _this.$__schema.path(path); + if (!p) { + return; + } + if (!_this.$isValid(path)) { + return; + } - // 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); + const val = _this.$__getValue(path); + const err = p.doValidateSync(val, _this, { + skipSchemaValidators: skipSchemaValidators[path], + path: path, + validateModifiedOnly: shouldValidateModifiedOnly + }); + if (err) { + const isSubdoc = p.$isSingleNested || + p.$isArraySubdocument || + p.$isMongooseDocumentArray; + if (isSubdoc && err instanceof ValidationError) { + return; + } + _this.invalidate(path, err, undefined, true); + } + }); - // 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")); + const err = _this.$__.validationError; + _this.$__.validationError = undefined; + _this.$emit('validate', _this); + _this.constructor.emit('validate', _this); - self.s.coreTopology.on("fullsetup", function () { - self.emit("fullsetup", self, self); - }); + if (err) { + for (const key in err.errors) { + // Make sure cast errors persist + if (err.errors[key] instanceof MongooseError.CastError) { + _this.invalidate(key, err.errors[key]); + } + } + } - self.s.coreTopology.on("all", function () { - self.emit("all", null, self); - }); + return err; +}; - // 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")); +/** + * Marks a path as invalid, causing validation to fail. + * + * The `errorMsg` argument will become the message of the `ValidationError`. + * + * The `value` argument (if passed) will be available through the `ValidationError.value` property. + * + * doc.invalidate('size', 'must be less than 20', 14); - // Emit open event - self.emit("open", null, self); + * doc.validate(function (err) { + * console.log(err) + * // prints + * { message: 'Validation failed', + * name: 'ValidationError', + * errors: + * { size: + * { message: 'must be less than 20', + * name: 'ValidatorError', + * path: 'size', + * type: 'user defined', + * value: 14 } } } + * }) + * + * @param {String} path the field to invalidate. For array elements, use the `array.i.field` syntax, where `i` is the 0-based index in the array. + * @param {String|Error} errorMsg the error which states the reason `path` was invalid + * @param {Object|String|Number|any} value optional invalid value + * @param {String} [kind] optional `kind` property for the error + * @return {ValidationError} the current ValidationError, with all currently invalidated paths + * @api public + */ - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function () { - throw err; - }); - } - }; +Document.prototype.invalidate = function(path, err, val, kind) { + if (!this.$__.validationError) { + this.$__.validationError = new ValidationError(this); + } - // Error handler - var connectErrorHandler = function () { - return function (err) { - ["timeout", "error", "close"].forEach(function (e) { - self.s.coreTopology.removeListener(e, connectErrorHandler); - }); + if (this.$__.validationError.errors[path]) { + return; + } - self.s.coreTopology.removeListener( - "connect", - connectErrorHandler - ); - // Destroy the replset - self.s.coreTopology.destroy(); + if (!err || typeof err === 'string') { + err = new ValidatorError({ + path: path, + message: err, + type: kind || 'user defined', + value: val + }); + } - // Try to callback - try { - callback(err); - } catch (err) { - if (!self.s.coreTopology.isConnected()) - process.nextTick(function () { - throw err; - }); - } - }; - }; + if (this.$__.validationError === err) { + return this.$__.validationError; + } - // 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); + this.$__.validationError.addError(path, err); + return this.$__.validationError; +}; - // Start connection - self.s.coreTopology.connect(_options); - } +/** + * Marks a path as valid, removing existing validation errors. + * + * @param {String} path the field to mark as valid + * @api public + * @memberOf Document + * @instance + * @method $markValid + */ - close(forceClosed, callback) { - ["timeout", "error", "close", "joined", "left"].forEach((e) => - this.removeAllListeners(e) - ); - super.close(forceClosed, callback); - } - } +Document.prototype.$markValid = function(path) { + if (!this.$__.validationError || !this.$__.validationError.errors[path]) { + return; + } - Object.defineProperty(ReplSet.prototype, "haInterval", { - enumerable: true, - get: function () { - return this.s.coreTopology.s.haInterval; - }, - }); + delete this.$__.validationError.errors[path]; + if (Object.keys(this.$__.validationError.errors).length === 0) { + this.$__.validationError = null; + } +}; - /** - * 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; - - /***/ - }, +/*! + * ignore + */ - /***/ 8421: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const CServer = __nccwpck_require__(3994).Server; - const Cursor = __nccwpck_require__(7159); - const TopologyBase = __nccwpck_require__(8589) /* .TopologyBase */.oF; - const Store = __nccwpck_require__(8589) /* .Store */.yh; - const MongoError = __nccwpck_require__(3994).MongoError; - const MAX_JS_INT = __nccwpck_require__(1371).MAX_JS_INT; - const translateOptions = __nccwpck_require__(1371).translateOptions; - const filterOptions = __nccwpck_require__(1371).filterOptions; - const mergeOptions = __nccwpck_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", - "bsonRegExp", - "compression", - "promiseLibrary", - "monitorCommands", - ]; +function _markValidSubpaths(doc, path) { + if (!doc.$__.validationError) { + return; + } - /** - * 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=0] 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, - }; + const keys = Object.keys(doc.$__.validationError.errors); + for (const key of keys) { + if (key.startsWith(path + '.')) { + delete doc.$__.validationError.errors[key]; + } + } + if (Object.keys(doc.$__.validationError.errors).length === 0) { + doc.$__.validationError = null; + } +} - // Shared global store - var store = options.store || new Store(self, storeOptions); +/*! + * ignore + */ - // 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, - }); - } +function _checkImmutableSubpaths(subdoc, schematype, priorVal) { + const schema = schematype.schema; + if (schema == null) { + return; + } - // 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, - } - ); + for (const key of Object.keys(schema.paths)) { + const path = schema.paths[key]; + if (path.$immutableSetter == null) { + continue; + } + const oldVal = priorVal == null ? void 0 : priorVal.$__getValue(key); + // Calling immutableSetter with `oldVal` even though it expects `newVal` + // is intentional. That's because `$immutableSetter` compares its param + // to the current value. + path.$immutableSetter.call(subdoc, oldVal); + } +} - // 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, - }; - } +/** + * Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`, + * or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation **only** with the modifications to the database, it does not replace the whole document in the latter case. + * + * ####Example: + * + * product.sold = Date.now(); + * product = await product.save(); + * + * If save is successful, the returned promise will fulfill with the document + * saved. + * + * ####Example: + * + * const newProduct = await product.save(); + * newProduct === product; // true + * + * @param {Object} [options] options optional options + * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). + * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead. + * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. + * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths. + * @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) + * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) + * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern). + * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names) + * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`. + * @param {Function} [fn] optional callback + * @method save + * @memberOf Document + * @instance + * @throws {DocumentNotFoundError} if this [save updates an existing document](api.html#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating). + * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise. + * @api public + * @see middleware http://mongoosejs.com/docs/middleware.html + */ - // 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]); - }); +/** + * Checks if a path is invalid + * + * @param {String|Array} path the field to check + * @method $isValid + * @memberOf Document + * @instance + * @api private + */ - self.s.coreTopology.removeListener( - "connect", - connectErrorHandler - ); +Document.prototype.$isValid = function(path) { + if (this.$__.validationError == null || Object.keys(this.$__.validationError.errors).length === 0) { + return true; + } + if (path == null) { + return false; + } - // Try to callback - try { - callback(err); - } catch (err) { - process.nextTick(function () { - throw err; - }); - } - }; - }; + if (path.indexOf(' ') !== -1) { + path = path.split(' '); + } + if (Array.isArray(path)) { + return path.some(p => this.$__.validationError.errors[p] == null); + } - // Actual handler - var errorHandler = function (event) { - return function (err) { - if (event !== "error") { - self.emit(event, err); - } - }; - }; + return this.$__.validationError.errors[path] == null; +}; - // Error handler - var reconnectHandler = function () { - self.emit("reconnect", self); - self.s.store.execute(); - }; +/** + * Resets the internal modified state of this document. + * + * @api private + * @return {Document} + * @method $__reset + * @memberOf Document + * @instance + */ - // Reconnect failed - var reconnectFailedHandler = function (err) { - self.emit("reconnectFailed", err); - self.s.store.flush(err); - }; +Document.prototype.$__reset = function reset() { + let _this = this; + DocumentArray || (DocumentArray = __nccwpck_require__(3369)); + + this.$__.activePaths + .map('init', 'modify', function(i) { + return _this.$__getValue(i); + }) + .filter(function(val) { + return val && val instanceof Array && val.isMongooseDocumentArray && val.length; + }) + .forEach(function(array) { + let i = array.length; + while (i--) { + const doc = array[i]; + if (!doc) { + continue; + } + doc.$__reset(); + } - // Destroy called on topology, perform cleanup - var destroyHandler = function () { - self.s.store.flush(); - }; + _this.$__.activePaths.init(array.$path()); - // relay the event - var relay = function (event) { - return function (t, server) { - self.emit(event, t, server); - }; - }; + array[arrayAtomicsBackupSymbol] = array[arrayAtomicsSymbol]; + array[arrayAtomicsSymbol] = {}; + }); - // 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); - }); + this.$__.activePaths. + map('init', 'modify', function(i) { + return _this.$__getValue(i); + }). + filter(function(val) { + return val && val.$isSingleNested; + }). + forEach(function(doc) { + doc.$__reset(); + if (doc.$parent() === _this) { + _this.$__.activePaths.init(doc.$basePath); + } else if (doc.$parent() != null && doc.$parent().$isSubdocument) { + // If map path underneath subdocument, may end up with a case where + // map path is modified but parent still needs to be reset. See gh-10295 + doc.$parent().$__reset(); + } + }); - // 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); + // clear atomics + this.$__dirty().forEach(function(dirt) { + const type = dirt.value; - // Emit open event - self.emit("open", null, self); + if (type && type[arrayAtomicsSymbol]) { + type[arrayAtomicsBackupSymbol] = type[arrayAtomicsSymbol]; + type[arrayAtomicsSymbol] = {}; + } + }); - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function () { - throw err; - }); - } - }; + this.$__.backup = {}; + this.$__.backup.activePaths = { + modify: Object.assign({}, this.$__.activePaths.states.modify), + default: Object.assign({}, this.$__.activePaths.states.default) + }; + this.$__.backup.validationError = this.$__.validationError; + this.$__.backup.errors = this.$errors; + + // Clear 'dirty' cache + this.$__.activePaths.clear('modify'); + this.$__.activePaths.clear('default'); + this.$__.validationError = undefined; + this.$errors = undefined; + _this = this; + this.$__schema.requiredPaths().forEach(function(path) { + _this.$__.activePaths.require(path); + }); + + return this; +}; + +/*! + * ignore + */ - // Set up listeners - var connectHandlers = { - timeout: connectErrorHandler("timeout"), - error: connectErrorHandler("error"), - close: connectErrorHandler("close"), - }; +Document.prototype.$__undoReset = function $__undoReset() { + if (this.$__.backup == null || this.$__.backup.activePaths == null) { + return; + } - // 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); - }); + this.$__.activePaths.states.modify = this.$__.backup.activePaths.modify; + this.$__.activePaths.states.default = this.$__.backup.activePaths.default; - // 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")); + this.$__.validationError = this.$__.backup.validationError; + this.$errors = this.$__.backup.errors; - // Start connection - self.s.coreTopology.connect(_options); - } - } + for (const dirt of this.$__dirty()) { + const type = dirt.value; - Object.defineProperty(Server.prototype, "poolSize", { - enumerable: true, - get: function () { - return this.s.coreTopology.connections().length; - }, - }); + if (type && type[arrayAtomicsSymbol] && type[arrayAtomicsBackupSymbol]) { + type[arrayAtomicsSymbol] = type[arrayAtomicsBackupSymbol]; + } + } - Object.defineProperty(Server.prototype, "autoReconnect", { - enumerable: true, - get: function () { - return this.s.reconnect; - }, - }); + for (const subdoc of this.$getAllSubdocs()) { + subdoc.$__undoReset(); + } +}; - Object.defineProperty(Server.prototype, "host", { - enumerable: true, - get: function () { - return this.s.host; - }, - }); +/** + * Returns this documents dirty paths / vals. + * + * @api private + * @method $__dirty + * @memberOf Document + * @instance + */ - Object.defineProperty(Server.prototype, "port", { - enumerable: true, - get: function () { - return this.s.port; - }, - }); +Document.prototype.$__dirty = function() { + const _this = this; + let all = this.$__.activePaths.map('modify', function(path) { + return { + path: path, + value: _this.$__getValue(path), + schema: _this.$__path(path) + }; + }); + // gh-2558: if we had to set a default and the value is not undefined, + // we have to save as well + all = all.concat(this.$__.activePaths.map('default', function(path) { + if (path === '_id' || _this.$__getValue(path) == null) { + return; + } + return { + path: path, + value: _this.$__getValue(path), + schema: _this.$__path(path) + }; + })); - /** - * 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; - - /***/ - }, + const allPaths = new Map(all.filter((el) => el != null).map((el) => [el.path, el.value])); + // Ignore "foo.a" if "foo" is dirty already. + const minimal = []; - /***/ 8589: /***/ ( - __unused_webpack_module, - exports, - __nccwpck_require__ - ) => { - "use strict"; - - const EventEmitter = __nccwpck_require__(8614), - MongoError = __nccwpck_require__(3994).MongoError, - f = __nccwpck_require__(1669).format, - ReadPreference = __nccwpck_require__(3994).ReadPreference, - ClientSession = __nccwpck_require__(3994).Sessions.ClientSession; - - // The store of ops - var Store = function (topology, storeOptions) { - var self = this; - var storedOps = []; - storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 }; + all.forEach(function(item) { + if (!item) { + return; + } - // Internal state - this.s = { - storedOps: storedOps, - storeOptions: storeOptions, - topology: topology, - }; + let top = null; - Object.defineProperty(this, "length", { - enumerable: true, - get: function () { - return self.s.storedOps.length; - }, - }); - }; + const array = parentPaths(item.path); + for (let i = 0; i < array.length - 1; i++) { + if (allPaths.has(array[i])) { + top = allPaths.get(array[i]); + break; + } + } + if (top == null) { + minimal.push(item); + } else if (top != null && + top[arrayAtomicsSymbol] != null && + top.hasAtomics()) { + // special case for top level MongooseArrays + // the `top` array itself and a sub path of `top` are being set. + // the only way to honor all of both modifications is through a $set + // of entire array. + top[arrayAtomicsSymbol] = {}; + top[arrayAtomicsSymbol].$set = top; + } + }); + return minimal; +}; - 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, - }) - ); - } +/** + * Assigns/compiles `schema` into this documents prototype. + * + * @param {Schema} schema + * @api private + * @method $__setSchema + * @memberOf Document + * @instance + */ - 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, - }) - ); - } +Document.prototype.$__setSchema = function(schema) { + compile(schema.tree, this, undefined, schema.options); - 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, - }) - ); - } + // Apply default getters if virtual doesn't have any (gh-6262) + for (const key of Object.keys(schema.virtuals)) { + schema.virtuals[key]._applyDefaultGetters(); + } + if (schema.path('schema') == null) { + this.schema = schema; + } + this.$__schema = schema; + this[documentSchemaSymbol] = schema; +}; - return; - } - this.s.storedOps.push({ - t: opType, - n: ns, - o: ops, - op: options, - c: callback, - }); - }; +/** + * Get active path that were changed and are arrays + * + * @api private + * @method $__getArrayPathsToValidate + * @memberOf Document + * @instance + */ - 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, - }) - ); - } +Document.prototype.$__getArrayPathsToValidate = function() { + DocumentArray || (DocumentArray = __nccwpck_require__(3369)); + + // validate all document arrays. + return this.$__.activePaths + .map('init', 'modify', function(i) { + return this.$__getValue(i); + }.bind(this)) + .filter(function(val) { + return val && val instanceof Array && val.isMongooseDocumentArray && val.length; + }).reduce(function(seed, array) { + return seed.concat(array); + }, []) + .filter(function(doc) { + return doc; + }); +}; - 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, - }) - ); - } +/** + * Get all subdocs (by bfs) + * + * @api public + * @method $getAllSubdocs + * @memberOf Document + * @instance + */ +Document.prototype.$getAllSubdocs = function() { + DocumentArray || (DocumentArray = __nccwpck_require__(3369)); + Embedded = Embedded || __nccwpck_require__(9999); + + function docReducer(doc, seed, path) { + let val = doc; + let isNested = false; + if (path) { + if (doc instanceof Document && doc[documentSchemaSymbol].paths[path]) { + val = doc._doc[path]; + } else if (doc instanceof Document && doc[documentSchemaSymbol].nested[path]) { + val = doc._doc[path]; + isNested = true; + } else { + val = doc[path]; + } + } + if (val instanceof Embedded) { + seed.push(val); + } else if (val instanceof Map) { + seed = Array.from(val.keys()).reduce(function(seed, path) { + return docReducer(val.get(path), seed, null); + }, seed); + } else if (val && val.$isSingleNested) { + seed = Object.keys(val._doc).reduce(function(seed, path) { + return docReducer(val._doc, seed, path); + }, seed); + seed.push(val); + } else if (val && val.isMongooseDocumentArray) { + val.forEach(function _docReduce(doc) { + if (!doc || !doc._doc) { 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, - }) - ); + seed = Object.keys(doc._doc).reduce(function(seed, path) { + return docReducer(doc._doc, seed, path); + }, seed); + if (doc instanceof Embedded) { + seed.push(doc); } - }; + }); + } else if (isNested && val != null) { + for (const path of Object.keys(val)) { + docReducer(val, seed, path); + } + } + return seed; + } - var primaryOptions = [ - "primary", - "primaryPreferred", - "nearest", - "secondaryPreferred", - ]; - var secondaryOptions = ["secondary", "secondaryPreferred"]; + const subDocs = []; + for (const path of Object.keys(this._doc)) { + docReducer(this, subDocs, path); + } - 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); - } - } - } - }; + return subDocs; +}; - Store.prototype.all = function () { - return this.s.storedOps; - }; +/*! + * Runs queued functions + */ - // Server capabilities - var ServerCapabilities = function (ismaster) { - var setup_get_property = function (object, name, value) { - Object.defineProperty(object, name, { - enumerable: true, - get: function () { - return value; - }, - }); - }; +function applyQueue(doc) { + const q = doc.$__schema && doc.$__schema.callQueue; + if (!q.length) { + return; + } - // 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; + for (const pair of q) { + if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') { + doc[pair[0]].apply(doc, pair[1]); + } + } +} - if (ismaster.minWireVersion >= 0) { - textSearch = true; - } +/*! + * ignore + */ - if (ismaster.maxWireVersion >= 1) { - aggregationCursor = true; - authCommands = true; - } +Document.prototype.$__handleReject = function handleReject(err) { + // emit on the Model if listening + if (this.$listeners('error').length) { + this.$emit('error', err); + } else if (this.constructor.listeners && this.constructor.listeners('error').length) { + this.constructor.emit('error', err); + } +}; - if (ismaster.maxWireVersion >= 2) { - writeCommands = true; - } +/** + * Internal helper for toObject() and toJSON() that doesn't manipulate options + * + * @api private + * @method $toObject + * @memberOf Document + * @instance + */ - if (ismaster.maxWireVersion >= 3) { - listCollections = true; - listIndexes = true; - } +Document.prototype.$toObject = function(options, json) { + let defaultOptions = { + transform: true, + flattenDecimals: true + }; - if (ismaster.maxWireVersion >= 5) { - commandsTakeWriteConcern = true; - commandsTakeCollation = true; - } + const path = json ? 'toJSON' : 'toObject'; + const baseOptions = get(this, 'constructor.base.options.' + path, {}); + const schemaOptions = get(this, '$__schema.options', {}); + // merge base default options with Schema's set default options if available. + // `clone` is necessary here because `utils.options` directly modifies the second input. + defaultOptions = utils.options(defaultOptions, clone(baseOptions)); + defaultOptions = utils.options(defaultOptions, clone(schemaOptions[path] || {})); + + // If options do not exist or is not an object, set it to empty object + options = utils.isPOJO(options) ? clone(options) : {}; + options._calledWithOptions = options._calledWithOptions || clone(options); + + let _minimize; + if (options._calledWithOptions.minimize != null) { + _minimize = options.minimize; + } else if (defaultOptions.minimize != null) { + _minimize = defaultOptions.minimize; + } else { + _minimize = schemaOptions.minimize; + } - // If no min or max wire version set to 0 - if (ismaster.minWireVersion == null) { - ismaster.minWireVersion = 0; - } + let flattenMaps; + if (options._calledWithOptions.flattenMaps != null) { + flattenMaps = options.flattenMaps; + } else if (defaultOptions.flattenMaps != null) { + flattenMaps = defaultOptions.flattenMaps; + } else { + flattenMaps = schemaOptions.flattenMaps; + } - if (ismaster.maxWireVersion == null) { - ismaster.maxWireVersion = 0; - } + // The original options that will be passed to `clone()`. Important because + // `clone()` will recursively call `$toObject()` on embedded docs, so we + // need the original options the user passed in, plus `_isNested` and + // `_parentOptions` for checking whether we need to depopulate. + const cloneOptions = Object.assign(utils.clone(options), { + _isNested: true, + json: json, + minimize: _minimize, + flattenMaps: flattenMaps + }); + + if (utils.hasUserDefinedProperty(options, 'getters')) { + cloneOptions.getters = options.getters; + } + if (utils.hasUserDefinedProperty(options, 'virtuals')) { + cloneOptions.virtuals = options.virtuals; + } - // 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 - ); - }; + const depopulate = options.depopulate || + get(options, '_parentOptions.depopulate', false); + // _isNested will only be true if this is not the top level document, we + // should never depopulate + if (depopulate && options._isNested && this.$__.wasPopulated) { + // populated paths that we set to a document + return clone(this._id, cloneOptions); + } - class TopologyBase extends EventEmitter { - constructor() { - super(); - this.setMaxListeners(Infinity); - } + // merge default options with input options. + options = utils.options(defaultOptions, options); + options._isNested = true; + options.json = json; + options.minimize = _minimize; - // Sessions related methods - hasSessionSupport() { - return this.logicalSessionTimeoutMinutes != null; - } + cloneOptions._parentOptions = options; + cloneOptions._skipSingleNestedGetters = true; - startSession(options, clientOptions) { - const session = new ClientSession( - this, - this.s.sessionPool, - options, - clientOptions - ); + const gettersOptions = Object.assign({}, cloneOptions); + gettersOptions._skipSingleNestedGetters = false; - session.once("ended", () => { - this.s.sessions.delete(session); - }); + // remember the root transform function + // to save it from being overwritten by sub-transform functions + const originalTransform = options.transform; - this.s.sessions.add(session); - return session; - } + let ret = clone(this._doc, cloneOptions) || {}; - endSessions(sessions, callback) { - return this.s.coreTopology.endSessions(sessions, callback); - } + if (options.getters) { + applyGetters(this, ret, gettersOptions); - get clientMetadata() { - return this.s.coreTopology.s.options.metadata; - } + if (options.minimize) { + ret = minimize(ret) || {}; + } + } - // 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; - } + if (options.virtuals || (options.getters && options.virtuals !== false)) { + applyVirtuals(this, ret, gettersOptions, options); + } - // Command - command(ns, cmd, options, callback) { - this.s.coreTopology.command( - ns.toString(), - cmd, - ReadPreference.translate(options), - callback - ); - } + if (options.versionKey === false && this.$__schema.options.versionKey) { + delete ret[this.$__schema.options.versionKey]; + } - // Insert - insert(ns, ops, options, callback) { - this.s.coreTopology.insert(ns.toString(), ops, options, callback); - } + let transform = options.transform; - // Update - update(ns, ops, options, callback) { - this.s.coreTopology.update(ns.toString(), ops, options, callback); - } + // In the case where a subdocument has its own transform function, we need to + // check and see if the parent has a transform (options.transform) and if the + // child schema has a transform (this.schema.options.toObject) In this case, + // we need to adjust options.transform to be the child schema's transform and + // not the parent schema's + if (transform) { + applySchemaTypeTransforms(this, ret); + } - // Remove - remove(ns, ops, options, callback) { - this.s.coreTopology.remove(ns.toString(), ops, options, callback); - } + if (options.useProjection) { + omitDeselectedFields(this, ret); + } - // IsConnected - isConnected(options) { - options = options || {}; - options = ReadPreference.translate(options); + if (transform === true || (schemaOptions.toObject && transform)) { + const opts = options.json ? schemaOptions.toJSON : schemaOptions.toObject; - return this.s.coreTopology.isConnected(options); - } + if (opts) { + transform = (typeof options.transform === 'function' ? options.transform : opts.transform); + } + } else { + options.transform = originalTransform; + } - // IsDestroyed - isDestroyed() { - return this.s.coreTopology.isDestroyed(); - } + if (typeof transform === 'function') { + const xformed = transform(this, ret, options); + if (typeof xformed !== 'undefined') { + ret = xformed; + } + } - // Cursor - cursor(ns, cmd, options) { - options = options || {}; - options = ReadPreference.translate(options); - options.disconnectHandler = this.s.store; - options.topology = this; + return ret; +}; - return this.s.coreTopology.cursor(ns, cmd, options); - } +/** + * Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). + * + * Buffers are converted to instances of [mongodb.Binary](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage. + * + * ####Options: + * + * - `getters` apply all getters (path and virtual getters), defaults to false + * - `aliases` apply all aliases if `virtuals=true`, defaults to true + * - `virtuals` apply virtual getters (can override `getters` option), defaults to false + * - `minimize` remove empty objects, defaults to true + * - `transform` a transform function to apply to the resulting document before returning + * - `depopulate` depopulate any populated paths, replacing them with their original refs, defaults to false + * - `versionKey` whether to include the version key, defaults to true + * - `flattenMaps` convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject(), defaults to false + * - `useProjection` set to `true` to omit fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. + * + * ####Getters/Virtuals + * + * Example of only applying path getters + * + * doc.toObject({ getters: true, virtuals: false }) + * + * Example of only applying virtual getters + * + * doc.toObject({ virtuals: true }) + * + * Example of applying both path and virtual getters + * + * doc.toObject({ getters: true }) + * + * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument. + * + * schema.set('toObject', { virtuals: true }) + * + * ####Transform + * + * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function. + * + * Transform functions receive three arguments + * + * function (doc, ret, options) {} + * + * - `doc` The mongoose document which is being converted + * - `ret` The plain object representation which has been converted + * - `options` The options in use (either schema options or the options passed inline) + * + * ####Example + * + * // specify the transform schema option + * if (!schema.options.toObject) schema.options.toObject = {}; + * schema.options.toObject.transform = function (doc, ret, options) { + * // remove the _id of every document before returning the result + * delete ret._id; + * return ret; + * } + * + * // without the transformation in the schema + * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } + * + * // with the transformation + * doc.toObject(); // { name: 'Wreck-it Ralph' } + * + * With transformations we can do a lot more than remove properties. We can even return completely new customized objects: + * + * if (!schema.options.toObject) schema.options.toObject = {}; + * schema.options.toObject.transform = function (doc, ret, options) { + * return { movie: ret.name } + * } + * + * // without the transformation in the schema + * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } + * + * // with the transformation + * doc.toObject(); // { movie: 'Wreck-it Ralph' } + * + * _Note: if a transform function returns `undefined`, the return value will be ignored._ + * + * Transformations may also be applied inline, overridding any transform set in the options: + * + * function xform (doc, ret, options) { + * return { inline: ret.name, custom: true } + * } + * + * // pass the transform as an inline option + * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true } + * + * If you want to skip transformations, use `transform: false`: + * + * schema.options.toObject.hide = '_id'; + * schema.options.toObject.transform = function (doc, ret, options) { + * if (options.hide) { + * options.hide.split(' ').forEach(function (prop) { + * delete ret[prop]; + * }); + * } + * return ret; + * } + * + * const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }); + * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' } + * doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' } + * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' } + * + * If you pass a transform in `toObject()` options, Mongoose will apply the transform + * to [subdocuments](/docs/subdocs.html) in addition to the top-level document. + * Similarly, `transform: false` skips transforms for all subdocuments. + * Note that this behavior is different for transforms defined in the schema: + * if you define a transform in `schema.options.toObject.transform`, that transform + * will **not** apply to subdocuments. + * + * const memberSchema = new Schema({ name: String, email: String }); + * const groupSchema = new Schema({ members: [memberSchema], name: String, email }); + * const Group = mongoose.model('Group', groupSchema); + * + * const doc = new Group({ + * name: 'Engineering', + * email: 'dev@mongoosejs.io', + * members: [{ name: 'Val', email: 'val@mongoosejs.io' }] + * }); + * + * // Removes `email` from both top-level document **and** array elements + * // { name: 'Engineering', members: [{ name: 'Val' }] } + * doc.toObject({ transform: (doc, ret) => { delete ret.email; return ret; } }); + * + * Transforms, like all of these options, are also available for `toJSON`. See [this guide to `JSON.stringify()`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html) to learn why `toJSON()` and `toObject()` are separate functions. + * + * See [schema options](/docs/guide.html#toObject) for some more details. + * + * _During save, no custom options are applied to the document before being sent to the database._ + * + * @param {Object} [options] + * @param {Boolean} [options.getters=false] if true, apply all getters, including virtuals + * @param {Boolean} [options.virtuals=false] if true, apply virtuals, including aliases. Use `{ getters: true, virtuals: false }` to just apply getters, not virtuals + * @param {Boolean} [options.aliases=true] if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`. + * @param {Boolean} [options.minimize=true] if true, omit any empty objects from the output + * @param {Function|null} [options.transform=null] if set, mongoose will call this function to allow you to transform the returned object + * @param {Boolean} [options.depopulate=false] if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths. + * @param {Boolean} [options.versionKey=true] if false, exclude the version key (`__v` by default) from the output + * @param {Boolean} [options.flattenMaps=false] if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`. + * @param {Boolean} [options.useProjection=false] - If true, omits fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. + * @return {Object} js object + * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html + * @api public + * @memberOf Document + * @instance + */ - lastIsMaster() { - return this.s.coreTopology.lastIsMaster(); - } +Document.prototype.toObject = function(options) { + return this.$toObject(options); +}; - selectServer(selector, options, callback) { - return this.s.coreTopology.selectServer(selector, options, callback); - } +/*! + * Minimizes an object, removing undefined values and empty objects + * + * @param {Object} object to minimize + * @return {Object} + */ - /** - * Unref all sockets - * @method - */ - unref() { - return this.s.coreTopology.unref(); - } +function minimize(obj) { + const keys = Object.keys(obj); + let i = keys.length; + let hasKeys; + let key; + let val; - /** - * All raw connections - * @method - * @return {array} - */ - connections() { - return this.s.coreTopology.connections(); - } + while (i--) { + key = keys[i]; + val = obj[key]; - 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 (utils.isPOJO(val)) { + obj[key] = minimize(val); + } - if (this.s.sessionPool) { - this.s.sessionPool.endAllPooledSessions(); - } + if (undefined === obj[key]) { + delete obj[key]; + continue; + } - // We need to wash out all stored processes - if (forceClosed === true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } + hasKeys = true; + } - this.s.coreTopology.destroy( - { - force: typeof forceClosed === "boolean" ? forceClosed : false, - }, - callback - ); - } - } + return hasKeys + ? obj + : undefined; +} - // Properties - Object.defineProperty(TopologyBase.prototype, "bson", { - enumerable: true, - get: function () { - return this.s.coreTopology.s.bson; - }, - }); +/*! + * Applies virtuals properties to `json`. + */ - Object.defineProperty(TopologyBase.prototype, "parserType", { - enumerable: true, - get: function () { - return this.s.coreTopology.parserType; - }, - }); +function applyVirtuals(self, json, options, toObjectOptions) { + const schema = self.$__schema; + const paths = Object.keys(schema.virtuals); + let i = paths.length; + const numPaths = i; + let path; + let assignPath; + let cur = self._doc; + let v; + const aliases = get(toObjectOptions, 'aliases', true); + + let virtualsToApply = null; + if (Array.isArray(options.virtuals)) { + virtualsToApply = new Set(options.virtuals); + } + else if (options.virtuals && options.virtuals.pathsToSkip) { + virtualsToApply = new Set(paths); + for (let i = 0; i < options.virtuals.pathsToSkip.length; i++) { + if (virtualsToApply.has(options.virtuals.pathsToSkip[i])) { + virtualsToApply.delete(options.virtuals.pathsToSkip[i]); + } + } + } - Object.defineProperty( - TopologyBase.prototype, - "logicalSessionTimeoutMinutes", - { - enumerable: true, - get: function () { - return this.s.coreTopology.logicalSessionTimeoutMinutes; - }, - } - ); + if (!cur) { + return json; + } - Object.defineProperty(TopologyBase.prototype, "type", { - enumerable: true, - get: function () { - return this.s.coreTopology.type; - }, - }); + options = options || {}; + for (i = 0; i < numPaths; ++i) { + path = paths[i]; - exports.yh = Store; - exports.ug = ServerCapabilities; - exports.oF = TopologyBase; + if (virtualsToApply != null && !virtualsToApply.has(path)) { + continue; + } - /***/ - }, + // Allow skipping aliases with `toObject({ virtuals: true, aliases: false })` + if (!aliases && schema.aliases.hasOwnProperty(path)) { + continue; + } - /***/ 8729: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const ReadPreference = __nccwpck_require__(3994).ReadPreference; - const parser = __nccwpck_require__(8835); - const f = __nccwpck_require__(1669).format; - const Logger = __nccwpck_require__(3994).Logger; - const dns = __nccwpck_require__(881); - const ReadConcern = __nccwpck_require__(7289); - const qs = __nccwpck_require__(1191); - const MongoParseError = __nccwpck_require__(3111).MongoParseError; - - module.exports = function (url, options, callback) { - if (typeof options === "function") (callback = options), (options = {}); - options = options || {}; + // We may be applying virtuals to a nested object, for example if calling + // `doc.nestedProp.toJSON()`. If so, the path we assign to, `assignPath`, + // will be a trailing substring of the `path`. + assignPath = path; + if (options.path != null) { + if (!path.startsWith(options.path + '.')) { + continue; + } + assignPath = path.substr(options.path.length + 1); + } + const parts = assignPath.split('.'); + v = clone(self.get(path), options); + if (v === void 0) { + continue; + } + const plen = parts.length; + cur = json; + for (let j = 0; j < plen - 1; ++j) { + cur[parts[j]] = cur[parts[j]] || {}; + cur = cur[parts[j]]; + } + cur[parts[plen - 1]] = v; + } - let result; - try { - result = parser.parse(url, true); - } catch (e) { - return callback(new Error("URL malformed, cannot be parsed")); - } + return json; +} - 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); - } +/*! + * Applies virtuals properties to `json`. + * + * @param {Document} self + * @param {Object} json + * @return {Object} `json` + */ - // 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") - ); - } +function applyGetters(self, json, options) { + const schema = self.$__schema; + const paths = Object.keys(schema.paths); + let i = paths.length; + let path; + let cur = self._doc; + let v; - result.domainLength = result.hostname.split(".").length; + if (!cur) { + return json; + } - const hostname = url.substring("mongodb+srv://".length).split("/")[0]; - if (hostname.match(",")) { - return callback( - new Error("Invalid URI, cannot contain multiple hostnames") - ); - } + while (i--) { + path = paths[i]; - if (result.port) { - return callback( - new Error("Ports not accepted with `mongodb+srv` URIs") - ); - } + const parts = path.split('.'); + const plen = parts.length; + const last = plen - 1; + let branch = json; + let part; + cur = self._doc; - let srvAddress = `_mongodb._tcp.${result.host}`; - dns.resolveSrv(srvAddress, function (err, addresses) { - if (err) return callback(err); + if (!self.$__isSelected(path)) { + continue; + } - if (addresses.length === 0) { - return callback(new Error("No addresses found at host")); - } + for (let ii = 0; ii < plen; ++ii) { + part = parts[ii]; + v = cur[part]; + if (ii === last) { + const val = self.$get(path); + branch[part] = clone(val, options); + } else if (v == null) { + if (part in cur) { + branch[part] = v; + } + break; + } else { + branch = branch[part] || (branch[part] = {}); + } + cur = v; + } + } - 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" - ) - ); - } - } + return json; +} - 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}`; - }); +/*! + * Applies schema type transforms to `json`. + * + * @param {Document} self + * @param {Object} json + * @return {Object} `json` + */ - let connectionString = connectionStrings.join(",") + "/"; - let connectionStringOptions = []; +function applySchemaTypeTransforms(self, json) { + const schema = self.$__schema; + const paths = Object.keys(schema.paths || {}); + const cur = self._doc; - // 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("?")); - } + if (!cur) { + return json; + } - connectionString += defaultDb; - } + for (const path of paths) { + const schematype = schema.paths[path]; + if (typeof schematype.options.transform === 'function') { + const val = self.$get(path); + const transformedValue = schematype.options.transform.call(self, val); + throwErrorIfPromise(path, transformedValue); + utils.setValue(path, transformedValue, json); + } else if (schematype.$embeddedSchemaType != null && + typeof schematype.$embeddedSchemaType.options.transform === 'function') { + const vals = [].concat(self.$get(path)); + const transform = schematype.$embeddedSchemaType.options.transform; + for (let i = 0; i < vals.length; ++i) { + const transformedValue = transform.call(self, vals[i]); + vals[i] = transformedValue; + throwErrorIfPromise(path, transformedValue); + } + + json[path] = vals; + } + } - // 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"); - } + return json; +} - // Keep original uri options - if (result.search) { - connectionStringOptions.push(result.search.replace("?", "")); - } +function throwErrorIfPromise(path, transformedValue) { + if (isPromise(transformedValue)) { + throw new Error('`transform` function must be synchronous, but the transform on path `' + path + '` returned a promise.'); + } +} - dns.resolveTxt(result.host, function (err, record) { - if (err && err.code !== "ENODATA" && err.code !== "ENOTFOUND") - return callback(err); - if (err && err.code === "ENODATA") record = null; +/*! + * ignore + */ - if (record) { - if (record.length > 1) { - return callback( - new MongoParseError("Multiple text records not allowed") - ); - } +function omitDeselectedFields(self, json) { + const schema = self.$__schema; + const paths = Object.keys(schema.paths || {}); + const cur = self._doc; - record = record[0].join(""); - const parsedRecord = qs.parse(record); - const items = Object.keys(parsedRecord); - if ( - items.some( - (item) => item !== "authSource" && item !== "replicaSet" - ) - ) { - return callback( - new MongoParseError( - "Text record must only set `authSource` or `replicaSet`" - ) - ); - } + if (!cur) { + return json; + } - if (items.length > 0) { - connectionStringOptions.push(record); - } - } + let selected = self.$__.selected; + if (selected === void 0) { + selected = {}; + queryhelpers.applyPaths(selected, schema); + } + if (selected == null || Object.keys(selected).length === 0) { + return json; + } - // Add any options to the connection string - if (connectionStringOptions.length) { - connectionString += `?${connectionStringOptions.join("&")}`; - } + for (const path of paths) { + if (selected[path] != null && !selected[path]) { + delete json[path]; + } + } - parseHandler(connectionString, options, callback); - }); - }); - }; + return json; +} - 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; - } +/** + * The return value of this method is used in calls to JSON.stringify(doc). + * + * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument. + * + * schema.set('toJSON', { virtuals: true }) + * + * See [schema options](/docs/guide.html#toJSON) for details. + * + * @param {Object} options + * @return {Object} + * @see Document#toObject #document_Document-toObject + * @see JSON.stringify() in JavaScript https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html + * @api public + * @memberOf Document + * @instance + */ - function parseHandler(address, options, callback) { - let result, err; - try { - result = parseConnectionString(address, options); - } catch (e) { - err = e; - } +Document.prototype.toJSON = function(options) { + return this.$toObject(options, true); +}; - 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"; +Document.prototype.ownerDocument = function() { + return this; +}; - // 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 this document is a subdocument or populated document, returns the document's + * parent. Returns the original document if there is no parent. + * + * @api public + * @method parent + * @memberOf Document + * @instance + */ - if ( - !isNaN(parseInt(result.port, 10)) && - parseInt(result.port, 10) > 65535 - ) { - throw new Error("Invalid port (larger than 65535) with hostname"); - } +Document.prototype.parent = function() { + if (this.$isSubdocument || this.$__.wasPopulated) { + return this.$__.parent; + } + return this; +}; - if ( - result.path && - result.path.length > 0 && - result.path[0] !== "/" && - url.indexOf(".sock") === -1 - ) { - throw new Error("Missing delimiting slash between hosts and options"); - } +/** + * Alias for `parent()`. If this document is a subdocument or populated + * document, returns the document's parent. Returns `undefined` otherwise. + * + * @api public + * @method $parent + * @memberOf Document + * @instance + */ - if (result.query) { - for (let name in result.query) { - if (name.indexOf("::") !== -1) { - throw new Error("Double colon in host identifier"); - } +Document.prototype.$parent = Document.prototype.parent; - if (result.query[name] === "") { - throw new Error( - "Query parameter " + name + " is an incomplete value pair" - ); - } - } - } +/** + * Helper for console.log + * + * @api public + * @method inspect + * @memberOf Document + * @instance + */ - 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" - ); - } +Document.prototype.inspect = function(options) { + const isPOJO = utils.isPOJO(options); + let opts; + if (isPOJO) { + opts = options; + opts.minimize = false; + } + const ret = this.toObject(opts); - if ( - url.indexOf(result.auth) !== -1 && - result.auth.indexOf("@") !== -1 - ) { - throw new Error("Username containing an unescaped at-sign"); - } - } + if (ret == null) { + // If `toObject()` returns null, `this` is still an object, so if `inspect()` + // prints out null this can cause some serious confusion. See gh-7942. + return 'MongooseDocument { ' + ret + ' }'; + } - // Remove query - let clean = url.split("?").shift(); + return ret; +}; - // Extract the list of hosts - let strings = clean.split(","); - let hosts = []; +if (inspect.custom) { + /*! + * Avoid Node deprecation warning DEP0079 + */ - for (let i = 0; i < strings.length; i++) { - let hostString = strings[i]; + Document.prototype[inspect.custom] = Document.prototype.inspect; +} - 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()); - } - } +/** + * Helper for console.log + * + * @api public + * @method toString + * @memberOf Document + * @instance + */ - 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"); - } - } - } +Document.prototype.toString = function() { + const ret = this.inspect(); + if (typeof ret === 'string') { + return ret; + } + return inspect(ret); +}; - // 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); - } +/** + * Returns true if this document is equal to another document. + * + * Documents are considered equal when they have matching `_id`s, unless neither + * document has an `_id`, in which case this function falls back to using + * `deepEqual()`. + * + * @param {Document} doc a document to compare + * @return {Boolean} + * @api public + * @memberOf Document + * @instance + */ - // Check if we have auth params - if (connection_part.indexOf("@") !== -1) { - auth_part = connection_part.split("@")[0]; - connection_part = connection_part.split("@")[1]; - } +Document.prototype.equals = function(doc) { + if (!doc) { + return false; + } - // 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" - ); - } + const tid = this.$__getValue('_id'); + const docid = doc.$__ != null ? doc.$__getValue('_id') : doc; + if (!tid && !docid) { + return deepEqual(this, doc); + } + return tid && tid.equals + ? tid.equals(docid) + : tid === docid; +}; - // 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]; - } +/** + * Populates paths on an existing document. + * + * ####Example: + * + * await doc.populate([ + * 'stories', + * { path: 'fans', sort: { name: -1 } } + * ]); + * doc.populated('stories'); // Array of ObjectIds + * doc.stories[0].title; // 'Casino Royale' + * doc.populated('fans'); // Array of ObjectIds + * + * await doc.populate('fans', '-email'); + * doc.fans[0].email // not populated + * + * await doc.populate('author fans', '-email'); + * doc.author.email // not populated + * doc.fans[0].email // not populated + * + * @param {String|Object|Array} path either the path to populate or an object specifying all parameters, or either an array of those + * @param {Object|String} [select] Field selection for the population query + * @param {Model} [model] The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field. + * @param {Object} [match] Conditions for the population query + * @param {Object} [options] Options for the population query (sort, etc) + * @param {String} [options.path=null] The path to populate. + * @param {boolean} [options.retainNullValues=false] by default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries. + * @param {boolean} [options.getters=false] if true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options). + * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them. + * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object. + * @param {Function} [options.transform=null] Function that Mongoose will call on every populated document that allows you to transform the populated document. + * @param {Object} [options.options=null] Additional options like `limit` and `lean`. + * @param {Function} [callback] Callback + * @see population ./populate.html + * @see Query#select #query_Query-select + * @see Model.populate #model_Model.populate + * @memberOf Document + * @instance + * @return {Promise|null} + * @api public + */ - // URI decode the host information - connection_part = decodeURIComponent(connection_part); +Document.prototype.populate = function populate() { + const pop = {}; + const args = utils.args(arguments); + let fn; - // Result object - let object = {}; + if (args.length > 0) { + if (typeof args[args.length - 1] === 'function') { + fn = args.pop(); + } - // Pick apart the authentication part of the string - let authPart = auth_part || ""; - let auth = authPart.split(":", 2); + // use hash to remove duplicate paths + const res = utils.populate.apply(null, args); + for (const populateOptions of res) { + pop[populateOptions.path] = populateOptions; + } + } - // 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; + const paths = utils.object.vals(pop); + let topLevelModel = this.constructor; + if (this.$__isNested) { + topLevelModel = this.$__[scopeSymbol].constructor; + const nestedPath = this.$__.nestedPath; + paths.forEach(function(populateOptions) { + populateOptions.path = nestedPath + '.' + populateOptions.path; + }); + } - 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]; - } + // Use `$session()` by default if the document has an associated session + // See gh-6754 + if (this.$session() != null) { + const session = this.$session(); + paths.forEach(path => { + if (path.options == null) { + path.options = { session: session }; + return; + } + if (!('session' in path.options)) { + path.options.session = session; + } + }); + } - // No entry returned for duplicate server - if (deduplicatedServers[_host + "_" + _port]) return null; - deduplicatedServers[_host + "_" + _port] = 1; + paths.forEach(p => { + p._localModel = topLevelModel; + }); - // Return the mapped object - return { host: _host, port: _port }; - }) - .filter(function (x) { - return x != null; - }); - } + return topLevelModel.populate(this, paths, fn); +}; - // 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) }; - } +/** + * Gets all populated documents associated with this document. + * + * @api public + * @return {Array} array of populated documents. Empty array if there are no populated documents associated with this document. + * @memberOf Document + * @instance + */ +Document.prototype.$getPopulatedDocs = function $getPopulatedDocs() { + let keys = []; + if (this.$__.populated != null) { + keys = keys.concat(Object.keys(this.$__.populated)); + } + let result = []; + for (const key of keys) { + const value = this.$get(key); + if (Array.isArray(value)) { + result = result.concat(value); + } else if (value instanceof Document) { + result.push(value); + } + } + return result; +}; - // 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" - ); +/** + * Gets _id(s) used during population of the given `path`. + * + * ####Example: + * + * Model.findOne().populate('author').exec(function (err, doc) { + * console.log(doc.author.name) // Dr.Seuss + * console.log(doc.populated('author')) // '5144cf8050f071d979c118a7' + * }) + * + * If the path was not populated, returns `undefined`. + * + * @param {String} path + * @return {Array|ObjectId|Number|Buffer|String|undefined} + * @memberOf Document + * @instance + * @api public + */ - // 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]; - }); +Document.prototype.populated = function(path, val, options) { + // val and options are internal + if (val == null || val === true) { + if (!this.$__.populated) { + return undefined; + } + if (typeof path !== 'string') { + return undefined; + } - // 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; - } + // Map paths can be populated with either `path.$*` or just `path` + const _path = path.endsWith('.$*') ? path.replace(/\.\$\*$/, '') : path; - // 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]; - } + const v = this.$__.populated[_path]; + if (v) { + return val === true ? v : v.value; + } + return undefined; + } - // 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" - ); - } + this.$__.populated || (this.$__.populated = {}); + this.$__.populated[path] = { value: val, options: options }; + + // If this was a nested populate, make sure each populated doc knows + // about its populated children (gh-7685) + const pieces = path.split('.'); + for (let i = 0; i < pieces.length - 1; ++i) { + const subpath = pieces.slice(0, i + 1).join('.'); + const subdoc = this.$get(subpath); + if (subdoc != null && subdoc.$__ != null && this.$populated(subpath)) { + const rest = pieces.slice(i + 1).join('.'); + subdoc.$populated(rest, val, options); + // No need to continue because the above recursion should take care of + // marking the rest of the docs as populated + break; + } + } - 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" - ); - } + return val; +}; - 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; - } - }); +Document.prototype.$populated = Document.prototype.populated; - // No tags: should be null (not []) - if (dbOptions.read_preference_tags.length === 0) { - dbOptions.read_preference_tags = null; - } +/** + * Takes a populated field and returns it to its unpopulated state. + * + * ####Example: + * + * Model.findOne().populate('author').exec(function (err, doc) { + * console.log(doc.author.name); // Dr.Seuss + * console.log(doc.depopulate('author')); + * console.log(doc.author); // '5144cf8050f071d979c118a7' + * }) + * + * If the path was not provided, then all populated fields are returned to their unpopulated state. + * + * @param {String} path + * @return {Document} this + * @see Document.populate #document_Document-populate + * @api public + * @memberOf Document + * @instance + */ - // 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" - ); +Document.prototype.depopulate = function(path) { + if (typeof path === 'string') { + path = path.indexOf(' ') === -1 ? [path] : path.split(' '); + } - // If no read preference set it to primary - if (!dbOptions.readPreference) { - dbOptions.readPreference = "primary"; - } + let populatedIds; + const virtualKeys = this.$$populatedVirtuals ? Object.keys(this.$$populatedVirtuals) : []; + const populated = get(this, '$__.populated', {}); - // make sure that user-provided options are applied with priority - dbOptions = Object.assign(dbOptions, options); + if (arguments.length === 0) { + // Depopulate all + for (const virtualKey of virtualKeys) { + delete this.$$populatedVirtuals[virtualKey]; + delete this._doc[virtualKey]; + delete populated[virtualKey]; + } - // Add servers to result - object.servers = servers; + const keys = Object.keys(populated); - // Returned parsed object - return object; + for (const key of keys) { + populatedIds = this.$populated(key); + if (!populatedIds) { + continue; } + delete populated[key]; + utils.setValue(key, populatedIds, this._doc); + } + return this; + } - /***/ - }, + for (const singlePath of path) { + populatedIds = this.$populated(singlePath); + delete populated[singlePath]; - /***/ 1371: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; + if (virtualKeys.indexOf(singlePath) !== -1) { + delete this.$$populatedVirtuals[singlePath]; + delete this._doc[singlePath]; + } else if (populatedIds) { + utils.setValue(singlePath, populatedIds, this._doc); + } + } + return this; +}; - const MongoError = __nccwpck_require__(3111).MongoError; - const WriteConcern = __nccwpck_require__(2481); - var shallowClone = function (obj) { - var copy = {}; - for (var name in obj) copy[name] = obj[name]; - return copy; - }; +/** + * Returns the full path to this document. + * + * @param {String} [path] + * @return {String} + * @api private + * @method $__fullPath + * @memberOf Document + * @instance + */ - // Set simple property - var getSingleProperty = function (obj, name, value) { - Object.defineProperty(obj, name, { - enumerable: true, - get: function () { - return value; - }, - }); - }; +Document.prototype.$__fullPath = function(path) { + // overridden in SubDocuments + return path || ''; +}; - var formatSortValue = (exports.formatSortValue = function ( - sortDirection - ) { - var value = ("" + sortDirection).toLowerCase(); +/** + * Returns the changes that happened to the document + * in the format that will be sent to MongoDB. + * + * #### Example: + * + * const userSchema = new Schema({ + * name: String, + * age: Number, + * country: String + * }); + * const User = mongoose.model('User', userSchema); + * const user = await User.create({ + * name: 'Hafez', + * age: 25, + * country: 'Egypt' + * }); + * + * // returns an empty object, no changes happened yet + * user.getChanges(); // { } + * + * user.country = undefined; + * user.age = 26; + * + * user.getChanges(); // { $set: { age: 26 }, { $unset: { country: 1 } } } + * + * await user.save(); + * + * user.getChanges(); // { } + * + * Modifying the object that `getChanges()` returns does not affect the document's + * change tracking state. Even if you `delete user.getChanges().$set`, Mongoose + * will still send a `$set` to the server. + * + * @return {Object} + * @api public + * @method getChanges + * @memberOf Document + * @instance + */ - 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)']]" - ); - } - }); +Document.prototype.getChanges = function() { + const delta = this.$__delta(); + const changes = delta ? delta[1] : {}; + return changes; +}; - var formattedOrderClause = (exports.formattedOrderClause = function ( - sortValue - ) { - var orderBy = new Map(); - if (sortValue == null) return null; - if (Array.isArray(sortValue)) { - if (sortValue.length === 0) { - return null; - } +/*! + * Module exports. + */ - for (var i = 0; i < sortValue.length; i++) { - if (sortValue[i].constructor === String) { - orderBy.set(`${sortValue[i]}`, 1); - } else { - orderBy.set( - `${sortValue[i][0]}`, - formatSortValue(sortValue[i][1]) - ); - } - } - } else if (sortValue != null && typeof sortValue === "object") { - if (sortValue instanceof Map) { - orderBy = sortValue; - } else { - var sortKeys = Object.keys(sortValue); - for (var k of sortKeys) { - orderBy.set(k, sortValue[k]); - } - } - } else if (typeof sortValue === "string") { - orderBy.set(`${sortValue}`, 1); - } else { - throw new Error( - "Illegal sort clause, must be of the form " + - "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" - ); - } +Document.ValidationError = ValidationError; +module.exports = exports = Document; - 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"); - } +/***/ 1860: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ( - collectionName.indexOf("$") !== -1 && - collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null - ) { - throw new MongoError("collection names must not contain '$'"); - } +"use strict"; - 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" - ); - } - }; +/* eslint-env browser */ - var handleCallback = function (callback, err, value1, value2) { - try { - if (callback == null) return; +/*! + * Module dependencies. + */ +const Document = __nccwpck_require__(6717); +const BrowserDocument = __nccwpck_require__(6830); - if (callback) { - return value2 - ? callback(err, value1, value2) - : callback(err, value1); - } - } catch (err) { - process.nextTick(function () { - throw err; - }); - return false; - } +let isBrowser = false; - return true; - }; +/** + * Returns the Document constructor for the current context + * + * @api private + */ +module.exports = function() { + if (isBrowser) { + return BrowserDocument; + } + return Document; +}; - /** - * Wrap a Mongo error document in an Error instance - * @ignore - * @api private - */ - var toError = function (error) { - if (error instanceof Error) return error; +/*! + * ignore + */ +module.exports.setBrowser = function(flag) { + isBrowser = flag; +}; - 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 - } - } +/***/ 2324: +/***/ ((module) => { - return e; - }; +"use strict"; - /** - * @ignore - */ - var normalizeHintField = function normalizeHintField(hint) { - var finalHint = null; - if (typeof hint === "string") { - finalHint = hint; - } else if (Array.isArray(hint)) { - finalHint = {}; +/*! + * ignore + */ - hint.forEach(function (param) { - finalHint[param] = 1; - }); - } else if (hint != null && typeof hint === "object") { - finalHint = {}; - for (var name in hint) { - finalHint[name] = hint[name]; - } - } +let driver = null; - return finalHint; - }; +module.exports.get = function() { + return driver; +}; - /** - * 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]; - }); - } +module.exports.set = function(v) { + driver = v; +}; - 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]; - }); +/***/ 8001: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return finaloptions; - }; +"use strict"; +/*! + * Module dependencies. + */ - 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]; - } +const mongodb = __nccwpck_require__(8821); +const ReadPref = mongodb.ReadPreference; - return target; - }; +/*! + * Converts arguments to ReadPrefs the driver + * can understand. + * + * @param {String|Array} pref + * @param {Array} [tags] + */ - // 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", - }; +module.exports = function readPref(pref, tags) { + if (Array.isArray(pref)) { + tags = pref[1]; + pref = pref[0]; + } - for (var name in source) { - if (translations[name]) { - target[translations[name]] = source[name]; - } else { - target[name] = source[name]; - } - } + if (pref instanceof ReadPref) { + return pref; + } - return target; - }; + switch (pref) { + case 'p': + pref = 'primary'; + break; + case 'pp': + pref = 'primaryPreferred'; + break; + case 's': + pref = 'secondary'; + break; + case 'sp': + pref = 'secondaryPreferred'; + break; + case 'n': + pref = 'nearest'; + break; + } - var filterOptions = function (options, names) { - var filterOptions = {}; + return new ReadPref(pref, tags); +}; - for (var name in options) { - if (names.indexOf(name) !== -1) filterOptions[name] = options[name]; - } - // Filtered options - return filterOptions; - }; +/***/ }), - // Write concern keys - const WRITE_CONCERN_KEYS = [ - "w", - "j", - "wtimeout", - "fsync", - "writeConcern", - ]; +/***/ 4473: +/***/ ((module, exports, __nccwpck_require__) => { - /** - * If there is no WriteConcern related options defined on target then inherit from source. - * Otherwise, do not inherit **any** options from source. - * @internal - * @param {object} target - options object conditionally receiving the writeConcern options - * @param {object} source - options object containing the potentially inherited writeConcern options - */ - function conditionallyMergeWriteConcern(target, source) { - let found = false; - for (const wcKey of WRITE_CONCERN_KEYS) { - if (wcKey in target) { - // Found a writeConcern option - found = true; - break; - } - } +"use strict"; - if (!found) { - for (const wcKey of WRITE_CONCERN_KEYS) { - if (source[wcKey]) { - if (!("writeConcern" in target)) { - target.writeConcern = {}; - } - target.writeConcern[wcKey] = source[wcKey]; - } - } - } +/*! + * Module dependencies. + */ - return target; - } - /** - * 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" - ); - } +const Binary = __nccwpck_require__(8821).Binary; - options = options || {}; - const Promise = topology.s.promiseLibrary; - let callback = args[args.length - 1]; +module.exports = exports = Binary; - // 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); +/***/ 449: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - try { - return operation.apply(null, args); - } catch (e) { - handler(e); - throw e; - } - } +"use strict"; - // 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; +/*! + * Module dependencies. + */ - try { - return operation.apply(null, args); - } catch (e) { - handler(e); - } - }); - }; +const MongooseCollection = __nccwpck_require__(6798); +const MongooseError = __nccwpck_require__(5953); +const Collection = __nccwpck_require__(8821).Collection; +const ObjectId = __nccwpck_require__(3589); +const get = __nccwpck_require__(8730); +const getConstructorName = __nccwpck_require__(7323); +const sliced = __nccwpck_require__(9889); +const stream = __nccwpck_require__(2413); +const util = __nccwpck_require__(1669); + +/** + * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) collection implementation. + * + * All methods methods from the [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver are copied and wrapped in queue management. + * + * @inherits Collection + * @api private + */ - /** - * 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; - } +function NativeCollection(name, conn, options) { + this.collection = null; + this.Promise = options.Promise || Promise; + this.modelName = options.modelName; + delete options.modelName; + this._closed = false; + MongooseCollection.apply(this, arguments); +} + +/*! + * Inherit from abstract Collection. + */ - return target; - } +NativeCollection.prototype.__proto__ = MongooseCollection.prototype; - /** - * 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; +/** + * Called when the connection opens. + * + * @api private + */ - if (options.session && options.session.inTransaction()) { - // writeConcern is not allowed within a multi-statement transaction - if (target.writeConcern) { - delete target.writeConcern; - } +NativeCollection.prototype.onOpen = function() { + const _this = this; - return target; - } + _this.collection = _this.conn.db.collection(_this.name); + MongooseCollection.prototype.onOpen.call(_this); + return _this.collection; +}; - const writeConcern = WriteConcern.fromOptions(options); - if (writeConcern) { - return Object.assign(target, { writeConcern }); - } +/** + * Called when the connection closes + * + * @api private + */ - if (coll && coll.writeConcern) { - return Object.assign(target, { - writeConcern: Object.assign({}, coll.writeConcern), - }); - } +NativeCollection.prototype.onClose = function(force) { + MongooseCollection.prototype.onClose.call(this, force); +}; - if (db && db.writeConcern) { - return Object.assign(target, { - writeConcern: Object.assign({}, db.writeConcern), - }); - } +/*! + * ignore + */ - return target; - } +const syncCollectionMethods = { watch: true, find: true, aggregate: true }; - /** - * 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"; +/*! + * Copy the collection methods and make them subject to queues + */ + +function iter(i) { + NativeCollection.prototype[i] = function() { + const collection = this.collection; + const args = Array.from(arguments); + const _this = this; + const debug = get(_this, 'conn.base.options.debug'); + const lastArg = arguments[arguments.length - 1]; + const opId = new ObjectId(); + + // If user force closed, queueing will hang forever. See #5664 + if (this.conn.$wasForceClosed) { + const error = new MongooseError('Connection was force closed'); + if (args.length > 0 && + typeof args[args.length - 1] === 'function') { + args[args.length - 1](error); + return; + } else { + throw error; } + } - /** - * 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; + let _args = args; + let callback = null; + if (this._shouldBufferCommands() && this.buffer) { + if (syncCollectionMethods[i] && typeof lastArg !== 'function') { + throw new Error('Collection method ' + i + ' is synchronous'); + } - if (!topology) { - throw new TypeError('parameter "target" is missing a topology'); - } + this.conn.emit('buffer', { + _id: opId, + modelName: _this.modelName, + collectionName: _this.name, + method: i, + args: args + }); - 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`); + let callback; + let _args = args; + let promise = null; + let timeout = null; + if (syncCollectionMethods[i]) { + this.addQueue(() => { + lastArg.call(this, null, this[i].apply(this, _args.slice(0, _args.length - 1))); + }, []); + } else if (typeof lastArg === 'function') { + callback = function collectionOperationCallback() { + if (timeout != null) { + clearTimeout(timeout); } - } + return lastArg.apply(this, arguments); + }; + _args = args.slice(0, args.length - 1).concat([callback]); + } else { + promise = new this.Promise((resolve, reject) => { + callback = function collectionOperationCallback(err, res) { + if (timeout != null) { + clearTimeout(timeout); + } + if (err != null) { + return reject(err); + } + resolve(res); + }; + _args = args.concat([callback]); + this.addQueue(i, _args); + }); } - /** - * 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); + const bufferTimeoutMS = this._getBufferTimeoutMS(); + timeout = setTimeout(() => { + const removed = this.removeQueue(i, _args); + if (removed) { + const message = 'Operation `' + this.name + '.' + i + '()` buffering timed out after ' + + bufferTimeoutMS + 'ms'; + const err = new MongooseError(message); + this.conn.emit('buffer-end', { _id: opId, modelName: _this.modelName, collectionName: _this.name, method: i, error: err }); + callback(err); } + }, bufferTimeoutMS); - if (Object.keys(readConcern).length > 0) { - Object.assign(command, { readConcern: readConcern }); - } + if (!syncCollectionMethods[i] && typeof lastArg === 'function') { + this.addQueue(i, _args); + return; } - /** - * Applies an explain to a given command. - * @internal - * - * @param {object} command - the command on which to apply the explain - * @param {Explain} explain - the options containing the explain verbosity - * @return the new command - */ - function decorateWithExplain(command, explain) { - if (command.explain) { - return command; + return promise; + } else if (!syncCollectionMethods[i] && typeof lastArg === 'function') { + callback = function collectionOperationCallback(err, res) { + if (err != null) { + _this.conn.emit('operation-end', { _id: opId, modelName: _this.modelName, collectionName: _this.name, method: i, error: err }); + } else { + _this.conn.emit('operation-end', { _id: opId, modelName: _this.modelName, collectionName: _this.name, method: i, result: res }); } + return lastArg.apply(this, arguments); + }; + _args = args.slice(0, args.length - 1).concat([callback]); + } - return { explain: command, verbosity: explain.verbosity }; + if (debug) { + if (typeof debug === 'function') { + debug.apply(_this, + [_this.name, i].concat(sliced(args, 0, args.length - 1))); + } else if (debug instanceof stream.Writable) { + this.$printToStream(_this.name, i, args, debug); + } else { + const color = debug.color == null ? true : debug.color; + const shell = debug.shell == null ? false : debug.shell; + this.$print(_this.name, i, args, color, shell); } + } - const nodejsMajorVersion = +process.version.split(".")[0].substring(1); - const emitProcessWarning = (msg) => - nodejsMajorVersion <= 6 - ? process.emitWarning(msg, "DeprecationWarning", MONGODB_WARNING_CODE) - : process.emitWarning(msg, { - type: "DeprecationWarning", - code: MONGODB_WARNING_CODE, - }); - // eslint-disable-next-line no-console - 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); + this.conn.emit('operation-start', { _id: opId, modelName: _this.modelName, collectionName: this.name, method: i, params: _args }); + + try { + if (collection == null) { + const message = 'Cannot call `' + this.name + '.' + i + '()` before initial connection ' + + 'is complete if `bufferCommands = false`. Make sure you `await mongoose.connect()` if ' + + 'you have `bufferCommands = false`.'; + throw new MongooseError(message); + } + + if (syncCollectionMethods[i] && typeof lastArg === 'function') { + return lastArg.call(this, null, collection[i].apply(collection, _args.slice(0, _args.length - 1))); + } + + const ret = collection[i].apply(collection, _args); + if (ret != null && typeof ret.then === 'function') { + return ret.then( + res => { + this.conn.emit('operation-end', { _id: opId, modelName: this.modelName, collectionName: this.name, method: i, result: res }); + return res; + }, + err => { + this.conn.emit('operation-end', { _id: opId, modelName: this.modelName, collectionName: this.name, method: i, error: err }); + throw err; } + ); + } + return ret; + } catch (error) { + // Collection operation may throw because of max bson size, catch it here + // See gh-3906 + if (typeof lastArg === 'function') { + return lastArg(error); + } else { + this.conn.emit('operation-end', { _id: opId, modelName: _this.modelName, collectionName: this.name, method: i, error: error }); - config.deprecatedOptions.forEach((deprecatedOption) => { - if ( - Object.prototype.hasOwnProperty.call(options, 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); - } - } - } - }); + throw error; + } + } + }; +} + +for (const key of Object.getOwnPropertyNames(Collection.prototype)) { + // Janky hack to work around gh-3005 until we can get rid of the mongoose + // collection abstraction + const descriptor = Object.getOwnPropertyDescriptor(Collection.prototype, key); + // Skip properties with getters because they may throw errors (gh-8528) + if (descriptor.get !== undefined) { + continue; + } + if (typeof Collection.prototype[key] !== 'function') { + continue; + } + + iter(key); +} + +/** + * Debug print helper + * + * @api public + * @method $print + */ + +NativeCollection.prototype.$print = function(name, i, args, color, shell) { + const moduleName = color ? '\x1B[0;36mMongoose:\x1B[0m ' : 'Mongoose: '; + const functionCall = [name, i].join('.'); + const _args = []; + for (let j = args.length - 1; j >= 0; --j) { + if (this.$format(args[j]) || _args.length) { + _args.unshift(this.$format(args[j], color, shell)); + } + } + const params = '(' + _args.join(', ') + ')'; - return fn.apply(this, arguments); - } + console.info(moduleName + functionCall + params); +}; - // 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; - } +/** + * Debug print helper + * + * @api public + * @method $print + */ - return deprecated; - } +NativeCollection.prototype.$printToStream = function(name, i, args, stream) { + const functionCall = [name, i].join('.'); + const _args = []; + for (let j = args.length - 1; j >= 0; --j) { + if (this.$format(args[j]) || _args.length) { + _args.unshift(this.$format(args[j])); + } + } + const params = '(' + _args.join(', ') + ')'; - const SUPPORTS = {}; - // Test asyncIterator support - try { - __nccwpck_require__(1749); - SUPPORTS.ASYNC_ITERATOR = true; - } catch (e) { - SUPPORTS.ASYNC_ITERATOR = false; - } + stream.write(functionCall + params, 'utf8'); +}; - class MongoDBNamespace { - constructor(db, collection) { - this.db = db; - this.collection = collection; - } +/** + * Formatter for debug print args + * + * @api public + * @method $format + */ - toString() { - return this.collection ? `${this.db}.${this.collection}` : this.db; - } +NativeCollection.prototype.$format = function(arg, color, shell) { + const type = typeof arg; + if (type === 'function' || type === 'undefined') return ''; + return format(arg, false, color, shell); +}; - withCollection(collection) { - return new MongoDBNamespace(this.db, collection); - } +/*! + * Debug print helper + */ - static fromString(namespace) { - if (!namespace) { - throw new Error(`Cannot parse namespace from "${namespace}"`); - } +function inspectable(representation) { + const ret = { + inspect: function() { return representation; } + }; + if (util.inspect.custom) { + ret[util.inspect.custom] = ret.inspect; + } + return ret; +} +function map(o) { + return format(o, true); +} +function formatObjectId(x, key) { + x[key] = inspectable('ObjectId("' + x[key].toHexString() + '")'); +} +function formatDate(x, key, shell) { + if (shell) { + x[key] = inspectable('ISODate("' + x[key].toUTCString() + '")'); + } else { + x[key] = inspectable('new Date("' + x[key].toUTCString() + '")'); + } +} +function format(obj, sub, color, shell) { + if (obj && typeof obj.toBSON === 'function') { + obj = obj.toBSON(); + } + if (obj == null) { + return obj; + } - const index = namespace.indexOf("."); - return new MongoDBNamespace( - namespace.substring(0, index), - namespace.substring(index + 1) - ); + const clone = __nccwpck_require__(5092); + let x = clone(obj, { transform: false }); + const constructorName = getConstructorName(x); + + if (constructorName === 'Binary') { + x = 'BinData(' + x.sub_type + ', "' + x.toString('base64') + '")'; + } else if (constructorName === 'ObjectID') { + x = inspectable('ObjectId("' + x.toHexString() + '")'); + } else if (constructorName === 'Date') { + x = inspectable('new Date("' + x.toUTCString() + '")'); + } else if (constructorName === 'Object') { + const keys = Object.keys(x); + const numKeys = keys.length; + let key; + for (let i = 0; i < numKeys; ++i) { + key = keys[i]; + if (x[key]) { + let error; + if (typeof x[key].toBSON === 'function') { + try { + // `session.toBSON()` throws an error. This means we throw errors + // in debug mode when using transactions, see gh-6712. As a + // workaround, catch `toBSON()` errors, try to serialize without + // `toBSON()`, and rethrow if serialization still fails. + x[key] = x[key].toBSON(); + } catch (_error) { + error = _error; + } + } + const _constructorName = getConstructorName(x[key]); + if (_constructorName === 'Binary') { + x[key] = 'BinData(' + x[key].sub_type + ', "' + + x[key].buffer.toString('base64') + '")'; + } else if (_constructorName === 'Object') { + x[key] = format(x[key], true); + } else if (_constructorName === 'ObjectID') { + formatObjectId(x, key); + } else if (_constructorName === 'Date') { + formatDate(x, key, shell); + } else if (_constructorName === 'ClientSession') { + x[key] = inspectable('ClientSession("' + + get(x[key], 'id.id.buffer', '').toString('hex') + '")'); + } else if (Array.isArray(x[key])) { + x[key] = x[key].map(map); + } else if (error != null) { + // If there was an error with `toBSON()` and the object wasn't + // already converted to a string representation, rethrow it. + // Open to better ideas on how to handle this. + throw error; } } + } + } + if (sub) { + return x; + } - 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); - }; - }); - } + return util. + inspect(x, false, 10, color). + replace(/\n/g, ''). + replace(/\s{2,}/g, ' '); +} - fn(function (err, res) { - if (err != null) { - try { - callback(err); - } catch (error) { - return process.nextTick(() => { - throw error; - }); - } - return; - } +/** + * Retrieves information about this collections indexes. + * + * @param {Function} callback + * @method getIndexes + * @api public + */ - callback(err, res); - }); +NativeCollection.prototype.getIndexes = NativeCollection.prototype.indexInformation; - return result; - } +/*! + * Module exports. + */ - function now() { - const hrtime = process.hrtime(); - return Math.floor(hrtime[0] * 1000 + hrtime[1] / 1000000); - } +module.exports = NativeCollection; - 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; +/***/ 4766: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - options = options || {}; - const interval = options.interval || 1000; - const minInterval = options.minInterval || 500; - const immediate = - typeof options.immediate === "boolean" ? options.immediate : false; - const clock = typeof options.clock === "function" ? options.clock : now; - - function wake() { - const currentTime = clock(); - const timeSinceLastWake = currentTime - lastWakeTime; - const timeSinceLastCall = currentTime - lastCallTime; - const timeUntilNextCall = interval - timeSinceLastCall; - 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; - } +"use strict"; +/*! + * Module dependencies. + */ - // reschedule a call as soon as possible, ensuring the call never happens - // faster than the `minInterval` - if (timeUntilNextCall > minInterval) { - reschedule(minInterval); - } - // This is possible in virtualized environments like AWS Lambda where our - // clock is unreliable. In these cases the timer is "running" but never - // actually completes, so we want to execute immediately and then attempt - // to reschedule. - if (timeUntilNextCall < 0) { - executeAndReschedule(); - } - } - function stop() { - stopped = true; - if (timerId) { - clearTimeout(timerId); - timerId = null; - } +const MongooseConnection = __nccwpck_require__(370); +const STATES = __nccwpck_require__(932); +const immediate = __nccwpck_require__(4830); +const setTimeout = __nccwpck_require__(82)/* .setTimeout */ .i; - lastCallTime = 0; - lastWakeTime = 0; - } +/** + * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation. + * + * @inherits Connection + * @api private + */ - function reschedule(ms) { - if (stopped) return; - clearTimeout(timerId); - timerId = setTimeout(executeAndReschedule, ms || interval); - } +function NativeConnection() { + MongooseConnection.apply(this, arguments); + this._listening = false; +} - function executeAndReschedule() { - lastWakeTime = 0; - lastCallTime = clock(); +/** + * Expose the possible connection states. + * @api public + */ - fn((err) => { - if (err) throw err; - reschedule(interval); - }); - } +NativeConnection.STATES = STATES; - if (immediate) { - executeAndReschedule(); - } else { - lastCallTime = clock(); - reschedule(); - } +/*! + * Inherits from Connection. + */ - return { wake, stop }; - } +NativeConnection.prototype.__proto__ = MongooseConnection.prototype; - function hasAtomicOperators(doc) { - if (Array.isArray(doc)) { - return doc.reduce((err, u) => err || hasAtomicOperators(u), null); - } +/** + * Switches to a different database using the same connection pool. + * + * Returns a new connection object, with the new db. If you set the `useCache` + * option, `useDb()` will cache connections by `name`. + * + * **Note:** Calling `close()` on a `useDb()` connection will close the base connection as well. + * + * @param {String} name The database name + * @param {Object} [options] + * @param {Boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object. + * @param {Boolean} [options.noListener=false] If true, the new connection object won't listen to any events on the base connection. This is better for memory usage in cases where you're calling `useDb()` for every request. + * @return {Connection} New Connection Object + * @api public + */ - return ( - Object.keys(typeof doc.toBSON !== "function" ? doc : doc.toBSON()) - .map((k) => k[0]) - .indexOf("$") >= 0 - ); - } +NativeConnection.prototype.useDb = function(name, options) { + // Return immediately if cached + options = options || {}; + if (options.useCache && this.relatedDbs[name]) { + return this.relatedDbs[name]; + } - /** - * When the driver used emitWarning the code will be equal to this. - * @public - * - * @example - * ```js - * process.on('warning', (warning) => { - * if (warning.code === MONGODB_WARNING_CODE) console.error('Ah an important warning! :)') - * }) - * ``` - */ - const MONGODB_WARNING_CODE = "MONGODB DRIVER"; - - /** - * @internal - * @param {string} message - message to warn about - */ - function emitWarning(message) { - if (process.emitWarning) { - return nodejsMajorVersion <= 6 - ? process.emitWarning(message, undefined, MONGODB_WARNING_CODE) - : process.emitWarning(message, { code: MONGODB_WARNING_CODE }); - } else { - // Approximate the style of print out on node versions pre 8.x - // eslint-disable-next-line no-console - return console.error(`[${MONGODB_WARNING_CODE}] Warning:`, message); - } - } + // we have to manually copy all of the attributes... + const newConn = new this.constructor(); + newConn.name = name; + newConn.base = this.base; + newConn.collections = {}; + newConn.models = {}; + newConn.replica = this.replica; + newConn.config = Object.assign({}, this.config, newConn.config); + newConn.name = this.name; + newConn.options = this.options; + newConn._readyState = this._readyState; + newConn._closeCalled = this._closeCalled; + newConn._hasOpened = this._hasOpened; + newConn._listening = false; + newConn._parent = this; + + newConn.host = this.host; + newConn.port = this.port; + newConn.user = this.user; + newConn.pass = this.pass; + + // First, when we create another db object, we are not guaranteed to have a + // db object to work with. So, in the case where we have a db object and it + // is connected, we can just proceed with setting everything up. However, if + // we do not have a db or the state is not connected, then we need to wait on + // the 'open' event of the connection before doing the rest of the setup + // the 'connected' event is the first time we'll have access to the db object + + const _this = this; + + newConn.client = _this.client; + + if (this.db && this._readyState === STATES.connected) { + wireup(); + } else { + this.once('connected', wireup); + } - const emittedWarnings = new Set(); - /** - * Will emit a warning once for the duration of the application. - * Uses the message to identify if it has already been emitted - * so using string interpolation can cause multiple emits - * @internal - * @param {string} message - message to warn about - */ - function emitWarningOnce(message) { - if (!emittedWarnings.has(message)) { - emittedWarnings.add(message); - return emitWarning(message); - } - } + function wireup() { + newConn.client = _this.client; + const _opts = {}; + if (options.hasOwnProperty('noListener')) { + _opts.noListener = options.noListener; + } + newConn.db = _this.client.db(name, _opts); + newConn.onOpen(); + } - function isSuperset(set, subset) { - set = Array.isArray(set) ? new Set(set) : set; - subset = Array.isArray(subset) ? new Set(subset) : subset; - for (const elem of subset) { - if (!set.has(elem)) { - return false; - } - } - return true; - } + newConn.name = name; - function isRecord(value, requiredKeys) { - const toString = Object.prototype.toString; - const hasOwnProperty = Object.prototype.hasOwnProperty; - const isObject = (v) => toString.call(v) === "[object Object]"; - if (!isObject(value)) { - return false; - } + // push onto the otherDbs stack, this is used when state changes + if (options.noListener !== true) { + this.otherDbs.push(newConn); + } + newConn.otherDbs.push(this); - const ctor = value.constructor; - if (ctor && ctor.prototype) { - if (!isObject(ctor.prototype)) { - return false; - } + // push onto the relatedDbs cache, this is used when state changes + if (options && options.useCache) { + this.relatedDbs[newConn.name] = newConn; + newConn.relatedDbs = this.relatedDbs; + } - // Check to see if some method exists from the Object exists - if (!hasOwnProperty.call(ctor.prototype, "isPrototypeOf")) { - return false; - } - } + return newConn; +}; - if (requiredKeys) { - const keys = Object.keys(value); - return isSuperset(keys, requiredKeys); - } +/** + * Closes the connection + * + * @param {Boolean} [force] + * @param {Function} [fn] + * @return {Connection} this + * @api private + */ - return true; - } +NativeConnection.prototype.doClose = function(force, fn) { + if (this.client == null) { + immediate(() => fn()); + return this; + } - /** - * Make a deep copy of an object - * - * NOTE: This is not meant to be the perfect implementation of a deep copy, - * but instead something that is good enough for the purposes of - * command monitoring. - */ - function deepCopy(value) { - if (value == null) { - return value; - } else if (Array.isArray(value)) { - return value.map((item) => deepCopy(item)); - } else if (isRecord(value)) { - const res = {}; - for (const key in value) { - res[key] = deepCopy(value[key]); - } - return res; - } - - const ctor = value.constructor; - if (ctor) { - switch (ctor.name.toLowerCase()) { - case "date": - return new ctor(Number(value)); - case "map": - return new Map(value); - case "set": - return new Set(value); - case "buffer": - return Buffer.from(value); - } - } + this.client.close(force, (err, res) => { + // Defer because the driver will wait at least 1ms before finishing closing + // the pool, see https://github.com/mongodb-js/mongodb-core/blob/a8f8e4ce41936babc3b9112bf42d609779f03b39/lib/connection/pool.js#L1026-L1030. + // If there's queued operations, you may still get some background work + // after the callback is called. + setTimeout(() => fn(err, res), 1); + }); + return this; +}; - return value; - } - module.exports = { - filterOptions, - mergeOptions, - translateOptions, - shallowClone, - getSingleProperty, - checkCollectionName, - toError, - formattedOrderClause, - parseIndexOptions, - normalizeHintField, - handleCallback, - decorateCommand, - isObject, - debugOptions, - MAX_JS_INT: Number.MAX_SAFE_INTEGER + 1, - conditionallyMergeWriteConcern, - executeLegacyOperation, - applyRetryableWrites, - applyWriteConcern, - isPromiseLike, - decorateWithCollation, - decorateWithReadConcern, - decorateWithExplain, - deprecateOptions, - SUPPORTS, - MongoDBNamespace, - emitDeprecationWarning, - makeCounter, - maybePromise, - now, - calculateDurationInMs, - makeInterruptableAsyncInterval, - hasAtomicOperators, - MONGODB_WARNING_CODE, - emitWarning, - emitWarningOnce, - deepCopy, - }; +/*! + * Module exports. + */ - /***/ - }, +module.exports = NativeConnection; - /***/ 2481: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const kWriteConcernKeys = new Set([ - "w", - "wtimeout", - "j", - "journal", - "fsync", - ]); - let utils; - - /** - * 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. - * @param {(number|string)} [options.w] **Deprecated** Use `options.writeConcern` instead - * @param {number} [options.wtimeout] **Deprecated** Use `options.writeConcern` instead - * @param {boolean} [options.j] **Deprecated** Use `options.writeConcern` instead - * @param {boolean} [options.fsync] **Deprecated** Use `options.writeConcern` instead - * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings. - * @return {WriteConcern} - */ - static fromOptions(options) { - if ( - options == null || - (options.writeConcern == null && - options.w == null && - options.wtimeout == null && - options.j == null && - options.journal == null && - options.fsync == null) - ) { - return; - } +/***/ }), - if (options.writeConcern) { - if (typeof options.writeConcern === "string") { - return new WriteConcern(options.writeConcern); - } +/***/ 5869: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ( - !Object.keys(options.writeConcern).some((key) => - kWriteConcernKeys.has(key) - ) - ) { - return; - } +"use strict"; +/*! + * ignore + */ - return new WriteConcern( - options.writeConcern.w, - options.writeConcern.wtimeout, - options.writeConcern.j || options.writeConcern.journal, - options.writeConcern.fsync - ); - } - // this is down here to prevent circular dependency - if (!utils) utils = __nccwpck_require__(1371); - utils.emitWarningOnce( - `Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead.` - ); - return new WriteConcern( - options.w, - options.wtimeout, - options.j || options.journal, - options.fsync - ); - } - } +module.exports = __nccwpck_require__(8821).Decimal128; - module.exports = WriteConcern; - /***/ - }, +/***/ }), - /***/ 7539: /***/ (module, exports) => { - module.exports = pluralize; - - /** - * Pluralization rules. - * - * These rules are applied while processing the argument to `toCollectionName`. - * - * @deprecated remove in 4.x gh-1350 - */ - - exports.pluralization = [ - [/(m)an$/gi, "$1en"], - [/(pe)rson$/gi, "$1ople"], - [/(child)$/gi, "$1ren"], - [/^(ox)$/gi, "$1en"], - [/(ax|test)is$/gi, "$1es"], - [/(octop|vir)us$/gi, "$1i"], - [/(alias|status)$/gi, "$1es"], - [/(bu)s$/gi, "$1ses"], - [/(buffal|tomat|potat)o$/gi, "$1oes"], - [/([ti])um$/gi, "$1a"], - [/sis$/gi, "ses"], - [/(?:([^f])fe|([lr])f)$/gi, "$1$2ves"], - [/(hive)$/gi, "$1s"], - [/([^aeiouy]|qu)y$/gi, "$1ies"], - [/(x|ch|ss|sh)$/gi, "$1es"], - [/(matr|vert|ind)ix|ex$/gi, "$1ices"], - [/([m|l])ouse$/gi, "$1ice"], - [/(kn|w|l)ife$/gi, "$1ives"], - [/(quiz)$/gi, "$1zes"], - [/s$/gi, "s"], - [/([^a-z])$/, "$1"], - [/$/gi, "s"], - ]; - var rules = exports.pluralization; - - /** - * Uncountable words. - * - * These words are applied while processing the argument to `toCollectionName`. - * @api public - */ - - exports.uncountables = [ - "advice", - "energy", - "excretion", - "digestion", - "cooperation", - "health", - "justice", - "labour", - "machinery", - "equipment", - "information", - "pollution", - "sewage", - "paper", - "money", - "species", - "series", - "rain", - "rice", - "fish", - "sheep", - "moose", - "deer", - "news", - "expertise", - "status", - "media", - ]; - var uncountables = exports.uncountables; - - /*! - * Pluralize function. - * - * @author TJ Holowaychuk (extracted from _ext.js_) - * @param {String} string to pluralize - * @api private - */ - - function pluralize(str) { - var found; - str = str.toLowerCase(); - if (!~uncountables.indexOf(str)) { - found = rules.filter(function (rule) { - return str.match(rule[0]); - }); - if (found[0]) { - return str.replace(found[0][0], found[0][1]); - } - } - return str; - } +/***/ 2676: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /***/ - }, +"use strict"; +/*! + * Module exports. + */ - /***/ 4740: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /** - * Export lib/mongoose - * - */ - module.exports = __nccwpck_require__(1028); +exports.Binary = __nccwpck_require__(4473); +exports.Collection = __nccwpck_require__(449); +exports.Decimal128 = __nccwpck_require__(5869); +exports.ObjectId = __nccwpck_require__(3589); +exports.ReadPreference = __nccwpck_require__(8001); +exports.getConnection = () => __nccwpck_require__(4766); - /***/ - }, +/***/ }), - /***/ 4336: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies - */ - - const AggregationCursor = __nccwpck_require__(5398); - const Query = __nccwpck_require__(1615); - const applyGlobalMaxTimeMS = __nccwpck_require__(7428); - const getConstructorName = __nccwpck_require__(7323); - const promiseOrCallback = __nccwpck_require__(4046); - const stringifyFunctionOperators = __nccwpck_require__(6819); - const util = __nccwpck_require__(1669); - const utils = __nccwpck_require__(9232); - const read = Query.prototype.read; - const readConcern = Query.prototype.readConcern; - - /** - * Aggregate constructor used for building aggregation pipelines. Do not - * instantiate this class directly, use [Model.aggregate()](/docs/api.html#model_Model.aggregate) instead. - * - * ####Example: - * - * const aggregate = Model.aggregate([ - * { $project: { a: 1, b: 1 } }, - * { $skip: 5 } - * ]); - * - * Model. - * aggregate([{ $match: { age: { $gte: 21 }}}]). - * unwind('tags'). - * exec(callback); - * - * ####Note: - * - * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). - * - Mongoose does **not** cast pipeline stages. The below will **not** work unless `_id` is a string in the database - * - * ```javascript - * new Aggregate([{ $match: { _id: '00000000000000000000000a' } }]); - * // Do this instead to cast to an ObjectId - * new Aggregate([{ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } }]); - * ``` - * - * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ - * @see driver http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#aggregate - * @param {Array} [pipeline] aggregation pipeline as an array of objects - * @api public - */ - - function Aggregate(pipeline) { - this._pipeline = []; - this._model = undefined; - this.options = {}; +/***/ 3589: +/***/ ((module, exports, __nccwpck_require__) => { - if (arguments.length === 1 && util.isArray(pipeline)) { - this.append.apply(this, pipeline); - } - } - - /** - * Contains options passed down to the [aggregate command](https://docs.mongodb.com/manual/reference/command/aggregate/). - * Supported options are: - * - * - `readPreference` - * - [`cursor`](./api.html#aggregate_Aggregate-cursor) - * - [`explain`](./api.html#aggregate_Aggregate-explain) - * - [`allowDiskUse`](./api.html#aggregate_Aggregate-allowDiskUse) - * - `maxTimeMS` - * - `bypassDocumentValidation` - * - `raw` - * - `promoteLongs` - * - `promoteValues` - * - `promoteBuffers` - * - [`collation`](./api.html#aggregate_Aggregate-collation) - * - `comment` - * - [`session`](./api.html#aggregate_Aggregate-session) - * - * @property options - * @memberOf Aggregate - * @api public - */ - - Aggregate.prototype.options; - - /** - * Get/set the model that this aggregation will execute on. - * - * ####Example: - * const aggregate = MyModel.aggregate([{ $match: { answer: 42 } }]); - * aggregate.model() === MyModel; // true - * - * // Change the model. There's rarely any reason to do this. - * aggregate.model(SomeOtherModel); - * aggregate.model() === SomeOtherModel; // true - * - * @param {Model} [model] the model to which the aggregate is to be bound - * @return {Aggregate|Model} if model is passed, will return `this`, otherwise will return the model - * @api public - */ - - Aggregate.prototype.model = function (model) { - if (arguments.length === 0) { - return this._model; - } - - this._model = model; - if (model.schema != null) { - if ( - this.options.readPreference == null && - model.schema.options.read != null - ) { - this.options.readPreference = model.schema.options.read; - } - if ( - this.options.collation == null && - model.schema.options.collation != null - ) { - this.options.collation = model.schema.options.collation; - } - } - return this; - }; +"use strict"; - /** - * Appends new operators to this aggregate pipeline - * - * ####Examples: - * - * aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); - * - * // or pass an array - * const pipeline = [{ $match: { daw: 'Logic Audio X' }} ]; - * aggregate.append(pipeline); - * - * @param {Object} ops operator(s) to append - * @return {Aggregate} - * @api public - */ - - Aggregate.prototype.append = function () { - const args = - arguments.length === 1 && util.isArray(arguments[0]) - ? arguments[0] - : utils.args(arguments); - - if (!args.every(isOperator)) { - throw new Error("Arguments must be aggregate pipeline operators"); - } - - this._pipeline = this._pipeline.concat(args); +/*! + * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId + * @constructor NodeMongoDbObjectId + * @see ObjectId + */ - return this; - }; - /** - * Appends a new $addFields operator to this aggregate pipeline. - * Requires MongoDB v3.4+ to work - * - * ####Examples: - * - * // adding new fields based on existing fields - * aggregate.addFields({ - * newField: '$b.nested' - * , plusTen: { $add: ['$val', 10]} - * , sub: { - * name: '$a' - * } - * }) - * - * // etc - * aggregate.addFields({ salary_k: { $divide: [ "$salary", 1000 ] } }); - * - * @param {Object} arg field specification - * @see $addFields https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/ - * @return {Aggregate} - * @api public - */ - Aggregate.prototype.addFields = function (arg) { - const fields = {}; - if (typeof arg === "object" && !util.isArray(arg)) { - Object.keys(arg).forEach(function (field) { - fields[field] = arg[field]; - }); - } else { - throw new Error("Invalid addFields() argument. Must be an object"); - } - return this.append({ $addFields: fields }); - }; - /** - * Appends a new $project operator to this aggregate pipeline. - * - * Mongoose query [selection syntax](#query_Query-select) is also supported. - * - * ####Examples: - * - * // include a, include b, exclude _id - * aggregate.project("a b -_id"); - * - * // or you may use object notation, useful when - * // you have keys already prefixed with a "-" - * aggregate.project({a: 1, b: 1, _id: 0}); - * - * // reshaping documents - * aggregate.project({ - * newField: '$b.nested' - * , plusTen: { $add: ['$val', 10]} - * , sub: { - * name: '$a' - * } - * }) - * - * // etc - * aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } }); - * - * @param {Object|String} arg field specification - * @see projection http://docs.mongodb.org/manual/reference/aggregation/project/ - * @return {Aggregate} - * @api public - */ - - Aggregate.prototype.project = function (arg) { - const fields = {}; - - if (typeof arg === "object" && !util.isArray(arg)) { - Object.keys(arg).forEach(function (field) { - fields[field] = arg[field]; - }); - } else if (arguments.length === 1 && typeof arg === "string") { - arg.split(/\s+/).forEach(function (field) { - if (!field) { - return; - } - const include = field[0] === "-" ? 0 : 1; - if (include === 0) { - field = field.substring(1); - } - fields[field] = include; - }); - } else { - throw new Error( - "Invalid project() argument. Must be string or object" - ); - } +const ObjectId = __nccwpck_require__(8821).ObjectId; - return this.append({ $project: fields }); - }; +/*! + * ignore + */ - /** - * Appends a new custom $group operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.group({ _id: "$department" }); - * - * @see $group http://docs.mongodb.org/manual/reference/aggregation/group/ - * @method group - * @memberOf Aggregate - * @instance - * @param {Object} arg $group operator contents - * @return {Aggregate} - * @api public - */ - - /** - * Appends a new custom $match operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.match({ department: { $in: [ "sales", "engineering" ] } }); - * - * @see $match http://docs.mongodb.org/manual/reference/aggregation/match/ - * @method match - * @memberOf Aggregate - * @instance - * @param {Object} arg $match operator contents - * @return {Aggregate} - * @api public - */ - - /** - * Appends a new $skip operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.skip(10); - * - * @see $skip http://docs.mongodb.org/manual/reference/aggregation/skip/ - * @method skip - * @memberOf Aggregate - * @instance - * @param {Number} num number of records to skip before next stage - * @return {Aggregate} - * @api public - */ - - /** - * Appends a new $limit operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.limit(10); - * - * @see $limit http://docs.mongodb.org/manual/reference/aggregation/limit/ - * @method limit - * @memberOf Aggregate - * @instance - * @param {Number} num maximum number of records to pass to the next stage - * @return {Aggregate} - * @api public - */ - - /** - * Appends a new $geoNear operator to this aggregate pipeline. - * - * ####NOTE: - * - * **MUST** be used as the first operator in the pipeline. - * - * ####Examples: - * - * aggregate.near({ - * near: [40.724, -73.997], - * distanceField: "dist.calculated", // required - * maxDistance: 0.008, - * query: { type: "public" }, - * includeLocs: "dist.location", - * uniqueDocs: true, - * num: 5 - * }); - * - * @see $geoNear http://docs.mongodb.org/manual/reference/aggregation/geoNear/ - * @method near - * @memberOf Aggregate - * @instance - * @param {Object} arg - * @return {Aggregate} - * @api public - */ - - Aggregate.prototype.near = function (arg) { - const op = {}; - op.$geoNear = arg; - return this.append(op); - }; +module.exports = exports = ObjectId; - /*! - * define methods - */ - "group match skip limit out".split(" ").forEach(function ($operator) { - Aggregate.prototype[$operator] = function (arg) { - const op = {}; - op["$" + $operator] = arg; - return this.append(op); - }; - }); +/***/ }), - /** - * Appends new custom $unwind operator(s) to this aggregate pipeline. - * - * Note that the `$unwind` operator requires the path name to start with '$'. - * Mongoose will prepend '$' if the specified field doesn't start '$'. - * - * ####Examples: - * - * aggregate.unwind("tags"); - * aggregate.unwind("a", "b", "c"); - * aggregate.unwind({ path: '$tags', preserveNullAndEmptyArrays: true }); - * - * @see $unwind http://docs.mongodb.org/manual/reference/aggregation/unwind/ - * @param {String|Object} fields the field(s) to unwind, either as field names or as [objects with options](https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/#document-operand-with-options). If passing a string, prefixing the field name with '$' is optional. If passing an object, `path` must start with '$'. - * @return {Aggregate} - * @api public - */ - - Aggregate.prototype.unwind = function () { - const args = utils.args(arguments); - - const res = []; - for (const arg of args) { - if (arg && typeof arg === "object") { - res.push({ $unwind: arg }); - } else if (typeof arg === "string") { - res.push({ - $unwind: arg && arg.startsWith("$") ? arg : "$" + arg, - }); - } else { - throw new Error( - 'Invalid arg "' + - arg + - '" to unwind(), ' + - "must be string or object" - ); - } - } +/***/ 2798: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return this.append.apply(this, res); - }; +"use strict"; - /** - * Appends a new $replaceRoot operator to this aggregate pipeline. - * - * Note that the `$replaceRoot` operator requires field strings to start with '$'. - * If you are passing in a string Mongoose will prepend '$' if the specified field doesn't start '$'. - * If you are passing in an object the strings in your expression will not be altered. - * - * ####Examples: - * - * aggregate.replaceRoot("user"); - * - * aggregate.replaceRoot({ x: { $concat: ['$this', '$that'] } }); - * - * @see $replaceRoot https://docs.mongodb.org/manual/reference/operator/aggregation/replaceRoot - * @param {String|Object} the field or document which will become the new root document - * @return {Aggregate} - * @api public - */ - - Aggregate.prototype.replaceRoot = function (newRoot) { - let ret; - - if (typeof newRoot === "string") { - ret = newRoot.startsWith("$") ? newRoot : "$" + newRoot; - } else { - ret = newRoot; - } - return this.append({ - $replaceRoot: { - newRoot: ret, - }, - }); - }; +/*! + * Module dependencies. + */ - /** - * Appends a new $count operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.count("userCount"); - * - * @see $count https://docs.mongodb.org/manual/reference/operator/aggregation/count - * @param {String} the name of the count field - * @return {Aggregate} - * @api public - */ - - Aggregate.prototype.count = function (countName) { - return this.append({ $count: countName }); - }; +const MongooseError = __nccwpck_require__(5953); +const get = __nccwpck_require__(8730); +const util = __nccwpck_require__(1669); - /** - * Appends a new $sortByCount operator to this aggregate pipeline. Accepts either a string field name - * or a pipeline object. - * - * Note that the `$sortByCount` operator requires the new root to start with '$'. - * Mongoose will prepend '$' if the specified field name doesn't start with '$'. - * - * ####Examples: - * - * aggregate.sortByCount('users'); - * aggregate.sortByCount({ $mergeObjects: [ "$employee", "$business" ] }) - * - * @see $sortByCount https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/ - * @param {Object|String} arg - * @return {Aggregate} this - * @api public - */ - - Aggregate.prototype.sortByCount = function (arg) { - if (arg && typeof arg === "object") { - return this.append({ $sortByCount: arg }); - } else if (typeof arg === "string") { - return this.append({ - $sortByCount: arg && arg.startsWith("$") ? arg : "$" + arg, - }); - } else { - throw new TypeError( - 'Invalid arg "' + - arg + - '" to sortByCount(), ' + - "must be string or object" - ); - } - }; +/** + * Casting Error constructor. + * + * @param {String} type + * @param {String} value + * @inherits MongooseError + * @api private + */ - /** - * Appends new custom $lookup operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' }); - * - * @see $lookup https://docs.mongodb.org/manual/reference/operator/aggregation/lookup/#pipe._S_lookup - * @param {Object} options to $lookup as described in the above link - * @return {Aggregate}* @api public - */ - - Aggregate.prototype.lookup = function (options) { - return this.append({ $lookup: options }); - }; +class CastError extends MongooseError { + constructor(type, value, path, reason, schemaType) { + // If no args, assume we'll `init()` later. + if (arguments.length > 0) { + const stringValue = getStringValue(value); + const valueType = getValueType(value); + const messageFormat = getMessageFormat(schemaType); + const msg = formatMessage(null, type, stringValue, path, messageFormat, valueType); + super(msg); + this.init(type, value, path, reason, schemaType); + } else { + super(formatMessage()); + } + } - /** - * Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection. - * - * Note that graphLookup can only consume at most 100MB of memory, and does not allow disk use even if `{ allowDiskUse: true }` is specified. - * - * #### Examples: - * // Suppose we have a collection of courses, where a document might look like `{ _id: 0, name: 'Calculus', prerequisite: 'Trigonometry'}` and `{ _id: 0, name: 'Trigonometry', prerequisite: 'Algebra' }` - * aggregate.graphLookup({ from: 'courses', startWith: '$prerequisite', connectFromField: 'prerequisite', connectToField: 'name', as: 'prerequisites', maxDepth: 3 }) // this will recursively search the 'courses' collection up to 3 prerequisites - * - * @see $graphLookup https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/#pipe._S_graphLookup - * @param {Object} options to $graphLookup as described in the above link - * @return {Aggregate} - * @api public - */ - - Aggregate.prototype.graphLookup = function (options) { - const cloneOptions = {}; - if (options) { - if (!utils.isObject(options)) { - throw new TypeError( - "Invalid graphLookup() argument. Must be an object." - ); - } + toJSON() { + return { + stringValue: this.stringValue, + valueType: this.valueType, + kind: this.kind, + value: this.value, + path: this.path, + reason: this.reason, + name: this.name, + message: this.message + }; + } + /*! + * ignore + */ + init(type, value, path, reason, schemaType) { + this.stringValue = getStringValue(value); + this.messageFormat = getMessageFormat(schemaType); + this.kind = type; + this.value = value; + this.path = path; + this.reason = reason; + this.valueType = getValueType(value); + } - utils.mergeClone(cloneOptions, options); - const startWith = cloneOptions.startWith; + /*! + * ignore + * @param {Readonly} other + */ + copy(other) { + this.messageFormat = other.messageFormat; + this.stringValue = other.stringValue; + this.kind = other.kind; + this.value = other.value; + this.path = other.path; + this.reason = other.reason; + this.message = other.message; + this.valueType = other.valueType; + } - if (startWith && typeof startWith === "string") { - cloneOptions.startWith = cloneOptions.startWith.startsWith("$") - ? cloneOptions.startWith - : "$" + cloneOptions.startWith; - } - } - return this.append({ $graphLookup: cloneOptions }); - }; + /*! + * ignore + */ + setModel(model) { + this.model = model; + this.message = formatMessage(model, this.kind, this.stringValue, this.path, + this.messageFormat, this.valueType); + } +} - /** - * Appends new custom $sample operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.sample(3); // Add a pipeline that picks 3 random documents - * - * @see $sample https://docs.mongodb.org/manual/reference/operator/aggregation/sample/#pipe._S_sample - * @param {Number} size number of random documents to pick - * @return {Aggregate} - * @api public - */ - - Aggregate.prototype.sample = function (size) { - return this.append({ $sample: { size: size } }); - }; +Object.defineProperty(CastError.prototype, 'name', { + value: 'CastError' +}); - /** - * Appends a new $sort operator to this aggregate pipeline. - * - * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. - * - * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. - * - * ####Examples: - * - * // these are equivalent - * aggregate.sort({ field: 'asc', test: -1 }); - * aggregate.sort('field -test'); - * - * @see $sort http://docs.mongodb.org/manual/reference/aggregation/sort/ - * @param {Object|String} arg - * @return {Aggregate} this - * @api public - */ - - Aggregate.prototype.sort = function (arg) { - // TODO refactor to reuse the query builder logic - - const sort = {}; - - if (getConstructorName(arg) === "Object") { - const desc = ["desc", "descending", -1]; - Object.keys(arg).forEach(function (field) { - // If sorting by text score, skip coercing into 1/-1 - if (arg[field] instanceof Object && arg[field].$meta) { - sort[field] = arg[field]; - return; - } - sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1; - }); - } else if (arguments.length === 1 && typeof arg === "string") { - arg.split(/\s+/).forEach(function (field) { - if (!field) { - return; - } - const ascend = field[0] === "-" ? -1 : 1; - if (ascend === -1) { - field = field.substring(1); - } - sort[field] = ascend; - }); - } else { - throw new TypeError( - "Invalid sort() argument. Must be a string or object." - ); - } +function getStringValue(value) { + let stringValue = util.inspect(value); + stringValue = stringValue.replace(/^'|'$/g, '"'); + if (!stringValue.startsWith('"')) { + stringValue = '"' + stringValue + '"'; + } + return stringValue; +} - return this.append({ $sort: sort }); - }; +function getValueType(value) { + if (value == null) { + return '' + value; + } - /** - * Sets the readPreference option for the aggregation query. - * - * ####Example: - * - * Model.aggregate(..).read('primaryPreferred').exec(callback) - * - * @param {String} pref one of the listed preference options or their aliases - * @param {Array} [tags] optional tags for this query - * @return {Aggregate} this - * @api public - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences - */ - - Aggregate.prototype.read = function (pref, tags) { - if (!this.options) { - this.options = {}; - } - read.call(this, pref, tags); - return this; - }; + const t = typeof value; + if (t !== 'object') { + return t; + } + if (typeof value.constructor !== 'function') { + return t; + } + return value.constructor.name; +} - /** - * Sets the readConcern level for the aggregation query. - * - * ####Example: - * - * Model.aggregate(..).readConcern('majority').exec(callback) - * - * @param {String} level one of the listed read concern level or their aliases - * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/ - * @return {Aggregate} this - * @api public - */ - - Aggregate.prototype.readConcern = function (level) { - if (!this.options) { - this.options = {}; - } - readConcern.call(this, level); - return this; - }; +function getMessageFormat(schemaType) { + const messageFormat = get(schemaType, 'options.cast', null); + if (typeof messageFormat === 'string') { + return messageFormat; + } +} - /** - * Appends a new $redact operator to this aggregate pipeline. - * - * If 3 arguments are supplied, Mongoose will wrap them with if-then-else of $cond operator respectively - * If `thenExpr` or `elseExpr` is string, make sure it starts with $$, like `$$DESCEND`, `$$PRUNE` or `$$KEEP`. - * - * ####Example: - * - * Model.aggregate(...) - * .redact({ - * $cond: { - * if: { $eq: [ '$level', 5 ] }, - * then: '$$PRUNE', - * else: '$$DESCEND' - * } - * }) - * .exec(); - * - * // $redact often comes with $cond operator, you can also use the following syntax provided by mongoose - * Model.aggregate(...) - * .redact({ $eq: [ '$level', 5 ] }, '$$PRUNE', '$$DESCEND') - * .exec(); - * - * @param {Object} expression redact options or conditional expression - * @param {String|Object} [thenExpr] true case for the condition - * @param {String|Object} [elseExpr] false case for the condition - * @return {Aggregate} this - * @see $redact https://docs.mongodb.com/manual/reference/operator/aggregation/redact/ - * @api public - */ - - Aggregate.prototype.redact = function (expression, thenExpr, elseExpr) { - if (arguments.length === 3) { - if ( - (typeof thenExpr === "string" && !thenExpr.startsWith("$$")) || - (typeof elseExpr === "string" && !elseExpr.startsWith("$$")) - ) { - throw new Error( - "If thenExpr or elseExpr is string, it must start with $$. e.g. $$DESCEND, $$PRUNE, $$KEEP" - ); - } +/*! + * ignore + */ - expression = { - $cond: { - if: expression, - then: thenExpr, - else: elseExpr, - }, - }; - } else if (arguments.length !== 1) { - throw new TypeError("Invalid arguments"); - } +function formatMessage(model, kind, stringValue, path, messageFormat, valueType) { + if (messageFormat != null) { + let ret = messageFormat. + replace('{KIND}', kind). + replace('{VALUE}', stringValue). + replace('{PATH}', path); + if (model != null) { + ret = ret.replace('{MODEL}', model.modelName); + } - return this.append({ $redact: expression }); - }; + return ret; + } else { + const valueTypeMsg = valueType ? ' (type ' + valueType + ')' : ''; + let ret = 'Cast to ' + kind + ' failed for value ' + + stringValue + valueTypeMsg + ' at path "' + path + '"'; + if (model != null) { + ret += ' for model "' + model.modelName + '"'; + } + return ret; + } +} - /** - * Execute the aggregation with explain - * - * ####Example: - * - * Model.aggregate(..).explain(callback) - * - * @param {Function} callback - * @return {Promise} - */ - - Aggregate.prototype.explain = function (callback) { - const model = this._model; - - return promiseOrCallback( - callback, - (cb) => { - if (!this._pipeline.length) { - const err = new Error("Aggregate has empty pipeline"); - return cb(err); - } - - prepareDiscriminatorPipeline(this); - - model.hooks.execPre("aggregate", this, (error) => { - if (error) { - const _opts = { error: error }; - return model.hooks.execPost( - "aggregate", - this, - [null], - _opts, - (error) => { - cb(error); - } - ); - } +/*! + * exports + */ - this.options.explain = true; - - model.collection - .aggregate(this._pipeline, this.options || {}) - .explain((error, result) => { - const _opts = { error: error }; - return model.hooks.execPost( - "aggregate", - this, - [result], - _opts, - (error) => { - if (error) { - return cb(error); - } - return cb(null, result); - } - ); - }); - }); - }, - model.events - ); - }; +module.exports = CastError; - /** - * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) - * - * ####Example: - * - * await Model.aggregate([{ $match: { foo: 'bar' } }]).allowDiskUse(true); - * - * @param {Boolean} value Should tell server it can use hard drive to store data during aggregation. - * @param {Array} [tags] optional tags for this query - * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ - */ - - Aggregate.prototype.allowDiskUse = function (value) { - this.options.allowDiskUse = value; - return this; - }; - /** - * Sets the hint option for the aggregation query (ignored for < 3.6.0) - * - * ####Example: - * - * Model.aggregate(..).hint({ qty: 1, category: 1 }).exec(callback) - * - * @param {Object|String} value a hint object or the index name - * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ - */ - - Aggregate.prototype.hint = function (value) { - this.options.hint = value; - return this; - }; +/***/ }), - /** - * Sets the session for this aggregation. Useful for [transactions](/docs/transactions.html). - * - * ####Example: - * - * const session = await Model.startSession(); - * await Model.aggregate(..).session(session); - * - * @param {ClientSession} session - * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ - */ - - Aggregate.prototype.session = function (session) { - if (session == null) { - delete this.options.session; - } else { - this.options.session = session; - } - return this; - }; +/***/ 8912: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Lets you set arbitrary options, for middleware or plugins. - * - * ####Example: - * - * const agg = Model.aggregate(..).option({ allowDiskUse: true }); // Set the `allowDiskUse` option - * agg.options; // `{ allowDiskUse: true }` - * - * @param {Object} options keys to merge into current options - * @param [options.maxTimeMS] number limits the time this aggregation will run, see [MongoDB docs on `maxTimeMS`](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) - * @param [options.allowDiskUse] boolean if true, the MongoDB server will use the hard drive to store data during this aggregation - * @param [options.collation] object see [`Aggregate.prototype.collation()`](./docs/api.html#aggregate_Aggregate-collation) - * @param [options.session] ClientSession see [`Aggregate.prototype.session()`](./docs/api.html#aggregate_Aggregate-session) - * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ - * @return {Aggregate} this - * @api public - */ - - Aggregate.prototype.option = function (value) { - for (const key in value) { - this.options[key] = value[key]; - } - return this; - }; +"use strict"; - /** - * Sets the cursor option option for the aggregation query (ignored for < 2.6.0). - * Note the different syntax below: .exec() returns a cursor object, and no callback - * is necessary. - * - * ####Example: - * - * const cursor = Model.aggregate(..).cursor({ batchSize: 1000 }).exec(); - * cursor.eachAsync(function(doc, i) { - * // use doc - * }); - * - * @param {Object} options - * @param {Number} options.batchSize set the cursor batch size - * @param {Boolean} [options.useMongooseAggCursor] use experimental mongoose-specific aggregation cursor (for `eachAsync()` and other query cursor semantics) - * @return {Aggregate} this - * @api public - * @see mongodb http://mongodb.github.io/node-mongodb-native/2.0/api/AggregationCursor.html - */ - - Aggregate.prototype.cursor = function (options) { - if (!this.options) { - this.options = {}; - } - this.options.cursor = options || {}; - return this; - }; +/*! + * Module dependencies. + */ - /** - * Sets an option on this aggregation. This function will be deprecated in a - * future release. Use the [`cursor()`](./api.html#aggregate_Aggregate-cursor), - * [`collation()`](./api.html#aggregate_Aggregate-collation), etc. helpers to - * set individual options, or access `agg.options` directly. - * - * Note that MongoDB aggregations [do **not** support the `noCursorTimeout` flag](https://jira.mongodb.org/browse/SERVER-6036), - * if you try setting that flag with this function you will get a "unrecognized field 'noCursorTimeout'" error. - * - * @param {String} flag - * @param {Boolean} value - * @return {Aggregate} this - * @api public - * @deprecated Use [`.option()`](api.html#aggregate_Aggregate-option) instead. Note that MongoDB aggregations do **not** support a `noCursorTimeout` option. - */ - - Aggregate.prototype.addCursorFlag = util.deprecate(function ( - flag, - value - ) { - if (!this.options) { - this.options = {}; - } - this.options[flag] = value; - return this; - }, - "Mongoose: `Aggregate#addCursorFlag()` is deprecated, use `option()` instead"); - - /** - * Adds a collation - * - * ####Example: - * - * Model.aggregate(..).collation({ locale: 'en_US', strength: 1 }).exec(); - * - * @param {Object} collation options - * @return {Aggregate} this - * @api public - * @see mongodb http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#aggregate - */ - - Aggregate.prototype.collation = function (collation) { - if (!this.options) { - this.options = {}; - } - this.options.collation = collation; - return this; - }; - /** - * Combines multiple aggregation pipelines. - * - * ####Example: - * - * Model.aggregate(...) - * .facet({ - * books: [{ groupBy: '$author' }], - * price: [{ $bucketAuto: { groupBy: '$price', buckets: 2 } }] - * }) - * .exec(); - * - * // Output: { books: [...], price: [{...}, {...}] } - * - * @param {Object} facet options - * @return {Aggregate} this - * @see $facet https://docs.mongodb.com/v3.4/reference/operator/aggregation/facet/ - * @api public - */ - - Aggregate.prototype.facet = function (options) { - return this.append({ $facet: options }); - }; - /** - * Helper for [Atlas Text Search](https://docs.atlas.mongodb.com/reference/atlas-search/tutorial/)'s - * `$search` stage. - * - * ####Example: - * - * Model.aggregate(). - * search({ - * text: { - * query: 'baseball', - * path: 'plot' - * } - * }); - * - * // Output: [{ plot: '...', title: '...' }] - * - * @param {Object} $search options - * @return {Aggregate} this - * @see $search https://docs.atlas.mongodb.com/reference/atlas-search/tutorial/ - * @api public - */ - - Aggregate.prototype.search = function (options) { - return this.append({ $search: options }); - }; +const MongooseError = __nccwpck_require__(4327); + +class DivergentArrayError extends MongooseError { + /*! + * DivergentArrayError constructor. + * @param {Array} paths + */ + constructor(paths) { + const msg = 'For your own good, using `document.save()` to update an array ' + + 'which was selected using an $elemMatch projection OR ' + + 'populated using skip, limit, query conditions, or exclusion of ' + + 'the _id field when the operation results in a $pop or $set of ' + + 'the entire array is not supported. The following ' + + 'path(s) would have been modified unsafely:\n' + + ' ' + paths.join('\n ') + '\n' + + 'Use Model.update() to update these arrays instead.'; + // TODO write up a docs page (FAQ) and link to it + super(msg); + } +} - /** - * Returns the current pipeline - * - * ####Example: - * - * MyModel.aggregate().match({ test: 1 }).pipeline(); // [{ $match: { test: 1 } }] - * - * @return {Array} - * @api public - */ - - Aggregate.prototype.pipeline = function () { - return this._pipeline; - }; +Object.defineProperty(DivergentArrayError.prototype, 'name', { + value: 'DivergentArrayError' +}); - /** - * Executes the aggregate pipeline on the currently bound Model. - * - * ####Example: - * - * aggregate.exec(callback); - * - * // Because a promise is returned, the `callback` is optional. - * const promise = aggregate.exec(); - * promise.then(..); - * - * @see Promise #promise_Promise - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - - Aggregate.prototype.exec = function (callback) { - if (!this._model) { - throw new Error("Aggregate not bound to any Model"); - } - const model = this._model; - const collection = this._model.collection; - - applyGlobalMaxTimeMS(this.options, model); - - if (this.options && this.options.cursor) { - return new AggregationCursor(this); - } - - return promiseOrCallback( - callback, - (cb) => { - prepareDiscriminatorPipeline(this); - stringifyFunctionOperators(this._pipeline); - - model.hooks.execPre("aggregate", this, (error) => { - if (error) { - const _opts = { error: error }; - return model.hooks.execPost( - "aggregate", - this, - [null], - _opts, - (error) => { - cb(error); - } - ); - } - if (!this._pipeline.length) { - return cb(new Error("Aggregate has empty pipeline")); - } +/*! + * exports + */ - const options = utils.clone(this.options || {}); - collection.aggregate(this._pipeline, options, (error, cursor) => { - if (error) { - const _opts = { error: error }; - return model.hooks.execPost( - "aggregate", - this, - [null], - _opts, - (error) => { - if (error) { - return cb(error); - } - return cb(null); - } - ); - } - cursor.toArray((error, result) => { - const _opts = { error: error }; - model.hooks.execPost( - "aggregate", - this, - [result], - _opts, - (error, result) => { - if (error) { - return cb(error); - } - - cb(null, result); - } - ); - }); - }); - }); - }, - model.events - ); - }; +module.exports = DivergentArrayError; - /** - * Provides promise for aggregate. - * - * ####Example: - * - * Model.aggregate(..).then(successCallback, errorCallback); - * - * @see Promise #promise_Promise - * @param {Function} [resolve] successCallback - * @param {Function} [reject] errorCallback - * @return {Promise} - */ - Aggregate.prototype.then = function (resolve, reject) { - return this.exec().then(resolve, reject); - }; - /** - * Executes the query returning a `Promise` which will be - * resolved with either the doc(s) or rejected with the error. - * Like [`.then()`](#query_Query-then), but only takes a rejection handler. - * - * @param {Function} [reject] - * @return {Promise} - * @api public - */ - - Aggregate.prototype.catch = function (reject) { - return this.exec().then(null, reject); - }; +/***/ }), - /** - * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js - * You do not need to call this function explicitly, the JavaScript runtime - * will call it for you. - * - * ####Example - * - * const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]); - * for await (const doc of agg) { - * console.log(doc.name); - * } - * - * Node.js 10.x supports async iterators natively without any flags. You can - * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). - * - * **Note:** This function is not set if `Symbol.asyncIterator` is undefined. If - * `Symbol.asyncIterator` is undefined, that means your Node.js version does not - * support async iterators. - * - * @method Symbol.asyncIterator - * @memberOf Aggregate - * @instance - * @api public - */ - - if (Symbol.asyncIterator != null) { - Aggregate.prototype[Symbol.asyncIterator] = function () { - return this.cursor({ useMongooseAggCursor: true }) - .exec() - .transformNull() - ._transformForAsyncIterator(); - }; - } +/***/ 4327: +/***/ ((module, exports, __nccwpck_require__) => { - /*! - * Helpers - */ +"use strict"; - /** - * Checks whether an object is likely a pipeline operator - * - * @param {Object} obj object to check - * @return {Boolean} - * @api private - */ - function isOperator(obj) { - if (typeof obj !== "object") { - return false; - } +/** + * MongooseError constructor. MongooseError is the base class for all + * Mongoose-specific errors. + * + * ####Example: + * const Model = mongoose.model('Test', new Schema({ answer: Number })); + * const doc = new Model({ answer: 'not a number' }); + * const err = doc.validateSync(); + * + * err instanceof mongoose.Error; // true + * + * @constructor Error + * @param {String} msg Error message + * @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error + */ - const k = Object.keys(obj); +const MongooseError = __nccwpck_require__(5953); - return ( - k.length === 1 && - k.some((key) => { - return key[0] === "$"; - }) - ); - } +/** + * The name of the error. The name uniquely identifies this Mongoose error. The + * possible values are: + * + * - `MongooseError`: general Mongoose error + * - `CastError`: Mongoose could not convert a value to the type defined in the schema path. May be in a `ValidationError` class' `errors` property. + * - `DisconnectedError`: This [connection](connections.html) timed out in trying to reconnect to MongoDB and will not successfully reconnect to MongoDB unless you explicitly reconnect. + * - `DivergentArrayError`: You attempted to `save()` an array that was modified after you loaded it with a `$elemMatch` or similar projection + * - `MissingSchemaError`: You tried to access a model with [`mongoose.model()`](api.html#mongoose_Mongoose-model) that was not defined + * - `DocumentNotFoundError`: The document you tried to [`save()`](api.html#document_Document-save) was not found + * - `ValidatorError`: error from an individual schema path's validator + * - `ValidationError`: error returned from [`validate()`](api.html#document_Document-validate) or [`validateSync()`](api.html#document_Document-validateSync). Contains zero or more `ValidatorError` instances in `.errors` property. + * - `MissingSchemaError`: You called `mongoose.Document()` without a schema + * - `ObjectExpectedError`: Thrown when you set a nested path to a non-object value with [strict mode set](guide.html#strict). + * - `ObjectParameterError`: Thrown when you pass a non-object value to a function which expects an object as a paramter + * - `OverwriteModelError`: Thrown when you call [`mongoose.model()`](api.html#mongoose_Mongoose-model) to re-define a model that was already defined. + * - `ParallelSaveError`: Thrown when you call [`save()`](api.html#model_Model-save) on a document when the same document instance is already saving. + * - `StrictModeError`: Thrown when you set a path that isn't the schema and [strict mode](guide.html#strict) is set to `throw`. + * - `VersionError`: Thrown when the [document is out of sync](guide.html#versionKey) + * + * @api public + * @property {String} name + * @memberOf Error + * @instance + */ - /*! - * Adds the appropriate `$match` pipeline step to the top of an aggregate's - * pipeline, should it's model is a non-root discriminator type. This is - * analogous to the `prepareDiscriminatorCriteria` function in `lib/query.js`. - * - * @param {Aggregate} aggregate Aggregate to prepare - */ - - Aggregate._prepareDiscriminatorPipeline = prepareDiscriminatorPipeline; - - function prepareDiscriminatorPipeline(aggregate) { - const schema = aggregate._model.schema; - const discriminatorMapping = schema && schema.discriminatorMapping; - - if (discriminatorMapping && !discriminatorMapping.isRoot) { - const originalPipeline = aggregate._pipeline; - const discriminatorKey = discriminatorMapping.key; - const discriminatorValue = discriminatorMapping.value; - - // If the first pipeline stage is a match and it doesn't specify a `__t` - // key, add the discriminator key to it. This allows for potential - // aggregation query optimizations not to be disturbed by this feature. - if ( - originalPipeline[0] && - originalPipeline[0].$match && - !originalPipeline[0].$match[discriminatorKey] - ) { - originalPipeline[0].$match[discriminatorKey] = discriminatorValue; - // `originalPipeline` is a ref, so there's no need for - // aggregate._pipeline = originalPipeline - } else if (originalPipeline[0] && originalPipeline[0].$geoNear) { - originalPipeline[0].$geoNear.query = - originalPipeline[0].$geoNear.query || {}; - originalPipeline[0].$geoNear.query[discriminatorKey] = - discriminatorValue; - } else if (originalPipeline[0] && originalPipeline[0].$search) { - if (originalPipeline[1] && originalPipeline[1].$match != null) { - originalPipeline[1].$match[discriminatorKey] = - originalPipeline[1].$match[discriminatorKey] || - discriminatorValue; - } else { - const match = {}; - match[discriminatorKey] = discriminatorValue; - originalPipeline.splice(1, 0, { $match: match }); - } - } else { - const match = {}; - match[discriminatorKey] = discriminatorValue; - aggregate._pipeline.unshift({ $match: match }); - } - } - } +/*! + * Module exports. + */ - /*! - * Exports - */ +module.exports = exports = MongooseError; - module.exports = Aggregate; +/** + * The default built-in validator error messages. + * + * @see Error.messages #error_messages_MongooseError-messages + * @api public + * @memberOf Error + * @static messages + */ - /***/ - }, +MongooseError.messages = __nccwpck_require__(8657); - /***/ 6830: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; - /*! - * Module dependencies. - */ - - const NodeJSDocument = __nccwpck_require__(6717); - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const MongooseError = __nccwpck_require__(4327); - const Schema = __nccwpck_require__(7606); - const ObjectId = __nccwpck_require__(2706); - const ValidationError = MongooseError.ValidationError; - const applyHooks = __nccwpck_require__(5373); - const isObject = __nccwpck_require__(273); - - /** - * Document constructor. - * - * @param {Object} obj the values to set - * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data - * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `init`: Emitted on a document after it has was retrieved from the db and fully hydrated by Mongoose. - * @event `save`: Emitted when the document is successfully saved - * @api private - */ - - function Document(obj, schema, fields, skipId, skipInit) { - if (!(this instanceof Document)) { - return new Document(obj, schema, fields, skipId, skipInit); - } - - if (isObject(schema) && !schema.instanceOfSchema) { - schema = new Schema(schema); - } - - // When creating EmbeddedDocument, it already has the schema and he doesn't need the _id - schema = this.schema || schema; - - // Generate ObjectId if it is missing, but it requires a scheme - if (!this.schema && schema.options._id) { - obj = obj || {}; - - if (obj._id === undefined) { - obj._id = new ObjectId(); - } - } +// backward compat +MongooseError.Messages = MongooseError.messages; - if (!schema) { - throw new MongooseError.MissingSchemaError(); - } +/** + * An instance of this error class will be returned when `save()` fails + * because the underlying + * document was not found. The constructor takes one parameter, the + * conditions that mongoose passed to `update()` when trying to update + * the document. + * + * @api public + * @memberOf Error + * @static DocumentNotFoundError + */ - this.$__setSchema(schema); +MongooseError.DocumentNotFoundError = __nccwpck_require__(5147); - NodeJSDocument.call(this, obj, fields, skipId, skipInit); +/** + * An instance of this error class will be returned when mongoose failed to + * cast a value. + * + * @api public + * @memberOf Error + * @static CastError + */ - applyHooks(this, schema, { decorateDoc: true }); +MongooseError.CastError = __nccwpck_require__(2798); - // apply methods - for (const m in schema.methods) { - this[m] = schema.methods[m]; - } - // apply statics - for (const s in schema.statics) { - this[s] = schema.statics[s]; - } - } +/** + * An instance of this error class will be returned when [validation](/docs/validation.html) failed. + * The `errors` property contains an object whose keys are the paths that failed and whose values are + * instances of CastError or ValidationError. + * + * @api public + * @memberOf Error + * @static ValidationError + */ - /*! - * Inherit from the NodeJS document - */ +MongooseError.ValidationError = __nccwpck_require__(8460); - Document.prototype = Object.create(NodeJSDocument.prototype); - Document.prototype.constructor = Document; +/** + * A `ValidationError` has a hash of `errors` that contain individual + * `ValidatorError` instances. + * + * ####Example: + * + * const schema = Schema({ name: { type: String, required: true } }); + * const Model = mongoose.model('Test', schema); + * const doc = new Model({}); + * + * // Top-level error is a ValidationError, **not** a ValidatorError + * const err = doc.validateSync(); + * err instanceof mongoose.Error.ValidationError; // true + * + * // A ValidationError `err` has 0 or more ValidatorErrors keyed by the + * // path in the `err.errors` property. + * err.errors['name'] instanceof mongoose.Error.ValidatorError; + * + * err.errors['name'].kind; // 'required' + * err.errors['name'].path; // 'name' + * err.errors['name'].value; // undefined + * + * Instances of `ValidatorError` have the following properties: + * + * - `kind`: The validator's `type`, like `'required'` or `'regexp'` + * - `path`: The path that failed validation + * - `value`: The value that failed validation + * + * @api public + * @memberOf Error + * @static ValidatorError + */ - /*! - * ignore - */ +MongooseError.ValidatorError = __nccwpck_require__(6345); - Document.events = new EventEmitter(); +/** + * An instance of this error class will be returned when you call `save()` after + * the document in the database was changed in a potentially unsafe way. See + * the [`versionKey` option](/docs/guide.html#versionKey) for more information. + * + * @api public + * @memberOf Error + * @static VersionError + */ - /*! - * Browser doc exposes the event emitter API - */ +MongooseError.VersionError = __nccwpck_require__(4305); - Document.$emitter = new EventEmitter(); +/** + * An instance of this error class will be returned when you call `save()` multiple + * times on the same document in parallel. See the [FAQ](/docs/faq.html) for more + * information. + * + * @api public + * @memberOf Error + * @static ParallelSaveError + */ - [ - "on", - "once", - "emit", - "listeners", - "removeListener", - "setMaxListeners", - "removeAllListeners", - "addListener", - ].forEach(function (emitterFn) { - Document[emitterFn] = function () { - return Document.$emitter[emitterFn].apply( - Document.$emitter, - arguments - ); - }; - }); +MongooseError.ParallelSaveError = __nccwpck_require__(618); - /*! - * Module exports. - */ +/** + * Thrown when a model with the given name was already registered on the connection. + * See [the FAQ about `OverwriteModelError`](/docs/faq.html#overwrite-model-error). + * + * @api public + * @memberOf Error + * @static OverwriteModelError + */ - Document.ValidationError = ValidationError; - module.exports = exports = Document; +MongooseError.OverwriteModelError = __nccwpck_require__(970); - /***/ - }, +/** + * Thrown when you try to access a model that has not been registered yet + * + * @api public + * @memberOf Error + * @static MissingSchemaError + */ - /***/ 8874: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const CastError = __nccwpck_require__(2798); - const StrictModeError = __nccwpck_require__(703); - const Types = __nccwpck_require__(2987); - const castTextSearch = __nccwpck_require__(8807); - const get = __nccwpck_require__(8730); - const getConstructorName = __nccwpck_require__(7323); - const getSchemaDiscriminatorByValue = __nccwpck_require__(6250); - const isOperator = __nccwpck_require__(3342); - const util = __nccwpck_require__(1669); - const isObject = __nccwpck_require__(273); - const isMongooseObject = __nccwpck_require__(7104); - - const ALLOWED_GEOWITHIN_GEOJSON_TYPES = ["Polygon", "MultiPolygon"]; - - /** - * Handles internal casting for query filters. - * - * @param {Schema} schema - * @param {Object} obj Object to cast - * @param {Object} options the query options - * @param {Query} context passed to setters - * @api private - */ - module.exports = function cast(schema, obj, options, context) { - if (Array.isArray(obj)) { - throw new Error( - "Query filter must be an object, got an array ", - util.inspect(obj) - ); - } +MongooseError.MissingSchemaError = __nccwpck_require__(2860); - if (obj == null) { - return obj; - } +/** + * An instance of this error will be returned if you used an array projection + * and then modified the array in an unsafe way. + * + * @api public + * @memberOf Error + * @static DivergentArrayError + */ - // bson 1.x has the unfortunate tendency to remove filters that have a top-level - // `_bsontype` property. But we should still allow ObjectIds because - // `Collection#find()` has a special case to support `find(objectid)`. - // Should remove this when we upgrade to bson 4.x. See gh-8222, gh-8268 - if (obj.hasOwnProperty("_bsontype") && obj._bsontype !== "ObjectID") { - delete obj._bsontype; - } +MongooseError.DivergentArrayError = __nccwpck_require__(8912); - if ( - schema != null && - schema.discriminators != null && - obj[schema.options.discriminatorKey] != null - ) { - schema = - getSchemaDiscriminatorByValue( - schema, - obj[schema.options.discriminatorKey] - ) || schema; - } +/** + * Thrown when your try to pass values to model contrtuctor that + * were not specified in schema or change immutable properties when + * `strict` mode is `"throw"` + * + * @api public + * @memberOf Error + * @static StrictModeError + */ - const paths = Object.keys(obj); - let i = paths.length; - let _keys; - let any$conditionals; - let schematype; - let nested; - let path; - let type; - let val; +MongooseError.StrictModeError = __nccwpck_require__(5328); - options = options || {}; - while (i--) { - path = paths[i]; - val = obj[path]; +/***/ }), - if (path === "$or" || path === "$nor" || path === "$and") { - if (!Array.isArray(val)) { - throw new CastError("Array", val, path); - } - for (let k = 0; k < val.length; ++k) { - if (val[k] == null || typeof val[k] !== "object") { - throw new CastError("Object", val[k], path + "." + k); - } - val[k] = cast(schema, val[k], options, context); - } - } else if (path === "$where") { - type = typeof val; +/***/ 8657: +/***/ ((module, exports) => { - if (type !== "string" && type !== "function") { - throw new Error("Must have a string or function for $where"); - } +"use strict"; - if (type === "function") { - obj[path] = val.toString(); - } +/** + * The default built-in validator error messages. These may be customized. + * + * // customize within each schema or globally like so + * const mongoose = require('mongoose'); + * mongoose.Error.messages.String.enum = "Your custom message for {PATH}."; + * + * As you might have noticed, error messages support basic templating + * + * - `{PATH}` is replaced with the invalid document path + * - `{VALUE}` is replaced with the invalid value + * - `{TYPE}` is replaced with the validator type such as "regexp", "min", or "user defined" + * - `{MIN}` is replaced with the declared min value for the Number.min validator + * - `{MAX}` is replaced with the declared max value for the Number.max validator + * + * Click the "show code" link below to see all defaults. + * + * @static messages + * @receiver MongooseError + * @api public + */ - continue; - } else if (path === "$elemMatch") { - val = cast(schema, val, options, context); - } else if (path === "$text") { - val = castTextSearch(val, path); - } else { - if (!schema) { - // no casting for Mixed types - continue; - } - schematype = schema.path(path); - // Check for embedded discriminator paths - if (!schematype) { - const split = path.split("."); - let j = split.length; - while (j--) { - const pathFirstHalf = split.slice(0, j).join("."); - const pathLastHalf = split.slice(j).join("."); - const _schematype = schema.path(pathFirstHalf); - const discriminatorKey = get( - _schematype, - "schema.options.discriminatorKey" - ); +const msg = module.exports = exports = {}; - // gh-6027: if we haven't found the schematype but this path is - // underneath an embedded discriminator and the embedded discriminator - // key is in the query, use the embedded discriminator schema - if ( - _schematype != null && - get(_schematype, "schema.discriminators") != null && - discriminatorKey != null && - pathLastHalf !== discriminatorKey - ) { - const discriminatorVal = get( - obj, - pathFirstHalf + "." + discriminatorKey - ); - if (discriminatorVal != null) { - schematype = - _schematype.schema.discriminators[discriminatorVal].path( - pathLastHalf - ); - } - } - } - } +msg.DocumentNotFoundError = null; - if (!schematype) { - // Handle potential embedded array queries - const split = path.split("."); - let j = split.length; - let pathFirstHalf; - let pathLastHalf; - let remainingConds; - - // Find the part of the var path that is a path of the Schema - while (j--) { - pathFirstHalf = split.slice(0, j).join("."); - schematype = schema.path(pathFirstHalf); - if (schematype) { - break; - } - } +msg.general = {}; +msg.general.default = 'Validator failed for path `{PATH}` with value `{VALUE}`'; +msg.general.required = 'Path `{PATH}` is required.'; - // If a substring of the input path resolves to an actual real path... - if (schematype) { - // Apply the casting; similar code for $elemMatch in schema/array.js - if (schematype.caster && schematype.caster.schema) { - remainingConds = {}; - pathLastHalf = split.slice(j).join("."); - remainingConds[pathLastHalf] = val; - obj[path] = cast( - schematype.caster.schema, - remainingConds, - options, - context - )[pathLastHalf]; - } else { - obj[path] = val; - } - continue; - } +msg.Number = {}; +msg.Number.min = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).'; +msg.Number.max = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).'; +msg.Number.enum = '`{VALUE}` is not a valid enum value for path `{PATH}`.'; - if (isObject(val)) { - // handle geo schemas that use object notation - // { loc: { long: Number, lat: Number } - - let geo = ""; - if (val.$near) { - geo = "$near"; - } else if (val.$nearSphere) { - geo = "$nearSphere"; - } else if (val.$within) { - geo = "$within"; - } else if (val.$geoIntersects) { - geo = "$geoIntersects"; - } else if (val.$geoWithin) { - geo = "$geoWithin"; - } +msg.Date = {}; +msg.Date.min = 'Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN}).'; +msg.Date.max = 'Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX}).'; - if (geo) { - const numbertype = new Types.Number("__QueryCasting__"); - let value = val[geo]; +msg.String = {}; +msg.String.enum = '`{VALUE}` is not a valid enum value for path `{PATH}`.'; +msg.String.match = 'Path `{PATH}` is invalid ({VALUE}).'; +msg.String.minlength = 'Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).'; +msg.String.maxlength = 'Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH}).'; - if (val.$maxDistance != null) { - val.$maxDistance = numbertype.castForQueryWrapper({ - val: val.$maxDistance, - context: context, - }); - } - if (val.$minDistance != null) { - val.$minDistance = numbertype.castForQueryWrapper({ - val: val.$minDistance, - context: context, - }); - } - if (geo === "$within") { - const withinType = - value.$center || - value.$centerSphere || - value.$box || - value.$polygon; - - if (!withinType) { - throw new Error( - "Bad $within parameter: " + JSON.stringify(val) - ); - } +/***/ }), - value = withinType; - } else if ( - geo === "$near" && - typeof value.type === "string" && - Array.isArray(value.coordinates) - ) { - // geojson; cast the coordinates - value = value.coordinates; - } else if ( - (geo === "$near" || - geo === "$nearSphere" || - geo === "$geoIntersects") && - value.$geometry && - typeof value.$geometry.type === "string" && - Array.isArray(value.$geometry.coordinates) - ) { - if (value.$maxDistance != null) { - value.$maxDistance = numbertype.castForQueryWrapper({ - val: value.$maxDistance, - context: context, - }); - } - if (value.$minDistance != null) { - value.$minDistance = numbertype.castForQueryWrapper({ - val: value.$minDistance, - context: context, - }); - } - if (isMongooseObject(value.$geometry)) { - value.$geometry = value.$geometry.toObject({ - transform: false, - virtuals: false, - }); - } - value = value.$geometry.coordinates; - } else if (geo === "$geoWithin") { - if (value.$geometry) { - if (isMongooseObject(value.$geometry)) { - value.$geometry = value.$geometry.toObject({ - virtuals: false, - }); - } - const geoWithinType = value.$geometry.type; - if ( - ALLOWED_GEOWITHIN_GEOJSON_TYPES.indexOf( - geoWithinType - ) === -1 - ) { - throw new Error( - 'Invalid geoJSON type for $geoWithin "' + - geoWithinType + - '", must be "Polygon" or "MultiPolygon"' - ); - } - value = value.$geometry.coordinates; - } else { - value = - value.$box || - value.$polygon || - value.$center || - value.$centerSphere; - if (isMongooseObject(value)) { - value = value.toObject({ virtuals: false }); - } - } - } +/***/ 2860: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _cast(value, numbertype, context); - continue; - } - } +"use strict"; - if (schema.nested[path]) { - continue; - } - if (options.upsert && options.strict) { - if (options.strict === "throw") { - throw new StrictModeError(path); - } - throw new StrictModeError( - path, - 'Path "' + - path + - '" is not in ' + - "schema, strict mode is `true`, and upsert is `true`." - ); - } else if (options.strictQuery === "throw") { - throw new StrictModeError( - path, - 'Path "' + - path + - '" is not in ' + - "schema and strictQuery is 'throw'." - ); - } else if (options.strictQuery) { - delete obj[path]; - } - } else if (val == null) { - continue; - } else if (getConstructorName(val) === "Object") { - any$conditionals = Object.keys(val).some(isOperator); +/*! + * Module dependencies. + */ - if (!any$conditionals) { - obj[path] = schematype.castForQueryWrapper({ - val: val, - context: context, - }); - } else { - const ks = Object.keys(val); - let $cond; - - let k = ks.length; - - while (k--) { - $cond = ks[k]; - nested = val[$cond]; - - if ($cond === "$not") { - if (nested && schematype && !schematype.caster) { - _keys = Object.keys(nested); - if (_keys.length && isOperator(_keys[0])) { - for (const key in nested) { - nested[key] = schematype.castForQueryWrapper({ - $conditional: key, - val: nested[key], - context: context, - }); - } - } else { - val[$cond] = schematype.castForQueryWrapper({ - $conditional: $cond, - val: nested, - context: context, - }); - } - continue; - } - cast( - schematype.caster ? schematype.caster.schema : schema, - nested, - options, - context - ); - } else { - val[$cond] = schematype.castForQueryWrapper({ - $conditional: $cond, - val: nested, - context: context, - }); - } - } - } - } else if ( - Array.isArray(val) && - ["Buffer", "Array"].indexOf(schematype.instance) === -1 - ) { - const casted = []; - const valuesArray = val; - - for (const _val of valuesArray) { - casted.push( - schematype.castForQueryWrapper({ - val: _val, - context: context, - }) - ); - } - obj[path] = { $in: casted }; - } else { - obj[path] = schematype.castForQueryWrapper({ - val: val, - context: context, - }); - } - } - } - return obj; - }; +const MongooseError = __nccwpck_require__(4327); - function _cast(val, numbertype, context) { - if (Array.isArray(val)) { - val.forEach(function (item, i) { - if (Array.isArray(item) || isObject(item)) { - return _cast(item, numbertype, context); - } - val[i] = numbertype.castForQueryWrapper({ - val: item, - context: context, - }); - }); - } else { - const nearKeys = Object.keys(val); - let nearLen = nearKeys.length; - while (nearLen--) { - const nkey = nearKeys[nearLen]; - const item = val[nkey]; - if (Array.isArray(item) || isObject(item)) { - _cast(item, numbertype, context); - val[nkey] = item; - } else { - val[nkey] = numbertype.castForQuery({ - val: item, - context: context, - }); - } - } - } - } +class MissingSchemaError extends MongooseError { + /*! + * MissingSchema Error constructor. + * @param {String} name + */ + constructor(name) { + const msg = 'Schema hasn\'t been registered for model "' + name + '".\n' + + 'Use mongoose.model(name, schema)'; + super(msg); + } +} - /***/ - }, +Object.defineProperty(MissingSchemaError.prototype, 'name', { + value: 'MissingSchemaError' +}); - /***/ 66: /***/ (module, __unused_webpack_exports, __nccwpck_require__) => { - "use strict"; +/*! + * exports + */ - const CastError = __nccwpck_require__(2798); +module.exports = MissingSchemaError; - /*! - * Given a value, cast it to a boolean, or throw a `CastError` if the value - * cannot be casted. `null` and `undefined` are considered valid. - * - * @param {Any} value - * @param {String} [path] optional the path to set on the CastError - * @return {Boolean|null|undefined} - * @throws {CastError} if `value` is not one of the allowed values - * @api private - */ - module.exports = function castBoolean(value, path) { - if (module.exports.convertToTrue.has(value)) { - return true; - } - if (module.exports.convertToFalse.has(value)) { - return false; - } +/***/ }), - if (value == null) { - return value; - } +/***/ 5953: +/***/ ((module) => { - throw new CastError("boolean", value, path); - }; +"use strict"; - module.exports.convertToTrue = new Set([true, "true", 1, "1", "yes"]); - module.exports.convertToFalse = new Set([false, "false", 0, "0", "no"]); - /***/ - }, +/*! + * ignore + */ - /***/ 1001: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +class MongooseError extends Error { } - const assert = __nccwpck_require__(2357); +Object.defineProperty(MongooseError.prototype, 'name', { + value: 'MongooseError' +}); - module.exports = function castDate(value) { - // Support empty string because of empty form values. Originally introduced - // in https://github.com/Automattic/mongoose/commit/efc72a1898fc3c33a319d915b8c5463a22938dfe - if (value == null || value === "") { - return null; - } +module.exports = MongooseError; - if (value instanceof Date) { - assert.ok(!isNaN(value.valueOf())); - return value; - } +/***/ }), - let date; +/***/ 5147: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - assert.ok(typeof value !== "boolean"); +"use strict"; - if (value instanceof Number || typeof value === "number") { - date = new Date(value); - } else if ( - typeof value === "string" && - !isNaN(Number(value)) && - (Number(value) >= 275761 || Number(value) < -271820) - ) { - // string representation of milliseconds take this path - date = new Date(Number(value)); - } else if (typeof value.valueOf === "function") { - // support for moment.js. This is also the path strings will take because - // strings have a `valueOf()` - date = new Date(value.valueOf()); - } else { - // fallback - date = new Date(value); - } - if (!isNaN(date.valueOf())) { - return date; - } +/*! + * Module dependencies. + */ - assert.ok(false); - }; +const MongooseError = __nccwpck_require__(4327); +const util = __nccwpck_require__(1669); + +class DocumentNotFoundError extends MongooseError { + /*! + * OverwriteModel Error constructor. + */ + constructor(filter, model, numAffected, result) { + let msg; + const messages = MongooseError.messages; + if (messages.DocumentNotFoundError != null) { + msg = typeof messages.DocumentNotFoundError === 'function' ? + messages.DocumentNotFoundError(filter, model) : + messages.DocumentNotFoundError; + } else { + msg = 'No document found for query "' + util.inspect(filter) + + '" on model "' + model + '"'; + } - /***/ - }, + super(msg); - /***/ 8748: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + this.result = result; + this.numAffected = numAffected; + this.filter = filter; + // Backwards compat + this.query = filter; + } +} - const Decimal128Type = __nccwpck_require__(8319); - const assert = __nccwpck_require__(2357); +Object.defineProperty(DocumentNotFoundError.prototype, 'name', { + value: 'DocumentNotFoundError' +}); - module.exports = function castDecimal128(value) { - if (value == null) { - return value; - } +/*! + * exports + */ - if ( - typeof value === "object" && - typeof value.$numberDecimal === "string" - ) { - return Decimal128Type.fromString(value.$numberDecimal); - } +module.exports = DocumentNotFoundError; - if (value instanceof Decimal128Type) { - return value; - } - if (typeof value === "string") { - return Decimal128Type.fromString(value); - } +/***/ }), - if (Buffer.isBuffer(value)) { - return new Decimal128Type(value); - } +/***/ 2293: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (typeof value === "number") { - return Decimal128Type.fromString(String(value)); - } +"use strict"; +/*! + * Module dependencies. + */ - if ( - typeof value.valueOf === "function" && - typeof value.valueOf() === "string" - ) { - return Decimal128Type.fromString(value.valueOf()); - } - assert.ok(false); - }; - /***/ - }, +const MongooseError = __nccwpck_require__(4327); + + +class ObjectExpectedError extends MongooseError { + /** + * Strict mode error constructor + * + * @param {string} type + * @param {string} value + * @api private + */ + constructor(path, val) { + const typeDescription = Array.isArray(val) ? 'array' : 'primitive value'; + super('Tried to set nested object field `' + path + + `\` to ${typeDescription} \`` + val + '`'); + this.path = path; + } +} - /***/ 1582: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const assert = __nccwpck_require__(2357); - - /*! - * Given a value, cast it to a number, or throw a `CastError` if the value - * cannot be casted. `null` and `undefined` are considered valid. - * - * @param {Any} value - * @param {String} [path] optional the path to set on the CastError - * @return {Boolean|null|undefined} - * @throws {Error} if `value` is not one of the allowed values - * @api private - */ - - module.exports = function castNumber(val) { - if (val == null) { - return val; - } - if (val === "") { - return null; - } +Object.defineProperty(ObjectExpectedError.prototype, 'name', { + value: 'ObjectExpectedError' +}); - if (typeof val === "string" || typeof val === "boolean") { - val = Number(val); - } +module.exports = ObjectExpectedError; - assert.ok(!isNaN(val)); - if (val instanceof Number) { - return val.valueOf(); - } - if (typeof val === "number") { - return val; - } - if (!Array.isArray(val) && typeof val.valueOf === "function") { - return Number(val.valueOf()); - } - if ( - val.toString && - !Array.isArray(val) && - val.toString() == Number(val) - ) { - return Number(val); - } - assert.ok(false); - }; +/***/ }), - /***/ - }, +/***/ 3456: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /***/ 5552: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +"use strict"; +/*! + * Module dependencies. + */ - const ObjectId = __nccwpck_require__(2324).get().ObjectId; - const assert = __nccwpck_require__(2357); - module.exports = function castObjectId(value) { - if (value == null) { - return value; - } - if (value instanceof ObjectId) { - return value; - } +const MongooseError = __nccwpck_require__(4327); - if (value._id) { - if (value._id instanceof ObjectId) { - return value._id; - } - if (value._id.toString instanceof Function) { - return new ObjectId(value._id.toString()); - } - } +class ObjectParameterError extends MongooseError { + /** + * Constructor for errors that happen when a parameter that's expected to be + * an object isn't an object + * + * @param {Any} value + * @param {String} paramName + * @param {String} fnName + * @api private + */ + constructor(value, paramName, fnName) { + super('Parameter "' + paramName + '" to ' + fnName + + '() must be an object, got ' + value.toString()); + } +} - if (value.toString instanceof Function) { - return new ObjectId(value.toString()); - } - assert.ok(false); - }; +Object.defineProperty(ObjectParameterError.prototype, 'name', { + value: 'ObjectParameterError' +}); - /***/ - }, +module.exports = ObjectParameterError; - /***/ 1318: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const CastError = __nccwpck_require__(2798); - - /*! - * Given a value, cast it to a string, or throw a `CastError` if the value - * cannot be casted. `null` and `undefined` are considered valid. - * - * @param {Any} value - * @param {String} [path] optional the path to set on the CastError - * @return {string|null|undefined} - * @throws {CastError} - * @api private - */ - - module.exports = function castString(value, path) { - // If null or undefined - if (value == null) { - return value; - } - // handle documents being passed - if (value._id && typeof value._id === "string") { - return value._id; - } +/***/ }), - // Re: gh-647 and gh-3030, we're ok with casting using `toString()` - // **unless** its the default Object.toString, because "[object Object]" - // doesn't really qualify as useful data - if ( - value.toString && - value.toString !== Object.prototype.toString && - !Array.isArray(value) - ) { - return value.toString(); - } +/***/ 970: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - throw new CastError("string", value, path); - }; +"use strict"; - /***/ - }, +/*! + * Module dependencies. + */ - /***/ 6798: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const STATES = __nccwpck_require__(932); - const immediate = __nccwpck_require__(4830); +const MongooseError = __nccwpck_require__(4327); - /** - * Abstract Collection constructor - * - * This is the base class that drivers inherit from and implement. - * - * @param {String} name name of the collection - * @param {Connection} conn A MongooseConnection instance - * @param {Object} opts optional collection options - * @api public - */ - function Collection(name, conn, opts) { - if (opts === void 0) { - opts = {}; - } - if (opts.capped === void 0) { - opts.capped = {}; - } +class OverwriteModelError extends MongooseError { + /*! + * OverwriteModel Error constructor. + * @param {String} name + */ + constructor(name) { + super('Cannot overwrite `' + name + '` model once compiled.'); + } +} - if (typeof opts.capped === "number") { - opts.capped = { size: opts.capped }; - } +Object.defineProperty(OverwriteModelError.prototype, 'name', { + value: 'OverwriteModelError' +}); - this.opts = opts; - this.name = name; - this.collectionName = name; - this.conn = conn; - this.queue = []; - this.buffer = true; - this.emitter = new EventEmitter(); +/*! + * exports + */ - if (STATES.connected === this.conn.readyState) { - this.onOpen(); - } - } +module.exports = OverwriteModelError; - /** - * The collection name - * - * @api public - * @property name - */ - Collection.prototype.name; +/***/ }), - /** - * The collection name - * - * @api public - * @property collectionName - */ +/***/ 618: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Collection.prototype.collectionName; +"use strict"; - /** - * The Connection instance - * - * @api public - * @property conn - */ - Collection.prototype.conn; +/*! + * Module dependencies. + */ - /** - * Called when the database connects - * - * @api private - */ +const MongooseError = __nccwpck_require__(4327); + +class ParallelSaveError extends MongooseError { + /** + * ParallelSave Error constructor. + * + * @param {Document} doc + * @api private + */ + constructor(doc) { + const msg = 'Can\'t save() the same doc multiple times in parallel. Document: '; + super(msg + doc._id); + } +} - Collection.prototype.onOpen = function () { - this.buffer = false; - immediate(() => this.doQueue()); - }; +Object.defineProperty(ParallelSaveError.prototype, 'name', { + value: 'ParallelSaveError' +}); - /** - * Called when the database disconnects - * - * @api private - */ +/*! + * exports + */ - Collection.prototype.onClose = function (force) { - if (this._shouldBufferCommands() && !force) { - this.buffer = true; - } - }; +module.exports = ParallelSaveError; - /** - * Queues a method for later execution when its - * database connection opens. - * - * @param {String} name name of the method to queue - * @param {Array} args arguments to pass to the method when executed - * @api private - */ - - Collection.prototype.addQueue = function (name, args) { - this.queue.push([name, args]); - return this; - }; - /** - * Removes a queued method - * - * @param {String} name name of the method to queue - * @param {Array} args arguments to pass to the method when executed - * @api private - */ - - Collection.prototype.removeQueue = function (name, args) { - const index = this.queue.findIndex( - (v) => v[0] === name && v[1] === args - ); - if (index === -1) { - return false; - } - this.queue.splice(index, 1); - return true; - }; +/***/ }), - /** - * Executes all queued methods and clears the queue. - * - * @api private - */ +/***/ 3897: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Collection.prototype.doQueue = function () { - for (const method of this.queue) { - if (typeof method[0] === "function") { - method[0].apply(this, method[1]); - } else { - this[method[0]].apply(this, method[1]); - } - } - this.queue = []; - const _this = this; - immediate(function () { - _this.emitter.emit("queue"); - }); - return this; - }; +"use strict"; - /** - * Abstract method that drivers must implement. - */ - Collection.prototype.ensureIndex = function () { - throw new Error("Collection#ensureIndex unimplemented by driver"); - }; +/*! + * Module dependencies. + */ - /** - * Abstract method that drivers must implement. - */ +const MongooseError = __nccwpck_require__(5953); - Collection.prototype.createIndex = function () { - throw new Error("Collection#createIndex unimplemented by driver"); - }; - /** - * Abstract method that drivers must implement. - */ +class ParallelValidateError extends MongooseError { + /** + * ParallelValidate Error constructor. + * + * @param {Document} doc + * @api private + */ + constructor(doc) { + const msg = 'Can\'t validate() the same doc multiple times in parallel. Document: '; + super(msg + doc._id); + } +} - Collection.prototype.findAndModify = function () { - throw new Error("Collection#findAndModify unimplemented by driver"); - }; +Object.defineProperty(ParallelValidateError.prototype, 'name', { + value: 'ParallelValidateError' +}); - /** - * Abstract method that drivers must implement. - */ +/*! + * exports + */ - Collection.prototype.findOneAndUpdate = function () { - throw new Error("Collection#findOneAndUpdate unimplemented by driver"); - }; +module.exports = ParallelValidateError; - /** - * Abstract method that drivers must implement. - */ +/***/ }), - Collection.prototype.findOneAndDelete = function () { - throw new Error("Collection#findOneAndDelete unimplemented by driver"); - }; +/***/ 3070: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Abstract method that drivers must implement. - */ +"use strict"; +/*! + * Module dependencies. + */ - Collection.prototype.findOneAndReplace = function () { - throw new Error("Collection#findOneAndReplace unimplemented by driver"); - }; - /** - * Abstract method that drivers must implement. - */ - Collection.prototype.findOne = function () { - throw new Error("Collection#findOne unimplemented by driver"); - }; +const MongooseError = __nccwpck_require__(5953); +const allServersUnknown = __nccwpck_require__(8571); +const isAtlas = __nccwpck_require__(7352); +const isSSLError = __nccwpck_require__(5437); - /** - * Abstract method that drivers must implement. - */ +/*! + * ignore + */ - Collection.prototype.find = function () { - throw new Error("Collection#find unimplemented by driver"); - }; +const atlasMessage = 'Could not connect to any servers in your MongoDB Atlas cluster. ' + + 'One common reason is that you\'re trying to access the database from ' + + 'an IP that isn\'t whitelisted. Make sure your current IP address is on your Atlas ' + + 'cluster\'s IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/'; + +const sslMessage = 'Mongoose is connecting with SSL enabled, but the server is ' + + 'not accepting SSL connections. Please ensure that the MongoDB server you are ' + + 'connecting to is configured to accept SSL connections. Learn more: ' + + 'https://mongoosejs.com/docs/tutorials/ssl.html'; + +class MongooseServerSelectionError extends MongooseError { + /** + * MongooseServerSelectionError constructor + * + * @api private + */ + assimilateError(err) { + const reason = err.reason; + // Special message for a case that is likely due to IP whitelisting issues. + const isAtlasWhitelistError = isAtlas(reason) && + allServersUnknown(reason) && + err.message.indexOf('bad auth') === -1 && + err.message.indexOf('Authentication failed') === -1; + + if (isAtlasWhitelistError) { + this.message = atlasMessage; + } else if (isSSLError(reason)) { + this.message = sslMessage; + } else { + this.message = err.message; + } + for (const key in err) { + if (key !== 'name') { + this[key] = err[key]; + } + } - /** - * Abstract method that drivers must implement. - */ + return this; + } +} - Collection.prototype.insert = function () { - throw new Error("Collection#insert unimplemented by driver"); - }; +Object.defineProperty(MongooseServerSelectionError.prototype, 'name', { + value: 'MongooseServerSelectionError' +}); - /** - * Abstract method that drivers must implement. - */ +module.exports = MongooseServerSelectionError; - Collection.prototype.insertOne = function () { - throw new Error("Collection#insertOne unimplemented by driver"); - }; - /** - * Abstract method that drivers must implement. - */ +/***/ }), - Collection.prototype.insertMany = function () { - throw new Error("Collection#insertMany unimplemented by driver"); - }; +/***/ 5328: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Abstract method that drivers must implement. - */ +"use strict"; +/*! + * Module dependencies. + */ - Collection.prototype.save = function () { - throw new Error("Collection#save unimplemented by driver"); - }; - /** - * Abstract method that drivers must implement. - */ - Collection.prototype.update = function () { - throw new Error("Collection#update unimplemented by driver"); - }; +const MongooseError = __nccwpck_require__(4327); - /** - * Abstract method that drivers must implement. - */ - Collection.prototype.getIndexes = function () { - throw new Error("Collection#getIndexes unimplemented by driver"); - }; +class StrictModeError extends MongooseError { + /** + * Strict mode error constructor + * + * @param {String} path + * @param {String} [msg] + * @param {Boolean} [immutable] + * @inherits MongooseError + * @api private + */ + constructor(path, msg, immutable) { + msg = msg || 'Field `' + path + '` is not in schema and strict ' + + 'mode is set to throw.'; + super(msg); + this.isImmutableError = !!immutable; + this.path = path; + } +} - /** - * Abstract method that drivers must implement. - */ +Object.defineProperty(StrictModeError.prototype, 'name', { + value: 'StrictModeError' +}); - Collection.prototype.mapReduce = function () { - throw new Error("Collection#mapReduce unimplemented by driver"); - }; +module.exports = StrictModeError; - /** - * Abstract method that drivers must implement. - */ - Collection.prototype.watch = function () { - throw new Error("Collection#watch unimplemented by driver"); - }; +/***/ }), - /*! - * ignore - */ +/***/ 8460: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Collection.prototype._shouldBufferCommands = - function _shouldBufferCommands() { - const opts = this.opts; +"use strict"; +/*! + * Module requirements + */ - if (opts.bufferCommands != null) { - return opts.bufferCommands; - } - if ( - opts && - opts.schemaUserProvidedOptions != null && - opts.schemaUserProvidedOptions.bufferCommands != null - ) { - return opts.schemaUserProvidedOptions.bufferCommands; - } - return this.conn._shouldBufferCommands(); - }; - /*! - * ignore - */ +const MongooseError = __nccwpck_require__(5953); +const getConstructorName = __nccwpck_require__(7323); +const util = __nccwpck_require__(1669); + +class ValidationError extends MongooseError { + /** + * Document Validation Error + * + * @api private + * @param {Document} [instance] + * @inherits MongooseError + */ + constructor(instance) { + let _message; + if (getConstructorName(instance) === 'model') { + _message = instance.constructor.modelName + ' validation failed'; + } else { + _message = 'Validation failed'; + } - Collection.prototype._getBufferTimeoutMS = - function _getBufferTimeoutMS() { - const conn = this.conn; - const opts = this.opts; + super(_message); - if (opts.bufferTimeoutMS != null) { - return opts.bufferTimeoutMS; - } - if ( - opts && - opts.schemaUserProvidedOptions != null && - opts.schemaUserProvidedOptions.bufferTimeoutMS != null - ) { - return opts.schemaUserProvidedOptions.bufferTimeoutMS; - } - if (conn.config.bufferTimeoutMS != null) { - return conn.config.bufferTimeoutMS; - } - if (conn.base != null && conn.base.get("bufferTimeoutMS") != null) { - return conn.base.get("bufferTimeoutMS"); - } - return 10000; - }; + this.errors = {}; + this._message = _message; - /*! - * Module exports. - */ + if (instance) { + instance.$errors = this.errors; + } + } - module.exports = Collection; + /** + * Console.log helper + */ + toString() { + return this.name + ': ' + _generateMessage(this); + } - /***/ - }, + /*! + * inspect helper + */ + inspect() { + return Object.assign(new Error(this.message), this); + } - /***/ 370: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const ChangeStream = __nccwpck_require__(1662); - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const Schema = __nccwpck_require__(7606); - const Collection = __nccwpck_require__(2324).get().Collection; - const STATES = __nccwpck_require__(932); - const MongooseError = __nccwpck_require__(4327); - const PromiseProvider = __nccwpck_require__(5176); - const ServerSelectionError = __nccwpck_require__(3070); - const applyPlugins = __nccwpck_require__(6990); - const promiseOrCallback = __nccwpck_require__(4046); - const get = __nccwpck_require__(8730); - const immediate = __nccwpck_require__(4830); - const mongodb = __nccwpck_require__(5517); - const pkg = __nccwpck_require__(306); - const utils = __nccwpck_require__(9232); - - const parseConnectionString = - __nccwpck_require__(3994).parseConnectionString; - - const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; - const sessionNewDocuments = __nccwpck_require__(3240).sessionNewDocuments; - - /*! - * A list of authentication mechanisms that don't require a password for authentication. - * This is used by the authMechanismDoesNotRequirePassword method. - * - * @api private - */ - const noPasswordAuthMechanisms = ["MONGODB-X509"]; - - /** - * Connection constructor - * - * For practical reasons, a Connection equals a Db. - * - * @param {Mongoose} base a mongoose instance - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `connecting`: Emitted when `connection.openUri()` is executed on this connection. - * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios. - * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models. - * @event `disconnecting`: Emitted when `connection.close()` was executed. - * @event `disconnected`: Emitted after getting disconnected from the db. - * @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models. - * @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successful connection. - * @event `error`: Emitted when an error occurs on this connection. - * @event `fullsetup`: Emitted after the driver has connected to primary and all secondaries if specified in the connection string. - * @api public - */ - - function Connection(base) { - this.base = base; - this.collections = {}; - this.models = {}; - this.config = {}; - this.replica = false; - this.options = null; - this.otherDbs = []; // FIXME: To be replaced with relatedDbs - this.relatedDbs = {}; // Hashmap of other dbs that share underlying connection - this.states = STATES; - this._readyState = STATES.disconnected; - this._closeCalled = false; - this._hasOpened = false; - this.plugins = []; - if (typeof base === "undefined" || !base.connections.length) { - this.id = 0; - } else { - this.id = base.connections.length; - } - this._queue = []; - } - - /*! - * Inherit from EventEmitter - */ - - Connection.prototype.__proto__ = EventEmitter.prototype; - - /** - * Connection ready state - * - * - 0 = disconnected - * - 1 = connected - * - 2 = connecting - * - 3 = disconnecting - * - * Each state change emits its associated event name. - * - * ####Example - * - * conn.on('connected', callback); - * conn.on('disconnected', callback); - * - * @property readyState - * @memberOf Connection - * @instance - * @api public - */ - - Object.defineProperty(Connection.prototype, "readyState", { - get: function () { - return this._readyState; - }, - set: function (val) { - if (!(val in STATES)) { - throw new Error("Invalid connection state: " + val); - } + /*! + * add message + */ + addError(path, error) { + this.errors[path] = error; + this.message = this._message + ': ' + _generateMessage(this); + } +} - if (this._readyState !== val) { - this._readyState = val; - // [legacy] loop over the otherDbs on this connection and change their state - for (const db of this.otherDbs) { - db.readyState = val; - } - if (STATES.connected === val) { - this._hasOpened = true; - } +if (util.inspect.custom) { + /*! + * Avoid Node deprecation warning DEP0079 + */ - this.emit(STATES[val]); - } - }, - }); + ValidationError.prototype[util.inspect.custom] = ValidationError.prototype.inspect; +} - /** - * Gets the value of the option `key`. Equivalent to `conn.options[key]` - * - * ####Example: - * - * conn.get('test'); // returns the 'test' value - * - * @param {String} key - * @method get - * @api public - */ +/*! + * Helper for JSON.stringify + * Ensure `name` and `message` show up in toJSON output re: gh-9847 + */ +Object.defineProperty(ValidationError.prototype, 'toJSON', { + enumerable: false, + writable: false, + configurable: true, + value: function() { + return Object.assign({}, this, { name: this.name, message: this.message }); + } +}); - Connection.prototype.get = function (key) { - if (this.config.hasOwnProperty(key)) { - return this.config[key]; - } - return get(this.options, key); - }; +Object.defineProperty(ValidationError.prototype, 'name', { + value: 'ValidationError' +}); - /** - * Sets the value of the option `key`. Equivalent to `conn.options[key] = val` - * - * Supported options include: - * - * - `maxTimeMS`: Set [`maxTimeMS`](/docs/api.html#query_Query-maxTimeMS) for all queries on this connection. - * - `useFindAndModify`: Set to `false` to work around the [`findAndModify()` deprecation warning](/docs/deprecations.html#findandmodify) - * - * ####Example: - * - * conn.set('test', 'foo'); - * conn.get('test'); // 'foo' - * conn.options.test; // 'foo' - * - * @param {String} key - * @param {Any} val - * @method set - * @api public - */ - - Connection.prototype.set = function (key, val) { - if (this.config.hasOwnProperty(key)) { - this.config[key] = val; - return val; - } +/*! + * ignore + */ - this.options = this.options || {}; - this.options[key] = val; - return val; - }; +function _generateMessage(err) { + const keys = Object.keys(err.errors || {}); + const len = keys.length; + const msgs = []; + let key; - /** - * A hash of the collections associated with this connection - * - * @property collections - * @memberOf Connection - * @instance - * @api public - */ - - Connection.prototype.collections; - - /** - * The name of the database this connection points to. - * - * ####Example - * - * mongoose.createConnection('mongodb://localhost:27017/mydb').name; // "mydb" - * - * @property name - * @memberOf Connection - * @instance - * @api public - */ - - Connection.prototype.name; - - /** - * A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing - * a map from model names to models. Contains all models that have been - * added to this connection using [`Connection#model()`](/docs/api/connection.html#connection_Connection-model). - * - * ####Example - * - * const conn = mongoose.createConnection(); - * const Test = conn.model('Test', mongoose.Schema({ name: String })); - * - * Object.keys(conn.models).length; // 1 - * conn.models.Test === Test; // true - * - * @property models - * @memberOf Connection - * @instance - * @api public - */ - - Connection.prototype.models; - - /** - * A number identifier for this connection. Used for debugging when - * you have [multiple connections](/docs/connections.html#multiple_connections). - * - * ####Example - * - * // The default connection has `id = 0` - * mongoose.connection.id; // 0 - * - * // If you create a new connection, Mongoose increments id - * const conn = mongoose.createConnection(); - * conn.id; // 1 - * - * @property id - * @memberOf Connection - * @instance - * @api public - */ - - Connection.prototype.id; - - /** - * The plugins that will be applied to all models created on this connection. - * - * ####Example: - * - * const db = mongoose.createConnection('mongodb://localhost:27017/mydb'); - * db.plugin(() => console.log('Applied')); - * db.plugins.length; // 1 - * - * db.model('Test', new Schema({})); // Prints "Applied" - * - * @property plugins - * @memberOf Connection - * @instance - * @api public - */ - - Object.defineProperty(Connection.prototype, "plugins", { - configurable: false, - enumerable: true, - writable: true, - }); + for (let i = 0; i < len; ++i) { + key = keys[i]; + if (err === err.errors[key]) { + continue; + } + msgs.push(key + ': ' + err.errors[key].message); + } - /** - * The host name portion of the URI. If multiple hosts, such as a replica set, - * this will contain the first host name in the URI - * - * ####Example - * - * mongoose.createConnection('mongodb://localhost:27017/mydb').host; // "localhost" - * - * @property host - * @memberOf Connection - * @instance - * @api public - */ - - Object.defineProperty(Connection.prototype, "host", { - configurable: true, - enumerable: true, - writable: true, - }); + return msgs.join(', '); +} - /** - * The port portion of the URI. If multiple hosts, such as a replica set, - * this will contain the port from the first host name in the URI. - * - * ####Example - * - * mongoose.createConnection('mongodb://localhost:27017/mydb').port; // 27017 - * - * @property port - * @memberOf Connection - * @instance - * @api public - */ - - Object.defineProperty(Connection.prototype, "port", { - configurable: true, - enumerable: true, - writable: true, - }); +/*! + * Module exports + */ - /** - * The username specified in the URI - * - * ####Example - * - * mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').user; // "val" - * - * @property user - * @memberOf Connection - * @instance - * @api public - */ - - Object.defineProperty(Connection.prototype, "user", { - configurable: true, - enumerable: true, - writable: true, - }); +module.exports = ValidationError; - /** - * The password specified in the URI - * - * ####Example - * - * mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').pass; // "psw" - * - * @property pass - * @memberOf Connection - * @instance - * @api public - */ - - Object.defineProperty(Connection.prototype, "pass", { - configurable: true, - enumerable: true, - writable: true, - }); - /** - * The mongodb.Db instance, set when the connection is opened - * - * @property db - * @memberOf Connection - * @instance - * @api public - */ - - Connection.prototype.db; - - /** - * The MongoClient instance this connection uses to talk to MongoDB. Mongoose automatically sets this property - * when the connection is opened. - * - * @property client - * @memberOf Connection - * @instance - * @api public - */ - - Connection.prototype.client; - - /** - * A hash of the global options that are associated with this connection - * - * @property config - * @memberOf Connection - * @instance - * @api public - */ - - Connection.prototype.config; - - /** - * Helper for `createCollection()`. Will explicitly create the given collection - * with specified options. Used to create [capped collections](https://docs.mongodb.com/manual/core/capped-collections/) - * and [views](https://docs.mongodb.com/manual/core/views/) from mongoose. - * - * Options are passed down without modification to the [MongoDB driver's `createCollection()` function](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection) - * - * @method createCollection - * @param {string} collection The collection to create - * @param {Object} [options] see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection) - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - - Connection.prototype.createCollection = _wrapConnHelper( - function createCollection(collection, options, cb) { - if (typeof options === "function") { - cb = options; - options = {}; - } - this.db.createCollection(collection, options, cb); - } - ); +/***/ }), - /** - * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) - * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), - * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). - * - * ####Example: - * - * const session = await conn.startSession(); - * let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session }); - * await doc.remove(); - * // `doc` will always be null, even if reading from a replica set - * // secondary. Without causal consistency, it is possible to - * // get a doc back from the below query if the query reads from a - * // secondary that is experiencing replication lag. - * doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' }); - * - * - * @method startSession - * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) - * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency - * @param {Function} [callback] - * @return {Promise} promise that resolves to a MongoDB driver `ClientSession` - * @api public - */ - - Connection.prototype.startSession = _wrapConnHelper(function startSession( - options, - cb - ) { - if (typeof options === "function") { - cb = options; - options = null; - } - const session = this.client.startSession(options); - cb(null, session); - }); +/***/ 6345: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * _Requires MongoDB >= 3.6.0._ Executes the wrapped async function - * in a transaction. Mongoose will commit the transaction if the - * async function executes successfully and attempt to retry if - * there was a retriable error. - * - * Calls the MongoDB driver's [`session.withTransaction()`](http://mongodb.github.io/node-mongodb-native/3.5/api/ClientSession.html#withTransaction), - * but also handles resetting Mongoose document state as shown below. - * - * ####Example: - * - * const doc = new Person({ name: 'Will Riker' }); - * await db.transaction(async function setRank(session) { - * doc.rank = 'Captain'; - * await doc.save({ session }); - * doc.isNew; // false - * - * // Throw an error to abort the transaction - * throw new Error('Oops!'); - * },{ readPreference: 'primary' }).catch(() => {}); - * - * // true, `transaction()` reset the document's state because the - * // transaction was aborted. - * doc.isNew; - * - * @method transaction - * @param {Function} fn Function to execute in a transaction - * @param {mongodb.TransactionOptions} [options] Optional settings for the transaction - * @return {Promise} promise that is fulfilled if Mongoose successfully committed the transaction, or rejects if the transaction was aborted or if Mongoose failed to commit the transaction. If fulfilled, the promise resolves to a MongoDB command result. - * @api public - */ - - Connection.prototype.transaction = function transaction(fn, options) { - return this.startSession().then((session) => { - session[sessionNewDocuments] = new Map(); - return session - .withTransaction(() => fn(session), options) - .then((res) => { - delete session[sessionNewDocuments]; - return res; - }) - .catch((err) => { - // If transaction was aborted, we need to reset newly - // inserted documents' `isNew`. - for (const doc of session[sessionNewDocuments].keys()) { - const state = session[sessionNewDocuments].get(doc); - if (state.hasOwnProperty("isNew")) { - doc.isNew = state.isNew; - } - if (state.hasOwnProperty("versionKey")) { - doc.set(doc.schema.options.versionKey, state.versionKey); - } +"use strict"; +/*! + * Module dependencies. + */ - for (const path of state.modifiedPaths) { - doc.$__.activePaths.paths[path] = "modify"; - doc.$__.activePaths.states.modify[path] = true; - } - for (const path of state.atomics.keys()) { - const val = doc.$__getValue(path); - if (val == null) { - continue; - } - val[arrayAtomicsSymbol] = state.atomics.get(path); - } - } - delete session[sessionNewDocuments]; - throw err; - }); - }); - }; - /** - * Helper for `dropCollection()`. Will delete the given collection, including - * all documents and indexes. - * - * @method dropCollection - * @param {string} collection The collection to delete - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - - Connection.prototype.dropCollection = _wrapConnHelper( - function dropCollection(collection, cb) { - this.db.dropCollection(collection, cb); - } - ); +const MongooseError = __nccwpck_require__(4327); - /** - * Helper for `dropDatabase()`. Deletes the given database, including all - * collections, documents, and indexes. - * - * ####Example: - * - * const conn = mongoose.createConnection('mongodb://localhost:27017/mydb'); - * // Deletes the entire 'mydb' database - * await conn.dropDatabase(); - * - * @method dropDatabase - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - - Connection.prototype.dropDatabase = _wrapConnHelper(function dropDatabase( - cb - ) { - // If `dropDatabase()` is called, this model's collection will not be - // init-ed. It is sufficiently common to call `dropDatabase()` after - // `mongoose.connect()` but before creating models that we want to - // support this. See gh-6967 - for (const name of Object.keys(this.models)) { - delete this.models[name].$init; - } - this.db.dropDatabase(cb); - }); - /*! - * ignore - */ - - function _wrapConnHelper(fn) { - return function () { - const cb = - arguments.length > 0 ? arguments[arguments.length - 1] : null; - const argsWithoutCb = - typeof cb === "function" - ? Array.prototype.slice.call(arguments, 0, arguments.length - 1) - : Array.prototype.slice.call(arguments); - const disconnectedError = new MongooseError( - "Connection " + - this.id + - " was disconnected when calling `" + - fn.name + - "`" - ); - return promiseOrCallback(cb, (cb) => { - // Make it ok to call collection helpers before `mongoose.connect()` - // as long as `mongoose.connect()` is called on the same tick. - // Re: gh-8534 - immediate(() => { - if ( - this.readyState === STATES.connecting && - this._shouldBufferCommands() - ) { - this._queue.push({ - fn: fn, - ctx: this, - args: argsWithoutCb.concat([cb]), - }); - } else if ( - this.readyState === STATES.disconnected && - this.db == null - ) { - cb(disconnectedError); - } else { - try { - fn.apply(this, argsWithoutCb.concat([cb])); - } catch (err) { - return cb(err); - } - } - }); - }); - }; - } +class ValidatorError extends MongooseError { + /** + * Schema validator error + * + * @param {Object} properties + * @api private + */ + constructor(properties) { + let msg = properties.message; + if (!msg) { + msg = MongooseError.messages.general.default; + } - /*! - * ignore - */ + const message = formatMessage(msg, properties); + super(message); - Connection.prototype._shouldBufferCommands = - function _shouldBufferCommands() { - if (this.config.bufferCommands != null) { - return this.config.bufferCommands; - } - if (this.base.get("bufferCommands") != null) { - return this.base.get("bufferCommands"); - } - return true; - }; + properties = Object.assign({}, properties, { message: message }); + this.properties = properties; + this.kind = properties.type; + this.path = properties.path; + this.value = properties.value; + this.reason = properties.reason; + } - /** - * error - * - * Graceful error handling, passes error to callback - * if available, else emits error on the connection. - * - * @param {Error} err - * @param {Function} callback optional - * @api private - */ - - Connection.prototype.error = function (err, callback) { - if (callback) { - callback(err); - return null; - } - if (this.listeners("error").length > 0) { - this.emit("error", err); - } - return Promise.reject(err); - }; + /*! + * toString helper + * TODO remove? This defaults to `${this.name}: ${this.message}` + */ + toString() { + return this.message; + } - /** - * Called when the connection is opened - * - * @api private - */ + /*! + * Ensure `name` and `message` show up in toJSON output re: gh-9296 + */ - Connection.prototype.onOpen = function () { - this.readyState = STATES.connected; + toJSON() { + return Object.assign({ name: this.name, message: this.message }, this); + } +} - for (const d of this._queue) { - d.fn.apply(d.ctx, d.args); - } - this._queue = []; - // avoid having the collection subscribe to our event emitter - // to prevent 0.3 warning - for (const i in this.collections) { - if (utils.object.hasOwnProperty(this.collections, i)) { - this.collections[i].onOpen(); - } - } +Object.defineProperty(ValidatorError.prototype, 'name', { + value: 'ValidatorError' +}); - this.emit("open"); - }; +/*! + * The object used to define this validator. Not enumerable to hide + * it from `require('util').inspect()` output re: gh-3925 + */ - /** - * Opens the connection with a URI using `MongoClient.connect()`. - * - * @param {String} uri The URI to connect with. - * @param {Object} [options] Passed on to http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect - * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. - * @param {Number} [options.bufferTimeoutMS=10000] Mongoose specific option. If `bufferCommands` is true, Mongoose will throw an error after `bufferTimeoutMS` if the operation is still buffered. - * @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string. - * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. - * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. - * @param {Number} [options.poolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. By default, `poolSize` is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). - * @param {Boolean} [options.useUnifiedTopology=false] False by default. Set to `true` to opt in to the MongoDB driver's replica set and sharded cluster monitoring engine. - * @param {Number} [options.serverSelectionTimeoutMS] If `useUnifiedTopology = true`, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for `serverSelectionTimeoutMS` milliseconds before erroring out. If not set, the MongoDB driver defaults to using `30000` (30 seconds). - * @param {Number} [options.heartbeatFrequencyMS] If `useUnifiedTopology = true`, the MongoDB driver sends a heartbeat every `heartbeatFrequencyMS` to check on the status of the connection. A heartbeat is subject to `serverSelectionTimeoutMS`, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a `'disconnected'` event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits `'disconnected'`. We recommend you do **not** set this setting below 1000, too many heartbeats can lead to performance degradation. - * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. - * @param {Boolean} [options.useNewUrlParser=false] False by default. Set to `true` to opt in to the MongoDB driver's new URL parser logic. - * @param {Boolean} [options.useCreateIndex=false] Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](/docs/deprecations.html#ensureindex) for automatic index builds via [`Model.init()`](/docs/api.html#model_Model.init). - * @param {Boolean} [options.useFindAndModify=true] True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`. - * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections. - * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above. - * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html). - * @param {Number} [options.bufferMaxEntries] This option does nothing if `useUnifiedTopology` is set. The MongoDB driver also has its own buffering mechanism that kicks in when the driver is disconnected. Set this option to 0 and set `bufferCommands` to `false` on your schemas if you want your database operations to fail immediately when the driver is not connected, as opposed to waiting for reconnection. - * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback). - * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes. - * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both. - * @param {Boolean} [options.autoCreate=false] Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. - * @param {Function} [callback] - * @returns {Connection} this - * @api public - */ - - Connection.prototype.openUri = function (uri, options, callback) { - if (typeof options === "function") { - callback = options; - options = null; - } - - if (["string", "number"].indexOf(typeof options) !== -1) { - throw new MongooseError( - "Mongoose 5.x no longer supports " + - "`mongoose.connect(host, dbname, port)` or " + - "`mongoose.createConnection(host, dbname, port)`. See " + - "http://mongoosejs.com/docs/connections.html for supported connection syntax" - ); - } +Object.defineProperty(ValidatorError.prototype, 'properties', { + enumerable: false, + writable: true, + value: null +}); - if (typeof uri !== "string") { - throw new MongooseError( - "The `uri` parameter to `openUri()` must be a " + - `string, got "${typeof uri}". Make sure the first parameter to ` + - "`mongoose.connect()` or `mongoose.createConnection()` is a string." - ); - } +// Exposed for testing +ValidatorError.prototype.formatMessage = formatMessage; - if (callback != null && typeof callback !== "function") { - throw new MongooseError( - "3rd parameter to `mongoose.connect()` or " + - '`mongoose.createConnection()` must be a function, got "' + - typeof callback + - '"' - ); - } +/*! + * Formats error messages + */ - if ( - this.readyState === STATES.connecting || - this.readyState === STATES.connected - ) { - if (this._connectionString !== uri) { - throw new MongooseError( - "Can't call `openUri()` on an active connection with " + - "different connection strings. Make sure you aren't calling `mongoose.connect()` " + - "multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections" - ); - } +function formatMessage(msg, properties) { + if (typeof msg === 'function') { + return msg(properties); + } - if (typeof callback === "function") { - this.$initialConnection = this.$initialConnection.then( - () => callback(null, this), - (err) => callback(err) - ); - } - return this; - } + const propertyNames = Object.keys(properties); + for (const propertyName of propertyNames) { + if (propertyName === 'message') { + continue; + } + msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]); + } - this._connectionString = uri; - this.readyState = STATES.connecting; - this._closeCalled = false; + return msg; +} - const Promise = PromiseProvider.get(); - const _this = this; +/*! + * exports + */ - if (options) { - options = utils.clone(options); - - const autoIndex = - options.config && options.config.autoIndex != null - ? options.config.autoIndex - : options.autoIndex; - if (autoIndex != null) { - this.config.autoIndex = autoIndex !== false; - delete options.config; - delete options.autoIndex; - } +module.exports = ValidatorError; - if ("autoCreate" in options) { - this.config.autoCreate = !!options.autoCreate; - delete options.autoCreate; - } - if ("useCreateIndex" in options) { - this.config.useCreateIndex = !!options.useCreateIndex; - delete options.useCreateIndex; - } - if ("useFindAndModify" in options) { - this.config.useFindAndModify = !!options.useFindAndModify; - delete options.useFindAndModify; - } +/***/ }), - // Backwards compat - if (options.user || options.pass) { - options.auth = options.auth || {}; - options.auth.user = options.user; - options.auth.password = options.pass; +/***/ 4305: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this.user = options.user; - this.pass = options.pass; - } - delete options.user; - delete options.pass; +"use strict"; - if (options.bufferCommands != null) { - if (options.bufferMaxEntries == null) { - options.bufferMaxEntries = 0; - } - this.config.bufferCommands = options.bufferCommands; - delete options.bufferCommands; - } - if (options.useMongoClient != null) { - handleUseMongoClient(options); - } - } else { - options = {}; - } +/*! + * Module dependencies. + */ - this._connectionOptions = options; - const dbName = options.dbName; - if (dbName != null) { - this.$dbName = dbName; - } - delete options.dbName; +const MongooseError = __nccwpck_require__(4327); + +class VersionError extends MongooseError { + /** + * Version Error constructor. + * + * @param {Document} doc + * @param {Number} currentVersion + * @param {Array} modifiedPaths + * @api private + */ + constructor(doc, currentVersion, modifiedPaths) { + const modifiedPathsStr = modifiedPaths.join(', '); + super('No matching document found for id "' + doc._id + + '" version ' + currentVersion + ' modifiedPaths "' + modifiedPathsStr + '"'); + this.version = currentVersion; + this.modifiedPaths = modifiedPaths; + } +} - if (!("promiseLibrary" in options)) { - options.promiseLibrary = PromiseProvider.get(); - } - if (!("useNewUrlParser" in options)) { - if ("useNewUrlParser" in this.base.options) { - options.useNewUrlParser = this.base.options.useNewUrlParser; - } else { - options.useNewUrlParser = false; - } - } - if (!utils.hasUserDefinedProperty(options, "useUnifiedTopology")) { - if ( - utils.hasUserDefinedProperty( - this.base.options, - "useUnifiedTopology" - ) - ) { - options.useUnifiedTopology = this.base.options.useUnifiedTopology; - } else { - options.useUnifiedTopology = false; - } - } - if (!utils.hasUserDefinedProperty(options, "driverInfo")) { - options.driverInfo = { - name: "Mongoose", - version: pkg.version, - }; - } - const parsePromise = new Promise((resolve, reject) => { - parseConnectionString(uri, options, (err, parsed) => { - if (err) { - return reject(err); - } - if (dbName) { - this.name = dbName; - } else if (parsed.defaultDatabase) { - this.name = parsed.defaultDatabase; - } else { - this.name = get(parsed, "auth.db", null); - } - this.host = get(parsed, "hosts.0.host", "localhost"); - this.port = get(parsed, "hosts.0.port", 27017); - this.user = this.user || get(parsed, "auth.username"); - this.pass = this.pass || get(parsed, "auth.password"); - resolve(); - }); - }); +Object.defineProperty(VersionError.prototype, 'name', { + value: 'VersionError' +}); - const promise = new Promise((resolve, reject) => { - const client = new mongodb.MongoClient(uri, options); - _this.client = client; - client.connect((error) => { - if (error) { - return reject(error); - } +/*! + * exports + */ - _setClient(_this, client, options, dbName); +module.exports = VersionError; - resolve(_this); - }); - }); - const serverSelectionError = new ServerSelectionError(); - this.$initialConnection = Promise.all([promise, parsePromise]) - .then((res) => res[0]) - .catch((err) => { - this.readyState = STATES.disconnected; - if (err != null && err.name === "MongoServerSelectionError") { - err = serverSelectionError.assimilateError(err); - } +/***/ }), - if (this.listeners("error").length > 0) { - immediate(() => this.emit("error", err)); - } - throw err; - }); - this.then = function (resolve, reject) { - return this.$initialConnection.then(() => { - if (typeof resolve === "function") { - return resolve(_this); - } - }, reject); - }; - this.catch = function (reject) { - return this.$initialConnection.catch(reject); - }; +/***/ 9337: +/***/ ((module) => { - if (callback != null) { - this.$initialConnection = this.$initialConnection.then( - () => callback(null, this), - (err) => callback(err) - ); - } +"use strict"; - return this; - }; - function _setClient(conn, client, options, dbName) { - const db = dbName != null ? client.db(dbName) : client.db(); - conn.db = db; - conn.client = client; - conn._closeCalled = client._closeCalled; - - const _handleReconnect = () => { - // If we aren't disconnected, we assume this reconnect is due to a - // socket timeout. If there's no activity on a socket for - // `socketTimeoutMS`, the driver will attempt to reconnect and emit - // this event. - if (conn.readyState !== STATES.connected) { - conn.readyState = STATES.connected; - conn.emit("reconnect"); - conn.emit("reconnected"); - conn.onOpen(); - } - }; +module.exports = function prepareDiscriminatorPipeline(pipeline, schema, prefix) { + const discriminatorMapping = schema && schema.discriminatorMapping; + prefix = prefix || ''; - // `useUnifiedTopology` events - const type = get(db, "s.topology.s.description.type", ""); - if (options.useUnifiedTopology) { - if (type === "Single") { - const server = Array.from(db.s.topology.s.servers.values())[0]; - server.s.topology.on("serverHeartbeatSucceeded", () => { - _handleReconnect(); - }); - server.s.pool.on("reconnect", () => { - _handleReconnect(); - }); - client.on("serverDescriptionChanged", (ev) => { - const newDescription = ev.newDescription; - if (newDescription.type === "Standalone") { - _handleReconnect(); - } else { - conn.readyState = STATES.disconnected; - } - }); - } else if (type.startsWith("ReplicaSet")) { - client.on("topologyDescriptionChanged", (ev) => { - // Emit disconnected if we've lost connectivity to _all_ servers - // in the replica set. - const description = ev.newDescription; - const servers = Array.from(ev.newDescription.servers.values()); - const allServersDisconnected = - description.type === "ReplicaSetNoPrimary" && - servers.reduce((cur, d) => cur || d.type === "Unknown", false); - if ( - conn.readyState === STATES.connected && - allServersDisconnected - ) { - // Implicitly emits 'disconnected' - conn.readyState = STATES.disconnected; - } else if ( - conn.readyState === STATES.disconnected && - !allServersDisconnected - ) { - _handleReconnect(); - } - }); + if (discriminatorMapping && !discriminatorMapping.isRoot) { + const originalPipeline = pipeline; + const filterKey = (prefix.length > 0 ? prefix + '.' : prefix) + discriminatorMapping.key; + const discriminatorValue = discriminatorMapping.value; - client.on("close", function () { - const type = get(db, "s.topology.s.description.type", ""); - if (type !== "ReplicaSetWithPrimary") { - // Implicitly emits 'disconnected' - conn.readyState = STATES.disconnected; - } - }); - } - } + // If the first pipeline stage is a match and it doesn't specify a `__t` + // key, add the discriminator key to it. This allows for potential + // aggregation query optimizations not to be disturbed by this feature. + if (originalPipeline[0] != null && originalPipeline[0].$match && !originalPipeline[0].$match[filterKey]) { + originalPipeline[0].$match[filterKey] = discriminatorValue; + // `originalPipeline` is a ref, so there's no need for + // aggregate._pipeline = originalPipeline + } else if (originalPipeline[0] != null && originalPipeline[0].$geoNear) { + originalPipeline[0].$geoNear.query = + originalPipeline[0].$geoNear.query || {}; + originalPipeline[0].$geoNear.query[filterKey] = discriminatorValue; + } else if (originalPipeline[0] != null && originalPipeline[0].$search) { + if (originalPipeline[1] && originalPipeline[1].$match != null) { + originalPipeline[1].$match[filterKey] = originalPipeline[1].$match[filterKey] || discriminatorValue; + } else { + const match = {}; + match[filterKey] = discriminatorValue; + originalPipeline.splice(1, 0, { $match: match }); + } + } else { + const match = {}; + match[filterKey] = discriminatorValue; + originalPipeline.unshift({ $match: match }); + } + } +}; - // Backwards compat for mongoose 4.x - db.s.topology.on("reconnectFailed", function () { - conn.emit("reconnectFailed"); - }); +/***/ }), - if (!options.useUnifiedTopology) { - client.on("reconnect", function () { - _handleReconnect(); - }); +/***/ 7765: +/***/ ((module) => { - db.s.topology.on("left", function (data) { - conn.emit("left", data); - }); - } - db.s.topology.on("joined", function (data) { - conn.emit("joined", data); - }); - db.s.topology.on("fullsetup", function (data) { - conn.emit("fullsetup", data); - }); - if (get(db, "s.topology.s.coreTopology.s.pool") != null) { - db.s.topology.s.coreTopology.s.pool.on( - "attemptReconnect", - function () { - conn.emit("attemptReconnect"); - } - ); - } - if (!options.useUnifiedTopology) { - client.on("close", function () { - // Implicitly emits 'disconnected' - conn.readyState = STATES.disconnected; - }); - } else if (!type.startsWith("ReplicaSet")) { - client.on("close", function () { - // Implicitly emits 'disconnected' - conn.readyState = STATES.disconnected; - }); - } +"use strict"; - if (!options.useUnifiedTopology) { - client.on("left", function () { - if ( - conn.readyState === STATES.connected && - get( - db, - "s.topology.s.coreTopology.s.replicaSetState.topologyType" - ) === "ReplicaSetNoPrimary" - ) { - conn.readyState = STATES.disconnected; - } - }); - client.on("timeout", function () { - conn.emit("timeout"); - }); - } +module.exports = function stringifyFunctionOperators(pipeline) { + if (!Array.isArray(pipeline)) { + return; + } - delete conn.then; - delete conn.catch; + for (const stage of pipeline) { + if (stage == null) { + continue; + } - conn.onOpen(); + const canHaveAccumulator = stage.$group || stage.$bucket || stage.$bucketAuto; + if (canHaveAccumulator != null) { + for (const key of Object.keys(canHaveAccumulator)) { + handleAccumulator(canHaveAccumulator[key]); } + } - /*! - * ignore - */ + const stageType = Object.keys(stage)[0]; + if (stageType && typeof stage[stageType] === 'object') { + const stageOptions = stage[stageType]; + for (const key of Object.keys(stageOptions)) { + if (stageOptions[key] != null && + stageOptions[key].$function != null && + typeof stageOptions[key].$function.body === 'function') { + stageOptions[key].$function.body = stageOptions[key].$function.body.toString(); + } + } + } - const handleUseMongoClient = function handleUseMongoClient(options) { - console.warn( - "WARNING: The `useMongoClient` option is no longer " + - "necessary in mongoose 5.x, please remove it." - ); - const stack = new Error().stack; - console.warn(stack.substr(stack.indexOf("\n") + 1)); - delete options.useMongoClient; - }; + if (stage.$facet != null) { + for (const key of Object.keys(stage.$facet)) { + stringifyFunctionOperators(stage.$facet[key]); + } + } + } +}; - /** - * Closes the connection - * - * @param {Boolean} [force] optional - * @param {Function} [callback] optional - * @return {Promise} - * @api public - */ +function handleAccumulator(operator) { + if (operator == null || operator.$accumulator == null) { + return; + } - Connection.prototype.close = function (force, callback) { - if (typeof force === "function") { - callback = force; - force = false; - } + for (const key of ['init', 'accumulate', 'merge', 'finalize']) { + if (typeof operator.$accumulator[key] === 'function') { + operator.$accumulator[key] = String(operator.$accumulator[key]); + } + } +} - this.$wasForceClosed = !!force; +/***/ }), - return promiseOrCallback(callback, (cb) => { - this._close(force, cb); - }); - }; +/***/ 8906: +/***/ ((module) => { - /** - * Handles closing the connection - * - * @param {Boolean} force - * @param {Function} callback - * @api private - */ - Connection.prototype._close = function (force, callback) { - const _this = this; - const closeCalled = this._closeCalled; - this._closeCalled = true; - if (this.client != null) { - this.client._closeCalled = true; - } +"use strict"; - switch (this.readyState) { - case STATES.disconnected: - if (closeCalled) { - callback(); - } else { - this.doClose(force, function (err) { - if (err) { - return callback(err); - } - _this.onClose(force); - callback(null); - }); - } - break; - case STATES.connected: - this.readyState = STATES.disconnecting; - this.doClose(force, function (err) { - if (err) { - return callback(err); - } - _this.onClose(force); - callback(null); - }); +module.exports = arrayDepth; - break; - case STATES.connecting: - this.once("open", function () { - _this.close(callback); - }); - break; +function arrayDepth(arr) { + if (!Array.isArray(arr)) { + return { min: 0, max: 0, containsNonArrayItem: true }; + } + if (arr.length === 0) { + return { min: 1, max: 1, containsNonArrayItem: false }; + } + if (arr.length === 1 && !Array.isArray(arr[0])) { + return { min: 1, max: 1, containsNonArrayItem: false }; + } - case STATES.disconnecting: - this.once("close", function () { - callback(); - }); - break; - } + const res = arrayDepth(arr[0]); - return this; - }; + for (let i = 1; i < arr.length; ++i) { + const _res = arrayDepth(arr[i]); + if (_res.min < res.min) { + res.min = _res.min; + } + if (_res.max > res.max) { + res.max = _res.max; + } + res.containsNonArrayItem = res.containsNonArrayItem || _res.containsNonArrayItem; + } - /** - * Called when the connection closes - * - * @api private - */ + res.min = res.min + 1; + res.max = res.max + 1; - Connection.prototype.onClose = function (force) { - this.readyState = STATES.disconnected; + return res; +} - // avoid having the collection subscribe to our event emitter - // to prevent 0.3 warning - for (const i in this.collections) { - if (utils.object.hasOwnProperty(this.collections, i)) { - this.collections[i].onClose(force); - } - } +/***/ }), - this.emit("close", force); - }; +/***/ 5092: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Retrieves a collection, creating it if not cached. - * - * Not typically needed by applications. Just talk to your collection through your model. - * - * @param {String} name of the collection - * @param {Object} [options] optional collection options - * @return {Collection} collection instance - * @api public - */ - - Connection.prototype.collection = function (name, options) { - const defaultOptions = { - autoIndex: - this.config.autoIndex != null - ? this.config.autoIndex - : this.base.options.autoIndex, - autoCreate: - this.config.autoCreate != null - ? this.config.autoCreate - : this.base.options.autoCreate, - }; - options = Object.assign( - {}, - defaultOptions, - options ? utils.clone(options) : {} - ); - options.$wasForceClosed = this.$wasForceClosed; - if (!(name in this.collections)) { - this.collections[name] = new Collection(name, this, options); - } - return this.collections[name]; - }; +"use strict"; - /** - * Declares a plugin executed on all schemas you pass to `conn.model()` - * - * Equivalent to calling `.plugin(fn)` on each schema you create. - * - * ####Example: - * const db = mongoose.createConnection('mongodb://localhost:27017/mydb'); - * db.plugin(() => console.log('Applied')); - * db.plugins.length; // 1 - * - * db.model('Test', new Schema({})); // Prints "Applied" - * - * @param {Function} fn plugin callback - * @param {Object} [opts] optional options - * @return {Connection} this - * @see plugins ./plugins.html - * @api public - */ - - Connection.prototype.plugin = function (fn, opts) { - this.plugins.push([fn, opts]); - return this; - }; - /** - * Defines or retrieves a model. - * - * const mongoose = require('mongoose'); - * const db = mongoose.createConnection(..); - * db.model('Venue', new Schema(..)); - * const Ticket = db.model('Ticket', new Schema(..)); - * const Venue = db.model('Venue'); - * - * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._ - * - * ####Example: - * - * const schema = new Schema({ name: String }, { collection: 'actor' }); - * - * // or - * - * schema.set('collection', 'actor'); - * - * // or - * - * const collectionName = 'actor' - * const M = conn.model('Actor', schema, collectionName) - * - * @param {String|Function} name the model name or class extending Model - * @param {Schema} [schema] a schema. necessary when defining a model - * @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name - * @param {Object} [options] - * @param {Boolean} [options.overwriteModels=false] If true, overwrite existing models with the same name to avoid `OverwriteModelError` - * @see Mongoose#model #index_Mongoose-model - * @return {Model} The compiled model - * @api public - */ - - Connection.prototype.model = function ( - name, - schema, - collection, - options - ) { - if (!(this instanceof Connection)) { - throw new MongooseError( - "`connection.model()` should not be run with " + - "`new`. If you are doing `new db.model(foo)(bar)`, use " + - "`db.model(foo)(bar)` instead" - ); - } - let fn; - if (typeof name === "function") { - fn = name; - name = fn.name; - } +const cloneRegExp = __nccwpck_require__(8292); +const Decimal = __nccwpck_require__(8319); +const ObjectId = __nccwpck_require__(2706); +const specialProperties = __nccwpck_require__(6786); +const isMongooseObject = __nccwpck_require__(7104); +const getFunctionName = __nccwpck_require__(6621); +const isBsonType = __nccwpck_require__(8275); +const isObject = __nccwpck_require__(273); +const symbols = __nccwpck_require__(3240); +const trustedSymbol = __nccwpck_require__(7776).trustedSymbol; +const utils = __nccwpck_require__(9232); - // collection name discovery - if (typeof schema === "string") { - collection = schema; - schema = false; - } - if (utils.isObject(schema) && !schema.instanceOfSchema) { - schema = new Schema(schema); - } - if (schema && !schema.instanceOfSchema) { - throw new Error( - "The 2nd parameter to `mongoose.model()` should be a " + - "schema or a POJO" - ); - } +/*! + * Object clone with Mongoose natives support. + * + * If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible. + * + * Functions are never cloned. + * + * @param {Object} obj the object to clone + * @param {Object} options + * @param {Boolean} isArrayChild true if cloning immediately underneath an array. Special case for minimize. + * @return {Object} the cloned object + * @api private + */ - const defaultOptions = { - cache: false, - overwriteModels: this.base.options.overwriteModels, - }; - const opts = Object.assign(defaultOptions, options, { - connection: this, - }); - if (this.models[name] && !collection && opts.overwriteModels !== true) { - // model exists but we are not subclassing with custom collection - if ( - schema && - schema.instanceOfSchema && - schema !== this.models[name].schema - ) { - throw new MongooseError.OverwriteModelError(name); - } - return this.models[name]; - } +function clone(obj, options, isArrayChild) { + if (obj == null) { + return obj; + } - let model; + if (Array.isArray(obj)) { + return cloneArray(obj, options); + } - if (schema && schema.instanceOfSchema) { - applyPlugins(schema, this.plugins, null, "$connectionPluginsApplied"); + if (isMongooseObject(obj)) { + // Single nested subdocs should apply getters later in `applyGetters()` + // when calling `toObject()`. See gh-7442, gh-8295 + if (options && options._skipSingleNestedGetters && obj.$isSingleNested) { + options = Object.assign({}, options, { getters: false }); + } - // compile a model - model = this.base.model(fn || name, schema, collection, opts); + if (utils.isPOJO(obj) && obj.$__ != null && obj._doc != null) { + return obj._doc; + } - // only the first model with this name is cached to allow - // for one-offs with custom collection names etc. - if (!this.models[name]) { - this.models[name] = model; - } + if (options && options.json && typeof obj.toJSON === 'function') { + return obj.toJSON(options); + } + return obj.toObject(options); + } - // Errors handled internally, so safe to ignore error - model.init(function $modelInitNoop() {}); + if (obj.constructor) { + switch (getFunctionName(obj.constructor)) { + case 'Object': + return cloneObject(obj, options, isArrayChild); + case 'Date': + return new obj.constructor(+obj); + case 'RegExp': + return cloneRegExp(obj); + default: + // ignore + break; + } + } - return model; - } + if (obj instanceof ObjectId) { + return new ObjectId(obj.id); + } - if (this.models[name] && collection) { - // subclassing current model with alternate collection - model = this.models[name]; - schema = model.prototype.schema; - const sub = model.__subclass(this, schema, collection); - // do not cache the sub model - return sub; - } + if (isBsonType(obj, 'Decimal128')) { + if (options && options.flattenDecimals) { + return obj.toJSON(); + } + return Decimal.fromString(obj.toString()); + } - // lookup model in mongoose module - model = this.base.models[name]; + if (!obj.constructor && isObject(obj)) { + // object created with Object.create(null) + return cloneObject(obj, options, isArrayChild); + } - if (!model) { - throw new MongooseError.MissingSchemaError(name); - } + if (obj[symbols.schemaTypeSymbol]) { + return obj.clone(); + } - if ( - this === model.prototype.db && - (!collection || collection === model.collection.name) - ) { - // model already uses this connection. + // If we're cloning this object to go into a MongoDB command, + // and there's a `toBSON()` function, assume this object will be + // stored as a primitive in MongoDB and doesn't need to be cloned. + if (options && options.bson && typeof obj.toBSON === 'function') { + return obj; + } - // only the first model with this name is cached to allow - // for one-offs with custom collection names etc. - if (!this.models[name]) { - this.models[name] = model; - } + if (obj.valueOf != null) { + return obj.valueOf(); + } - return model; - } - this.models[name] = model.__subclass(this, schema, collection); - return this.models[name]; - }; + return cloneObject(obj, options, isArrayChild); +} +module.exports = clone; - /** - * Removes the model named `name` from this connection, if it exists. You can - * use this function to clean up any models you created in your tests to - * prevent OverwriteModelErrors. - * - * ####Example: - * - * conn.model('User', new Schema({ name: String })); - * console.log(conn.model('User')); // Model object - * conn.deleteModel('User'); - * console.log(conn.model('User')); // undefined - * - * // Usually useful in a Mocha `afterEach()` hook - * afterEach(function() { - * conn.deleteModel(/.+/); // Delete every model - * }); - * - * @api public - * @param {String|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. - * @return {Connection} this - */ - - Connection.prototype.deleteModel = function (name) { - if (typeof name === "string") { - const model = this.model(name); - if (model == null) { - return this; - } - const collectionName = model.collection.name; - delete this.models[name]; - delete this.collections[collectionName]; - delete this.base.modelSchemas[name]; - - this.emit("deleteModel", model); - } else if (name instanceof RegExp) { - const pattern = name; - const names = this.modelNames(); - for (const name of names) { - if (pattern.test(name)) { - this.deleteModel(name); - } - } - } else { - throw new Error( - "First parameter to `deleteModel()` must be a string " + - 'or regexp, got "' + - name + - '"' - ); - } +/*! + * ignore + */ - return this; - }; +function cloneObject(obj, options, isArrayChild) { + const minimize = options && options.minimize; + const ret = {}; + let hasKeys; - /** - * Watches the entire underlying database for changes. Similar to - * [`Model.watch()`](/docs/api/model.html#model_Model.watch). - * - * This function does **not** trigger any middleware. In particular, it - * does **not** trigger aggregate middleware. - * - * The ChangeStream object is an event emitter that emits the following events: - * - * - 'change': A change occurred, see below example - * - 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow [this GitHub issue](https://github.com/Automattic/mongoose/issues/6799) for updates. - * - 'end': Emitted if the underlying stream is closed - * - 'close': Emitted if the underlying stream is closed - * - * ####Example: - * - * const User = conn.model('User', new Schema({ name: String })); - * - * const changeStream = conn.watch().on('change', data => console.log(data)); - * - * // Triggers a 'change' event on the change stream. - * await User.create({ name: 'test' }); - * - * @api public - * @param {Array} [pipeline] - * @param {Object} [options] passed without changes to [the MongoDB driver's `Db#watch()` function](https://mongodb.github.io/node-mongodb-native/3.4/api/Db.html#watch) - * @return {ChangeStream} mongoose-specific change stream wrapper, inherits from EventEmitter - */ - - Connection.prototype.watch = function (pipeline, options) { - const disconnectedError = new MongooseError( - "Connection " + this.id + " was disconnected when calling `watch()`" - ); + if (obj[trustedSymbol]) { + ret[trustedSymbol] = obj[trustedSymbol]; + } - const changeStreamThunk = (cb) => { - immediate(() => { - if (this.readyState === STATES.connecting) { - this.once("open", function () { - const driverChangeStream = this.db.watch(pipeline, options); - cb(null, driverChangeStream); - }); - } else if ( - this.readyState === STATES.disconnected && - this.db == null - ) { - cb(disconnectedError); - } else { - const driverChangeStream = this.db.watch(pipeline, options); - cb(null, driverChangeStream); - } - }); - }; + for (const k of Object.keys(obj)) { + if (specialProperties.has(k)) { + continue; + } - const changeStream = new ChangeStream( - changeStreamThunk, - pipeline, - options - ); - return changeStream; - }; + // Don't pass `isArrayChild` down + const val = clone(obj[k], options); - /** - * Returns an array of model names created on this connection. - * @api public - * @return {Array} - */ + if (!minimize || (typeof val !== 'undefined')) { + if (minimize === false && typeof val === 'undefined') { + delete ret[k]; + } else { + hasKeys || (hasKeys = true); + ret[k] = val; + } + } + } - Connection.prototype.modelNames = function () { - return Object.keys(this.models); - }; + return minimize && !isArrayChild ? hasKeys && ret : ret; +} - /** - * @brief Returns if the connection requires authentication after it is opened. Generally if a - * username and password are both provided than authentication is needed, but in some cases a - * password is not required. - * @api private - * @return {Boolean} true if the connection should be authenticated after it is opened, otherwise false. - */ - Connection.prototype.shouldAuthenticate = function () { - return ( - this.user != null && - (this.pass != null || this.authMechanismDoesNotRequirePassword()) - ); - }; +function cloneArray(arr, options) { + const ret = []; - /** - * @brief Returns a boolean value that specifies if the current authentication mechanism needs a - * password to authenticate according to the auth objects passed into the openUri methods. - * @api private - * @return {Boolean} true if the authentication mechanism specified in the options object requires - * a password, otherwise false. - */ - Connection.prototype.authMechanismDoesNotRequirePassword = function () { - if (this.options && this.options.auth) { - return ( - noPasswordAuthMechanisms.indexOf(this.options.auth.authMechanism) >= - 0 - ); - } - return true; - }; + for (const item of arr) { + ret.push(clone(item, options, true)); + } - /** - * @brief Returns a boolean value that specifies if the provided objects object provides enough - * data to authenticate with. Generally this is true if the username and password are both specified - * but in some authentication methods, a password is not required for authentication so only a username - * is required. - * @param {Object} [options] the options object passed into the openUri methods. - * @api private - * @return {Boolean} true if the provided options object provides enough data to authenticate with, - * otherwise false. - */ - Connection.prototype.optionsProvideAuthenticationData = function ( - options - ) { - return ( - options && - options.user && - (options.pass || this.authMechanismDoesNotRequirePassword()) - ); - }; + return ret; +} - /** - * Returns the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance - * that this connection uses to talk to MongoDB. - * - * ####Example: - * const conn = await mongoose.createConnection('mongodb://localhost:27017/test'); - * - * conn.getClient(); // MongoClient { ... } - * - * @api public - * @return {MongoClient} - */ - - Connection.prototype.getClient = function getClient() { - return this.client; - }; +/***/ }), - /** - * Set the [MongoDB driver `MongoClient`](http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html) instance - * that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to - * reuse it. - * - * ####Example: - * const client = await mongodb.MongoClient.connect('mongodb://localhost:27017/test'); - * - * const conn = mongoose.createConnection().setClient(client); - * - * conn.getClient(); // MongoClient { ... } - * conn.readyState; // 1, means 'CONNECTED' - * - * @api public - * @return {Connection} this - */ - - Connection.prototype.setClient = function setClient(client) { - if (!(client instanceof mongodb.MongoClient)) { - throw new MongooseError( - "Must call `setClient()` with an instance of MongoClient" - ); - } - if (this.client != null || this.readyState !== STATES.disconnected) { - throw new MongooseError( - "Cannot call `setClient()` on a connection that is already connected." - ); - } - if (!client.isConnected()) { - throw new MongooseError( - "Cannot call `setClient()` with a MongoClient that is not connected." - ); - } +/***/ 3719: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this._connectionString = client.s.url; - _setClient( - this, - client, - { useUnifiedTopology: client.s.options.useUnifiedTopology }, - client.s.options.dbName - ); +"use strict"; - return this; - }; - /** - * Switches to a different database using the same connection pool. - * - * Returns a new connection object, with the new db. - * - * @method useDb - * @memberOf Connection - * @param {String} name The database name - * @param {Object} [options] - * @param {Boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object. - * @param {Boolean} [options.noListener=false] If true, the connection object will not make the db listen to events on the original connection. See [issue #9961](https://github.com/Automattic/mongoose/issues/9961). - * @return {Connection} New Connection Object - * @api public - */ - - /*! - * Module exports. - */ - - Connection.STATES = STATES; - module.exports = Connection; - - /***/ - }, +/*! + * Module dependencies. + */ - /***/ 932: /***/ (module, exports) => { - "use strict"; +const Binary = __nccwpck_require__(2324).get().Binary; +const Decimal128 = __nccwpck_require__(8319); +const ObjectId = __nccwpck_require__(2706); +const isMongooseObject = __nccwpck_require__(7104); - /*! - * Connection states - */ +exports.x = flatten; +exports.M = modifiedPaths; - const STATES = (module.exports = exports = Object.create(null)); +/*! + * ignore + */ - const disconnected = "disconnected"; - const connected = "connected"; - const connecting = "connecting"; - const disconnecting = "disconnecting"; - const uninitialized = "uninitialized"; +function flatten(update, path, options, schema) { + let keys; + if (update && isMongooseObject(update) && !Buffer.isBuffer(update)) { + keys = Object.keys(update.toObject({ transform: false, virtuals: false }) || {}); + } else { + keys = Object.keys(update || {}); + } - STATES[0] = disconnected; - STATES[1] = connected; - STATES[2] = connecting; - STATES[3] = disconnecting; - STATES[99] = uninitialized; + const numKeys = keys.length; + const result = {}; + path = path ? path + '.' : ''; - STATES[disconnected] = 0; - STATES[connected] = 1; - STATES[connecting] = 2; - STATES[disconnecting] = 3; - STATES[uninitialized] = 99; + for (let i = 0; i < numKeys; ++i) { + const key = keys[i]; + const val = update[key]; + result[path + key] = val; - /***/ - }, + // Avoid going into mixed paths if schema is specified + const keySchema = schema && schema.path && schema.path(path + key); + const isNested = schema && schema.nested && schema.nested[path + key]; + if (keySchema && keySchema.instance === 'Mixed') continue; - /***/ 5398: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ - - const MongooseError = __nccwpck_require__(5953); - const Readable = __nccwpck_require__(2413).Readable; - const promiseOrCallback = __nccwpck_require__(4046); - const eachAsync = __nccwpck_require__(9893); - const immediate = __nccwpck_require__(4830); - const util = __nccwpck_require__(1669); - - /** - * An AggregationCursor is a concurrency primitive for processing aggregation - * results one document at a time. It is analogous to QueryCursor. - * - * An AggregationCursor fulfills the Node.js streams3 API, - * in addition to several other mechanisms for loading documents from MongoDB - * one at a time. - * - * Creating an AggregationCursor executes the model's pre aggregate hooks, - * but **not** the model's post aggregate hooks. - * - * Unless you're an advanced user, do **not** instantiate this class directly. - * Use [`Aggregate#cursor()`](/docs/api.html#aggregate_Aggregate-cursor) instead. - * - * @param {Aggregate} agg - * @param {Object} options - * @inherits Readable - * @event `cursor`: Emitted when the cursor is created - * @event `error`: Emitted when an error occurred - * @event `data`: Emitted when the stream is flowing and the next doc is ready - * @event `end`: Emitted when the stream is exhausted - * @api public - */ - - function AggregationCursor(agg) { - Readable.call(this, { objectMode: true }); - - this.cursor = null; - this.agg = agg; - this._transforms = []; - const model = agg._model; - delete agg.options.cursor.useMongooseAggCursor; - this._mongooseOptions = {}; - - _init(model, this, agg); - } - - util.inherits(AggregationCursor, Readable); - - /*! - * ignore - */ - - function _init(model, c, agg) { - if (!model.collection.buffer) { - model.hooks.execPre("aggregate", agg, function () { - c.cursor = model.collection.aggregate( - agg._pipeline, - agg.options || {} - ); - c.emit("cursor", c.cursor); - }); - } else { - model.collection.emitter.once("queue", function () { - model.hooks.execPre("aggregate", agg, function () { - c.cursor = model.collection.aggregate( - agg._pipeline, - agg.options || {} - ); - c.emit("cursor", c.cursor); - }); - }); - } + if (shouldFlatten(val)) { + if (options && options.skipArrays && Array.isArray(val)) { + continue; + } + const flat = flatten(val, path + key, options, schema); + for (const k in flat) { + result[k] = flat[k]; } + if (Array.isArray(val)) { + result[path + key] = val; + } + } - /*! - * Necessary to satisfy the Readable API - */ + if (isNested) { + const paths = Object.keys(schema.paths); + for (const p of paths) { + if (p.startsWith(path + key + '.') && !result.hasOwnProperty(p)) { + result[p] = void 0; + } + } + } + } - AggregationCursor.prototype._read = function () { - const _this = this; - _next(this, function (error, doc) { - if (error) { - return _this.emit("error", error); - } - if (!doc) { - _this.push(null); - _this.cursor.close(function (error) { - if (error) { - return _this.emit("error", error); - } - setTimeout(function () { - // on node >= 14 streams close automatically (gh-8834) - const isNotClosedAutomatically = !_this.destroyed; - if (isNotClosedAutomatically) { - _this.emit("close"); - } - }, 0); - }); - return; - } - _this.push(doc); - }); - }; + return result; +} - if (Symbol.asyncIterator != null) { - const msg = - "Mongoose does not support using async iterators with an " + - "existing aggregation cursor. See http://bit.ly/mongoose-async-iterate-aggregation"; +/*! + * ignore + */ - AggregationCursor.prototype[Symbol.asyncIterator] = function () { - throw new MongooseError(msg); - }; +function modifiedPaths(update, path, result) { + const keys = Object.keys(update || {}); + const numKeys = keys.length; + result = result || {}; + path = path ? path + '.' : ''; + + for (let i = 0; i < numKeys; ++i) { + const key = keys[i]; + let val = update[key]; + + const _path = path + key; + result[_path] = true; + if (_path.indexOf('.') !== -1) { + const sp = _path.split('.'); + let cur = sp[0]; + for (let i = 1; i < sp.length; ++i) { + result[cur] = true; + cur += '.' + sp[i]; } + } + if (isMongooseObject(val) && !Buffer.isBuffer(val)) { + val = val.toObject({ transform: false, virtuals: false }); + } + if (shouldFlatten(val)) { + modifiedPaths(val, path + key, result); + } + } - /** - * Registers a transform function which subsequently maps documents retrieved - * via the streams interface or `.next()` - * - * ####Example - * - * // Map documents returned by `data` events - * Thing. - * find({ name: /^hello/ }). - * cursor(). - * map(function (doc) { - * doc.foo = "bar"; - * return doc; - * }) - * on('data', function(doc) { console.log(doc.foo); }); - * - * // Or map documents returned by `.next()` - * const cursor = Thing.find({ name: /^hello/ }). - * cursor(). - * map(function (doc) { - * doc.foo = "bar"; - * return doc; - * }); - * cursor.next(function(error, doc) { - * console.log(doc.foo); - * }); - * - * @param {Function} fn - * @return {AggregationCursor} - * @api public - * @method map - */ - - AggregationCursor.prototype.map = function (fn) { - this._transforms.push(fn); - return this; - }; - - /*! - * Marks this cursor as errored - */ + return result; +} - AggregationCursor.prototype._markError = function (error) { - this._error = error; - return this; - }; +/*! + * ignore + */ - /** - * Marks this cursor as closed. Will stop streaming and subsequent calls to - * `next()` will error. - * - * @param {Function} callback - * @return {Promise} - * @api public - * @method close - * @emits close - * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close - */ - - AggregationCursor.prototype.close = function (callback) { - return promiseOrCallback(callback, (cb) => { - this.cursor.close((error) => { - if (error) { - cb(error); - return ( - this.listeners("error").length > 0 && this.emit("error", error) - ); - } - this.emit("close"); - cb(null); - }); - }); - }; +function shouldFlatten(val) { + return val && + typeof val === 'object' && + !(val instanceof Date) && + !(val instanceof ObjectId) && + (!Array.isArray(val) || val.length > 0) && + !(val instanceof Buffer) && + !(val instanceof Decimal128) && + !(val instanceof Binary); +} - /** - * Get the next document from this cursor. Will return `null` when there are - * no documents left. - * - * @param {Function} callback - * @return {Promise} - * @api public - * @method next - */ - - AggregationCursor.prototype.next = function (callback) { - return promiseOrCallback(callback, (cb) => { - _next(this, cb); - }); - }; - /** - * Execute `fn` for every document in the cursor. If `fn` returns a promise, - * will wait for the promise to resolve before iterating on to the next one. - * Returns a promise that resolves when done. - * - * @param {Function} fn - * @param {Object} [options] - * @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1. - * @param {Function} [callback] executed when all docs have been processed - * @return {Promise} - * @api public - * @method eachAsync - */ - - AggregationCursor.prototype.eachAsync = function (fn, opts, callback) { - const _this = this; - if (typeof opts === "function") { - callback = opts; - opts = {}; - } - opts = opts || {}; +/***/ }), - return eachAsync( - function (cb) { - return _next(_this, cb); - }, - fn, - opts, - callback - ); - }; +/***/ 9893: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js - * You do not need to call this function explicitly, the JavaScript runtime - * will call it for you. - * - * ####Example - * - * // Async iterator without explicitly calling `cursor()`. Mongoose still - * // creates an AggregationCursor instance internally. - * const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]); - * for await (const doc of agg) { - * console.log(doc.name); - * } - * - * // You can also use an AggregationCursor instance for async iteration - * const cursor = Model.aggregate([{ $match: { age: { $gte: 25 } } }]).cursor(); - * for await (const doc of cursor) { - * console.log(doc.name); - * } - * - * Node.js 10.x supports async iterators natively without any flags. You can - * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). - * - * **Note:** This function is not set if `Symbol.asyncIterator` is undefined. If - * `Symbol.asyncIterator` is undefined, that means your Node.js version does not - * support async iterators. - * - * @method Symbol.asyncIterator - * @memberOf AggregationCursor - * @instance - * @api public - */ - - if (Symbol.asyncIterator != null) { - AggregationCursor.prototype[Symbol.asyncIterator] = function () { - return this.transformNull()._transformForAsyncIterator(); - }; - } +"use strict"; - /*! - * ignore - */ - AggregationCursor.prototype._transformForAsyncIterator = function () { - if (this._transforms.indexOf(_transformForAsyncIterator) === -1) { - this.map(_transformForAsyncIterator); - } - return this; - }; +/*! + * Module dependencies. + */ - /*! - * ignore - */ +const immediate = __nccwpck_require__(4830); +const promiseOrCallback = __nccwpck_require__(4046); - AggregationCursor.prototype.transformNull = function (val) { - if (arguments.length === 0) { - val = true; - } - this._mongooseOptions.transformNull = val; - return this; - }; +/** + * Execute `fn` for every document in the cursor. If `fn` returns a promise, + * will wait for the promise to resolve before iterating on to the next one. + * Returns a promise that resolves when done. + * + * @param {Function} next the thunk to call to get the next document + * @param {Function} fn + * @param {Object} options + * @param {Function} [callback] executed when all docs have been processed + * @return {Promise} + * @api public + * @method eachAsync + */ - /*! - * ignore - */ +module.exports = function eachAsync(next, fn, options, callback) { + const parallel = options.parallel || 1; + const batchSize = options.batchSize; + const enqueue = asyncQueue(); - function _transformForAsyncIterator(doc) { - return doc == null ? { done: true } : { value: doc, done: false }; + return promiseOrCallback(callback, cb => { + if (batchSize != null) { + if (typeof batchSize !== 'number') { + throw new TypeError('batchSize must be a number'); + } + if (batchSize < 1) { + throw new TypeError('batchSize must be at least 1'); } + if (batchSize !== Math.floor(batchSize)) { + throw new TypeError('batchSize must be a positive integer'); + } + } - /** - * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag). - * Useful for setting the `noCursorTimeout` and `tailable` flags. - * - * @param {String} flag - * @param {Boolean} value - * @return {AggregationCursor} this - * @api public - * @method addCursorFlag - */ + iterate(cb); + }); - AggregationCursor.prototype.addCursorFlag = function (flag, value) { - const _this = this; - _waitForCursor(this, function () { - _this.cursor.addCursorFlag(flag, value); - }); - return this; - }; + function iterate(finalCallback) { + let drained = false; + let handleResultsInProgress = 0; + let currentDocumentIndex = 0; + let documentsBatch = []; - /*! - * ignore - */ + let error = null; + for (let i = 0; i < parallel; ++i) { + enqueue(fetch); + } - function _waitForCursor(ctx, cb) { - if (ctx.cursor) { - return cb(); - } - ctx.once("cursor", function () { - cb(); - }); + function fetch(done) { + if (drained || error) { + return done(); } - /*! - * Get the next doc from the underlying cursor and mongooseify it - * (populate, etc.) - */ - - function _next(ctx, cb) { - let callback = cb; - if (ctx._transforms.length) { - callback = function (err, doc) { - if (err || (doc === null && !ctx._mongooseOptions.transformNull)) { - return cb(err, doc); - } - cb( - err, - ctx._transforms.reduce(function (doc, fn) { - return fn(doc); - }, doc) - ); - }; + next(function(err, doc) { + if (drained || error != null) { + return done(); } - - if (ctx._error) { - return immediate(function () { - callback(ctx._error); - }); + if (err != null) { + error = err; + finalCallback(err); + return done(); + } + if (doc == null) { + drained = true; + if (handleResultsInProgress <= 0) { + finalCallback(null); + } else if (batchSize != null && documentsBatch.length) { + handleNextResult(documentsBatch, currentDocumentIndex++, handleNextResultCallBack); + } + return done(); } - if (ctx.cursor) { - return ctx.cursor.next(function (error, doc) { - if (error) { - return callback(error); - } - if (!doc) { - return callback(null, null); - } + ++handleResultsInProgress; - callback(null, doc); - }); - } else { - ctx.once("cursor", function () { - _next(ctx, cb); - }); - } - } + // Kick off the subsequent `next()` before handling the result, but + // make sure we know that we still have a result to handle re: #8422 + immediate(() => done()); - module.exports = AggregationCursor; + if (batchSize != null) { + documentsBatch.push(doc); + } - /***/ - }, + // If the current documents size is less than the provided patch size don't process the documents yet + if (batchSize != null && documentsBatch.length !== batchSize) { + setTimeout(() => enqueue(fetch), 0); + return; + } - /***/ 1662: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + const docsToProcess = batchSize != null ? documentsBatch : doc; - /*! - * Module dependencies. - */ + function handleNextResultCallBack(err) { + if (batchSize != null) { + handleResultsInProgress -= documentsBatch.length; + documentsBatch = []; + } else { + --handleResultsInProgress; + } + if (err != null) { + error = err; + return finalCallback(err); + } + if (drained && handleResultsInProgress <= 0) { + return finalCallback(null); + } - const EventEmitter = __nccwpck_require__(8614).EventEmitter; + setTimeout(() => enqueue(fetch), 0); + } - /*! - * ignore - */ + handleNextResult(docsToProcess, currentDocumentIndex++, handleNextResultCallBack); + }); + } + } - class ChangeStream extends EventEmitter { - constructor(changeStreamThunk, pipeline, options) { - super(); + function handleNextResult(doc, i, callback) { + const promise = fn(doc, i); + if (promise && typeof promise.then === 'function') { + promise.then( + function() { callback(null); }, + function(error) { callback(error || new Error('`eachAsync()` promise rejected without error')); }); + } else { + callback(null); + } + } +}; + +// `next()` can only execute one at a time, so make sure we always execute +// `next()` in series, while still allowing multiple `fn()` instances to run +// in parallel. +function asyncQueue() { + const _queue = []; + let inProgress = null; + let id = 0; + + return function enqueue(fn) { + if (_queue.length === 0 && inProgress == null) { + inProgress = id++; + return fn(_step); + } + _queue.push(fn); + }; - this.driverChangeStream = null; - this.closed = false; - this.pipeline = pipeline; - this.options = options; + function _step() { + inProgress = null; + if (_queue.length > 0) { + inProgress = id++; + const fn = _queue.shift(); + fn(_step); + } + } +} - // This wrapper is necessary because of buffering. - changeStreamThunk((err, driverChangeStream) => { - if (err != null) { - this.emit("error", err); - return; - } - this.driverChangeStream = driverChangeStream; - this._bindEvents(); - this.emit("ready"); - }); - } +/***/ }), - _bindEvents() { - this.driverChangeStream.on("close", () => { - this.closed = true; - }); +/***/ 9295: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - ["close", "change", "end", "error"].forEach((ev) => { - this.driverChangeStream.on(ev, (data) => this.emit(ev, data)); - }); - } +"use strict"; - _queue(cb) { - this.once("ready", () => cb()); - } - close() { - this.closed = true; - if (this.driverChangeStream) { - this.driverChangeStream.close(); - } - } - } +const ObjectId = __nccwpck_require__(2706); - /*! - * ignore - */ +module.exports = function areDiscriminatorValuesEqual(a, b) { + if (typeof a === 'string' && typeof b === 'string') { + return a === b; + } + if (typeof a === 'number' && typeof b === 'number') { + return a === b; + } + if (a instanceof ObjectId && b instanceof ObjectId) { + return a.toString() === b.toString(); + } + return false; +}; - module.exports = ChangeStream; +/***/ }), - /***/ - }, +/***/ 1762: +/***/ ((module) => { - /***/ 3588: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ - - const Readable = __nccwpck_require__(2413).Readable; - const promiseOrCallback = __nccwpck_require__(4046); - const eachAsync = __nccwpck_require__(9893); - const helpers = __nccwpck_require__(5299); - const immediate = __nccwpck_require__(4830); - const util = __nccwpck_require__(1669); - - /** - * A QueryCursor is a concurrency primitive for processing query results - * one document at a time. A QueryCursor fulfills the Node.js streams3 API, - * in addition to several other mechanisms for loading documents from MongoDB - * one at a time. - * - * QueryCursors execute the model's pre `find` hooks before loading any documents - * from MongoDB, and the model's post `find` hooks after loading each document. - * - * Unless you're an advanced user, do **not** instantiate this class directly. - * Use [`Query#cursor()`](/docs/api.html#query_Query-cursor) instead. - * - * @param {Query} query - * @param {Object} options query options passed to `.find()` - * @inherits Readable - * @event `cursor`: Emitted when the cursor is created - * @event `error`: Emitted when an error occurred - * @event `data`: Emitted when the stream is flowing and the next doc is ready - * @event `end`: Emitted when the stream is exhausted - * @api public - */ - - function QueryCursor(query, options) { - Readable.call(this, { objectMode: true }); - - this.cursor = null; - this.query = query; - const _this = this; - const model = query.model; - this._mongooseOptions = {}; - this._transforms = []; - this.model = model; - this.options = options || {}; - - model.hooks.execPre("find", query, () => { - this._transforms = this._transforms.concat(query._transforms.slice()); - if (this.options.transform) { - this._transforms.push(options.transform); - } - // Re: gh-8039, you need to set the `cursor.batchSize` option, top-level - // `batchSize` option doesn't work. - if (this.options.batchSize) { - this.options.cursor = options.cursor || {}; - this.options.cursor.batchSize = options.batchSize; - - // Max out the number of documents we'll populate in parallel at 5000. - this.options._populateBatchSize = Math.min( - this.options.batchSize, - 5000 - ); - } - model.collection.find( - query._conditions, - this.options, - function (err, cursor) { - if (_this._error) { - if (cursor != null) { - cursor.close(function () {}); - } - _this.emit("cursor", null); - _this.listeners("error").length > 0 && - _this.emit("error", _this._error); - return; - } - if (err) { - return _this.emit("error", err); - } - _this.cursor = cursor; - _this.emit("cursor", cursor); - } - ); - }); - } +"use strict"; - util.inherits(QueryCursor, Readable); - /*! - * Necessary to satisfy the Readable API - */ +module.exports = function checkEmbeddedDiscriminatorKeyProjection(userProjection, path, schema, selected, addedPaths) { + const userProjectedInPath = Object.keys(userProjection). + reduce((cur, key) => cur || key.startsWith(path + '.'), false); + const _discriminatorKey = path + '.' + schema.options.discriminatorKey; + if (!userProjectedInPath && + addedPaths.length === 1 && + addedPaths[0] === _discriminatorKey) { + selected.splice(selected.indexOf(_discriminatorKey), 1); + } +}; - QueryCursor.prototype._read = function () { - const _this = this; - _next(this, function (error, doc) { - if (error) { - return _this.emit("error", error); - } - if (!doc) { - _this.push(null); - _this.cursor.close(function (error) { - if (error) { - return _this.emit("error", error); - } - setTimeout(function () { - // on node >= 14 streams close automatically (gh-8834) - const isNotClosedAutomatically = !_this.destroyed; - if (isNotClosedAutomatically) { - _this.emit("close"); - } - }, 0); - }); - return; - } - _this.push(doc); - }); - }; +/***/ }), - /** - * Registers a transform function which subsequently maps documents retrieved - * via the streams interface or `.next()` - * - * ####Example - * - * // Map documents returned by `data` events - * Thing. - * find({ name: /^hello/ }). - * cursor(). - * map(function (doc) { - * doc.foo = "bar"; - * return doc; - * }) - * on('data', function(doc) { console.log(doc.foo); }); - * - * // Or map documents returned by `.next()` - * const cursor = Thing.find({ name: /^hello/ }). - * cursor(). - * map(function (doc) { - * doc.foo = "bar"; - * return doc; - * }); - * cursor.next(function(error, doc) { - * console.log(doc.foo); - * }); - * - * @param {Function} fn - * @return {QueryCursor} - * @api public - * @method map - */ - - QueryCursor.prototype.map = function (fn) { - this._transforms.push(fn); - return this; - }; +/***/ 1449: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /*! - * Marks this cursor as errored - */ +"use strict"; - QueryCursor.prototype._markError = function (error) { - this._error = error; - return this; - }; - /** - * Marks this cursor as closed. Will stop streaming and subsequent calls to - * `next()` will error. - * - * @param {Function} callback - * @return {Promise} - * @api public - * @method close - * @emits close - * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close - */ - - QueryCursor.prototype.close = function (callback) { - return promiseOrCallback( - callback, - (cb) => { - this.cursor.close((error) => { - if (error) { - cb(error); - return ( - this.listeners("error").length > 0 && - this.emit("error", error) - ); - } - this.emit("close"); - cb(null); - }); - }, - this.model.events - ); - }; +const getDiscriminatorByValue = __nccwpck_require__(8689); - /** - * Get the next document from this cursor. Will return `null` when there are - * no documents left. - * - * @param {Function} callback - * @return {Promise} - * @api public - * @method next - */ - - QueryCursor.prototype.next = function (callback) { - return promiseOrCallback( - callback, - (cb) => { - _next(this, function (error, doc) { - if (error) { - return cb(error); - } - cb(null, doc); - }); - }, - this.model.events - ); - }; +/*! + * Find the correct constructor, taking into account discriminators + */ - /** - * Execute `fn` for every document in the cursor. If `fn` returns a promise, - * will wait for the promise to resolve before iterating on to the next one. - * Returns a promise that resolves when done. - * - * ####Example - * - * // Iterate over documents asynchronously - * Thing. - * find({ name: /^hello/ }). - * cursor(). - * eachAsync(async function (doc, i) { - * doc.foo = doc.bar + i; - * await doc.save(); - * }) - * - * @param {Function} fn - * @param {Object} [options] - * @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1. - * @param {Function} [callback] executed when all docs have been processed - * @return {Promise} - * @api public - * @method eachAsync - */ - - QueryCursor.prototype.eachAsync = function (fn, opts, callback) { - const _this = this; - if (typeof opts === "function") { - callback = opts; - opts = {}; - } - opts = opts || {}; +module.exports = function getConstructor(Constructor, value) { + const discriminatorKey = Constructor.schema.options.discriminatorKey; + if (value != null && + Constructor.discriminators && + value[discriminatorKey] != null) { + if (Constructor.discriminators[value[discriminatorKey]]) { + Constructor = Constructor.discriminators[value[discriminatorKey]]; + } else { + const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, value[discriminatorKey]); + if (constructorByValue) { + Constructor = constructorByValue; + } + } + } - return eachAsync( - function (cb) { - return _next(_this, cb); - }, - fn, - opts, - callback - ); - }; + return Constructor; +}; - /** - * The `options` passed in to the `QueryCursor` constructor. - * - * @api public - * @property options - */ - - QueryCursor.prototype.options; - - /** - * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag). - * Useful for setting the `noCursorTimeout` and `tailable` flags. - * - * @param {String} flag - * @param {Boolean} value - * @return {AggregationCursor} this - * @api public - * @method addCursorFlag - */ - - QueryCursor.prototype.addCursorFlag = function (flag, value) { - const _this = this; - _waitForCursor(this, function () { - _this.cursor.addCursorFlag(flag, value); - }); - return this; - }; +/***/ }), - /*! - * ignore - */ +/***/ 8689: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - QueryCursor.prototype.transformNull = function (val) { - if (arguments.length === 0) { - val = true; - } - this._mongooseOptions.transformNull = val; - return this; - }; +"use strict"; - /*! - * ignore - */ - QueryCursor.prototype._transformForAsyncIterator = function () { - if (this._transforms.indexOf(_transformForAsyncIterator) === -1) { - this.map(_transformForAsyncIterator); - } - return this; - }; +const areDiscriminatorValuesEqual = __nccwpck_require__(9295); - /** - * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js). - * You do not need to call this function explicitly, the JavaScript runtime - * will call it for you. - * - * ####Example - * - * // Works without using `cursor()` - * for await (const doc of Model.find([{ $sort: { name: 1 } }])) { - * console.log(doc.name); - * } - * - * // Can also use `cursor()` - * for await (const doc of Model.find([{ $sort: { name: 1 } }]).cursor()) { - * console.log(doc.name); - * } - * - * Node.js 10.x supports async iterators natively without any flags. You can - * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). - * - * **Note:** This function is not if `Symbol.asyncIterator` is undefined. If - * `Symbol.asyncIterator` is undefined, that means your Node.js version does not - * support async iterators. - * - * @method Symbol.asyncIterator - * @memberOf Query - * @instance - * @api public - */ - - if (Symbol.asyncIterator != null) { - QueryCursor.prototype[Symbol.asyncIterator] = function () { - return this.transformNull()._transformForAsyncIterator(); - }; - } +/*! +* returns discriminator by discriminatorMapping.value +* +* @param {Model} model +* @param {string} value +*/ - /*! - * ignore - */ +module.exports = function getDiscriminatorByValue(discriminators, value) { + if (discriminators == null) { + return null; + } + for (const name of Object.keys(discriminators)) { + const it = discriminators[name]; + if ( + it.schema && + it.schema.discriminatorMapping && + areDiscriminatorValuesEqual(it.schema.discriminatorMapping.value, value) + ) { + return it; + } + } + return null; +}; - function _transformForAsyncIterator(doc) { - return doc == null ? { done: true } : { value: doc, done: false }; - } +/***/ }), - /*! - * Get the next doc from the underlying cursor and mongooseify it - * (populate, etc.) - */ +/***/ 6250: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function _next(ctx, cb) { - let callback = cb; - if (ctx._transforms.length) { - callback = function (err, doc) { - if (err || (doc === null && !ctx._mongooseOptions.transformNull)) { - return cb(err, doc); - } - cb( - err, - ctx._transforms.reduce(function (doc, fn) { - return fn.call(ctx, doc); - }, doc) - ); - }; - } +"use strict"; - if (ctx._error) { - return immediate(function () { - callback(ctx._error); - }); - } - if (ctx.cursor) { - if (ctx.query._mongooseOptions.populate && !ctx._pop) { - ctx._pop = helpers.preparePopulationOptionsMQ( - ctx.query, - ctx.query._mongooseOptions - ); - ctx._pop.__noPromise = true; - } - if ( - ctx.query._mongooseOptions.populate && - ctx.options._populateBatchSize > 1 - ) { - if (ctx._batchDocs && ctx._batchDocs.length) { - // Return a cached populated doc - return _nextDoc(ctx, ctx._batchDocs.shift(), ctx._pop, callback); - } else if (ctx._batchExhausted) { - // Internal cursor reported no more docs. Act the same here - return callback(null, null); - } else { - // Request as many docs as batchSize, to populate them also in batch - ctx._batchDocs = []; - return ctx.cursor.next(_onNext.bind({ ctx, callback })); - } - } else { - return ctx.cursor.next(function (error, doc) { - if (error) { - return callback(error); - } - if (!doc) { - return callback(null, null); - } +const areDiscriminatorValuesEqual = __nccwpck_require__(9295); - if (!ctx.query._mongooseOptions.populate) { - return _nextDoc(ctx, doc, null, callback); - } +/*! +* returns discriminator by discriminatorMapping.value +* +* @param {Schema} schema +* @param {string} value +*/ - ctx.query.model.populate(doc, ctx._pop, function (err, doc) { - if (err) { - return callback(err); - } - return _nextDoc(ctx, doc, ctx._pop, callback); - }); - }); - } - } else { - ctx.once("cursor", function (cursor) { - if (cursor == null) { - return; - } - _next(ctx, cb); - }); - } - } +module.exports = function getSchemaDiscriminatorByValue(schema, value) { + if (schema == null || schema.discriminators == null) { + return null; + } + for (const key of Object.keys(schema.discriminators)) { + const discriminatorSchema = schema.discriminators[key]; + if (discriminatorSchema.discriminatorMapping == null) { + continue; + } + if (areDiscriminatorValuesEqual(discriminatorSchema.discriminatorMapping.value, value)) { + return discriminatorSchema; + } + } + return null; +}; - /*! - * ignore - */ +/***/ }), - function _onNext(error, doc) { - if (error) { - return this.callback(error); - } - if (!doc) { - this.ctx._batchExhausted = true; - return _populateBatch.call(this); - } +/***/ 7958: +/***/ ((module) => { - this.ctx._batchDocs.push(doc); +"use strict"; - if (this.ctx._batchDocs.length < this.ctx.options._populateBatchSize) { - // If both `batchSize` and `_populateBatchSize` are huge, calling `next()` repeatedly may - // cause a stack overflow. So make sure we clear the stack regularly. - if ( - this.ctx._batchDocs.length > 0 && - this.ctx._batchDocs.length % 1000 === 0 - ) { - return immediate(() => this.ctx.cursor.next(_onNext.bind(this))); - } - this.ctx.cursor.next(_onNext.bind(this)); - } else { - _populateBatch.call(this); - } - } - /*! - * ignore - */ +/*! + * ignore + */ - function _populateBatch() { - if (!this.ctx._batchDocs.length) { - return this.callback(null, null); - } - const _this = this; - this.ctx.query.model.populate( - this.ctx._batchDocs, - this.ctx._pop, - function (err) { - if (err) { - return _this.callback(err); - } +module.exports = function cleanModifiedSubpaths(doc, path, options) { + options = options || {}; + const skipDocArrays = options.skipDocArrays; - _nextDoc( - _this.ctx, - _this.ctx._batchDocs.shift(), - _this.ctx._pop, - _this.callback - ); - } - ); + let deleted = 0; + if (!doc) { + return deleted; + } + for (const modifiedPath of Object.keys(doc.$__.activePaths.states.modify)) { + if (skipDocArrays) { + const schemaType = doc.$__schema.path(modifiedPath); + if (schemaType && schemaType.$isMongooseDocumentArray) { + continue; } + } + if (modifiedPath.startsWith(path + '.')) { + delete doc.$__.activePaths.states.modify[modifiedPath]; + ++deleted; - /*! - * ignore - */ + if (doc.$isSubdocument) { + const owner = doc.ownerDocument(); + const fullPath = doc.$__fullPath(modifiedPath); + delete owner.$__.activePaths.states.modify[fullPath]; + } + } + } + return deleted; +}; - function _nextDoc(ctx, doc, pop, callback) { - if (ctx.query._mongooseOptions.lean) { - return ctx.model.hooks.execPost("find", ctx.query, [[doc]], (err) => { - if (err != null) { - return callback(err); - } - callback(null, doc); - }); - } - _create(ctx, doc, pop, (err, doc) => { - if (err != null) { - return callback(err); - } - ctx.model.hooks.execPost("find", ctx.query, [[doc]], (err) => { - if (err != null) { - return callback(err); - } - callback(null, doc); - }); - }); - } +/***/ }), - /*! - * ignore - */ +/***/ 2096: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - function _waitForCursor(ctx, cb) { - if (ctx.cursor) { - return cb(); - } - ctx.once("cursor", function (cursor) { - if (cursor == null) { - return; - } - cb(); - }); - } +"use strict"; - /*! - * Convert a raw doc into a full mongoose doc. - */ - function _create(ctx, doc, populatedIds, cb) { - const instance = helpers.createModel( - ctx.query.model, - doc, - ctx.query._fields - ); - const opts = populatedIds ? { populated: populatedIds } : undefined; +const documentSchemaSymbol = __nccwpck_require__(3240).documentSchemaSymbol; +const get = __nccwpck_require__(8730); +const internalToObjectOptions = __nccwpck_require__(5684)/* .internalToObjectOptions */ .h; +const utils = __nccwpck_require__(9232); - instance.init(doc, opts, function (err) { - if (err) { - return cb(err); - } - cb(null, instance); - }); - } +let Document; +const getSymbol = __nccwpck_require__(3240).getSymbol; +const scopeSymbol = __nccwpck_require__(3240).scopeSymbol; - module.exports = QueryCursor; +/*! + * exports + */ - /***/ - }, +exports.M = compile; +exports.c = defineKey; - /***/ 6717: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const InternalCache = __nccwpck_require__(5963); - const MongooseError = __nccwpck_require__(4327); - const MixedSchema = __nccwpck_require__(7495); - const ObjectExpectedError = __nccwpck_require__(2293); - const ObjectParameterError = __nccwpck_require__(3456); - const ParallelValidateError = __nccwpck_require__(3897); - const Schema = __nccwpck_require__(7606); - const StrictModeError = __nccwpck_require__(703); - const ValidationError = __nccwpck_require__(8460); - const ValidatorError = __nccwpck_require__(6345); - const VirtualType = __nccwpck_require__(1423); - const promiseOrCallback = __nccwpck_require__(4046); - const cleanModifiedSubpaths = __nccwpck_require__(7958); - const compile = __nccwpck_require__(2096) /* .compile */.M; - const defineKey = __nccwpck_require__(2096) /* .defineKey */.c; - const flatten = __nccwpck_require__(3719) /* .flatten */.x; - const get = __nccwpck_require__(8730); - const getEmbeddedDiscriminatorPath = __nccwpck_require__(509); - const handleSpreadDoc = __nccwpck_require__(5232); - const idGetter = __nccwpck_require__(3816); - const immediate = __nccwpck_require__(4830); - const isDefiningProjection = __nccwpck_require__(1903); - const isExclusive = __nccwpck_require__(9197); - const inspect = __nccwpck_require__(1669).inspect; - const internalToObjectOptions = - __nccwpck_require__(5684) /* .internalToObjectOptions */.h; - const mpath = __nccwpck_require__(8586); - const queryhelpers = __nccwpck_require__(5299); - const utils = __nccwpck_require__(9232); - const isPromise = __nccwpck_require__(224); - - const clone = utils.clone; - const deepEqual = utils.deepEqual; - const isMongooseObject = utils.isMongooseObject; - - const arrayAtomicsBackupSymbol = Symbol("mongoose.Array#atomicsBackup"); - const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; - const documentArrayParent = __nccwpck_require__(3240).documentArrayParent; - const documentIsModified = __nccwpck_require__(3240).documentIsModified; - const documentModifiedPaths = - __nccwpck_require__(3240).documentModifiedPaths; - const documentSchemaSymbol = - __nccwpck_require__(3240).documentSchemaSymbol; - const getSymbol = __nccwpck_require__(3240).getSymbol; - const populateModelSymbol = __nccwpck_require__(3240).populateModelSymbol; - const scopeSymbol = __nccwpck_require__(3240).scopeSymbol; - const schemaMixedSymbol = __nccwpck_require__(1205).schemaMixedSymbol; - - let DocumentArray; - let MongooseArray; - let Embedded; - - const specialProperties = utils.specialProperties; - - /** - * The core Mongoose document constructor. You should not call this directly, - * the Mongoose [Model constructor](./api.html#Model) calls this for you. - * - * @param {Object} obj the values to set - * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data - * @param {Object} [options] various configuration options for the document - * @param {Boolean} [options.defaults=true] if `false`, skip applying default values to this document. - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `init`: Emitted on a document after it has been retrieved from the db and fully hydrated by Mongoose. - * @event `save`: Emitted when the document is successfully saved - * @api private - */ - - function Document(obj, fields, skipId, options) { - if (typeof skipId === "object" && skipId != null) { - options = skipId; - skipId = options.skipId; - } - options = Object.assign({}, options); - const defaults = get(options, "defaults", true); - options.defaults = defaults; - // Support `browserDocument.js` syntax - if (this.$__schema == null) { - const _schema = - utils.isObject(fields) && !fields.instanceOfSchema - ? new Schema(fields) - : fields; - this.$__setSchema(_schema); - fields = skipId; - skipId = options; - options = arguments[4] || {}; - } - - this.$__ = new InternalCache(); - this.$__.emitter = new EventEmitter(); - this.isNew = "isNew" in options ? options.isNew : true; - this.errors = undefined; - this.$__.$options = options || {}; - this.$locals = {}; - this.$op = null; - if (obj != null && typeof obj !== "object") { - throw new ObjectParameterError(obj, "obj", "Document"); - } - - const schema = this.$__schema; - - if (typeof fields === "boolean" || fields === "throw") { - this.$__.strictMode = fields; - fields = undefined; - } else { - this.$__.strictMode = schema.options.strict; - this.$__.selected = fields; - } +/*! + * Compiles schemas. + */ - const requiredPaths = schema.requiredPaths(true); - for (const path of requiredPaths) { - this.$__.activePaths.require(path); - } +function compile(tree, proto, prefix, options) { + Document = Document || __nccwpck_require__(6717); - this.$__.emitter.setMaxListeners(0); + for (const key of Object.keys(tree)) { + const limb = tree[key]; - let exclude = null; + const hasSubprops = utils.isPOJO(limb) && Object.keys(limb).length && + (!limb[options.typeKey] || (options.typeKey === 'type' && limb.type.type)); + const subprops = hasSubprops ? limb : null; - // determine if this doc is a result of a query with - // excluded fields - if (utils.isPOJO(fields)) { - exclude = isExclusive(fields); - } + defineKey({ prop: key, subprops: subprops, prototype: proto, prefix: prefix, options: options }); + } +} - const hasIncludedChildren = - exclude === false && fields ? $__hasIncludedChildren(fields) : {}; +/*! + * Defines the accessor named prop on the incoming prototype. + */ - if (this._doc == null) { - this.$__buildDoc( - obj, - fields, - skipId, - exclude, - hasIncludedChildren, - false - ); +function defineKey({ prop, subprops, prototype, prefix, options }) { + Document = Document || __nccwpck_require__(6717); + const path = (prefix ? prefix + '.' : '') + prop; + prefix = prefix || ''; - // By default, defaults get applied **before** setting initial values - // Re: gh-6155 - if (defaults) { - $__applyDefaults( - this, - fields, - skipId, - exclude, - hasIncludedChildren, - true, - { - isNew: this.isNew, - } - ); - } + if (subprops) { + Object.defineProperty(prototype, prop, { + enumerable: true, + configurable: true, + get: function() { + const _this = this; + if (!this.$__.getters) { + this.$__.getters = {}; } - if (obj) { - // Skip set hooks - if (this.$__original_set) { - this.$__original_set(obj, undefined, true); - } else { - this.$set(obj, undefined, true); - } - if (obj instanceof Document) { - this.isNew = obj.isNew; + if (!this.$__.getters[path]) { + const nested = Object.create(Document.prototype, getOwnPropertyDescriptors(this)); + + // save scope for nested getters/setters + if (!prefix) { + nested.$__[scopeSymbol] = this; } - } + nested.$__.nestedPath = path; - // Function defaults get applied **after** setting initial values so they - // see the full doc rather than an empty one, unless they opt out. - // Re: gh-3781, gh-6155 - if (options.willInit && defaults) { - EventEmitter.prototype.once.call(this, "init", () => { - $__applyDefaults( - this, - fields, - skipId, - exclude, - hasIncludedChildren, - false, - options.skipDefaults, - { - isNew: this.isNew, - } - ); + Object.defineProperty(nested, 'schema', { + enumerable: false, + configurable: true, + writable: false, + value: prototype.schema }); - } else if (defaults) { - $__applyDefaults( - this, - fields, - skipId, - exclude, - hasIncludedChildren, - false, - options.skipDefaults, - { - isNew: this.isNew, - } - ); - } - this.$__._id = this._id; + Object.defineProperty(nested, '$__schema', { + enumerable: false, + configurable: true, + writable: false, + value: prototype.schema + }); - if (!this.$__.strictMode && obj) { - const _this = this; - const keys = Object.keys(this._doc); + Object.defineProperty(nested, documentSchemaSymbol, { + enumerable: false, + configurable: true, + writable: false, + value: prototype.schema + }); - keys.forEach(function (key) { - if (!(key in schema.tree)) { - defineKey(key, null, _this); + Object.defineProperty(nested, 'toObject', { + enumerable: false, + configurable: true, + writable: false, + value: function() { + return utils.clone(_this.get(path, null, { + virtuals: get(this, 'schema.options.toObject.virtuals', null) + })); } }); - } - applyQueue(this); - } - - /*! - * Document exposes the NodeJS event emitter API, so you can use - * `on`, `once`, etc. - */ - utils.each( - [ - "on", - "once", - "emit", - "listeners", - "removeListener", - "setMaxListeners", - "removeAllListeners", - "addListener", - ], - function (emitterFn) { - Document.prototype[emitterFn] = function () { - return this.$__.emitter[emitterFn].apply( - this.$__.emitter, - arguments - ); - }; - } - ); + Object.defineProperty(nested, '$__get', { + enumerable: false, + configurable: true, + writable: false, + value: function() { + return _this.get(path, null, { + virtuals: get(this, 'schema.options.toObject.virtuals', null) + }); + } + }); - Document.prototype.constructor = Document; - - for (const i in EventEmitter.prototype) { - Document[i] = EventEmitter.prototype[i]; - } - - /** - * The document's internal schema. - * - * @api private - * @property schema - * @memberOf Document - * @instance - */ - - Document.prototype.$__schema; - - /** - * The document's schema. - * - * @api public - * @property schema - * @memberOf Document - * @instance - */ - - Document.prototype.schema; - - /** - * Empty object that you can use for storing properties on the document. This - * is handy for passing data to middleware without conflicting with Mongoose - * internals. - * - * ####Example: - * - * schema.pre('save', function() { - * // Mongoose will set `isNew` to `false` if `save()` succeeds - * this.$locals.wasNew = this.isNew; - * }); - * - * schema.post('save', function() { - * // Prints true if `isNew` was set before `save()` - * console.log(this.$locals.wasNew); - * }); - * - * @api public - * @property $locals - * @memberOf Document - * @instance - */ - - Object.defineProperty(Document.prototype, "$locals", { - configurable: false, - enumerable: false, - writable: true, - }); + Object.defineProperty(nested, 'toJSON', { + enumerable: false, + configurable: true, + writable: false, + value: function() { + return _this.get(path, null, { + virtuals: get(_this, 'schema.options.toJSON.virtuals', null) + }); + } + }); - /** - * Boolean flag specifying if the document is new. - * - * @api public - * @property isNew - * @memberOf Document - * @instance - */ - - Document.prototype.isNew; - - /** - * Set this property to add additional query filters when Mongoose saves this document and `isNew` is false. - * - * ####Example: - * - * // Make sure `save()` never updates a soft deleted document. - * schema.pre('save', function() { - * this.$where = { isDeleted: false }; - * }); - * - * @api public - * @property $where - * @memberOf Document - * @instance - */ - - Object.defineProperty(Document.prototype, "$where", { - configurable: false, - enumerable: false, - writable: true, - }); + Object.defineProperty(nested, '$__isNested', { + enumerable: false, + configurable: true, + writable: false, + value: true + }); - /** - * The string version of this documents _id. - * - * ####Note: - * - * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time. - * - * new Schema({ name: String }, { id: false }); - * - * @api public - * @see Schema options /docs/guide.html#options - * @property id - * @memberOf Document - * @instance - */ - - Document.prototype.id; - - /** - * Hash containing current validation errors. - * - * @api public - * @property errors - * @memberOf Document - * @instance - */ - - Document.prototype.errors; - - /** - * A string containing the current operation that Mongoose is executing - * on this document. May be `null`, `'save'`, `'validate'`, or `'remove'`. - * - * ####Example: - * - * const doc = new Model({ name: 'test' }); - * doc.$op; // null - * - * const promise = doc.save(); - * doc.$op; // 'save' - * - * await promise; - * doc.$op; // null - * - * @api public - * @property $op - * @memberOf Document - * @instance - */ - - Document.prototype.$op; - - /*! - * ignore - */ - - function $__hasIncludedChildren(fields) { - const hasIncludedChildren = {}; - const keys = Object.keys(fields); + const _isEmptyOptions = Object.freeze({ + minimize: true, + virtuals: false, + getters: false, + transform: false + }); + Object.defineProperty(nested, '$isEmpty', { + enumerable: false, + configurable: true, + writable: false, + value: function() { + return Object.keys(this.get(path, null, _isEmptyOptions) || {}).length === 0; + } + }); - for (const key of keys) { - const parts = key.split("."); - const c = []; + Object.defineProperty(nested, '$__parent', { + enumerable: false, + configurable: true, + writable: false, + value: this + }); - for (const part of parts) { - c.push(part); - hasIncludedChildren[c.join(".")] = 1; - } + compile(subprops, nested, path, options); + this.$__.getters[path] = nested; } - return hasIncludedChildren; + return this.$__.getters[path]; + }, + set: function(v) { + if (v != null && v.$__isNested) { + // Convert top-level to POJO, but leave subdocs hydrated so `$set` + // can handle them. See gh-9293. + v = v.$__get(); + } else if (v instanceof Document && !v.$__isNested) { + v = v.$toObject(internalToObjectOptions); + } + const doc = this.$__[scopeSymbol] || this; + doc.$set(path, v); + } + }); + } else { + Object.defineProperty(prototype, prop, { + enumerable: true, + configurable: true, + get: function() { + return this[getSymbol].call(this.$__[scopeSymbol] || this, path); + }, + set: function(v) { + this.$set.call(this.$__[scopeSymbol] || this, path, v); } + }); + } +} + +// gets descriptors for all properties of `object` +// makes all properties non-enumerable to match previous behavior to #2211 +function getOwnPropertyDescriptors(object) { + const result = {}; + + Object.getOwnPropertyNames(object).forEach(function(key) { + const skip = [ + 'isNew', + '$__', + '$errors', + 'errors', + '_doc', + '$locals', + '$op', + '__parentArray', + '__index', + '$isDocumentArrayElement' + ].indexOf(key) === -1; + if (skip) { + return; + } - /*! - * ignore - */ + result[key] = Object.getOwnPropertyDescriptor(object, key); + result[key].enumerable = false; + }); - function $__applyDefaults( - doc, - fields, - skipId, - exclude, - hasIncludedChildren, - isBeforeSetters, - pathsToSkip - ) { - const paths = Object.keys(doc.$__schema.paths); - const plen = paths.length; + return result; +} - for (let i = 0; i < plen; ++i) { - let def; - let curPath = ""; - const p = paths[i]; - if (p === "_id" && skipId) { - continue; - } +/***/ }), - const type = doc.$__schema.paths[p]; - const path = type.splitPath(); - const len = path.length; - let included = false; - let doc_ = doc._doc; - for (let j = 0; j < len; ++j) { - if (doc_ == null) { - break; - } +/***/ 509: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const piece = path[j]; - curPath += (!curPath.length ? "" : ".") + piece; +"use strict"; - if (exclude === true) { - if (curPath in fields) { - break; - } - } else if (exclude === false && fields && !included) { - if (curPath in fields) { - included = true; - } else if (!hasIncludedChildren[curPath]) { - break; - } - } - if (j === len - 1) { - if (doc_[piece] !== void 0) { - break; - } +const get = __nccwpck_require__(8730); +const getSchemaDiscriminatorByValue = __nccwpck_require__(6250); - if (typeof type.defaultValue === "function") { - if (!type.defaultValue.$runBeforeSetters && isBeforeSetters) { - break; - } - if (type.defaultValue.$runBeforeSetters && !isBeforeSetters) { - break; - } - } else if (!isBeforeSetters) { - // Non-function defaults should always run **before** setters - continue; - } +/*! + * Like `schema.path()`, except with a document, because impossible to + * determine path type without knowing the embedded discriminator key. + */ - if (pathsToSkip && pathsToSkip[curPath]) { - break; - } +module.exports = function getEmbeddedDiscriminatorPath(doc, path, options) { + options = options || {}; + const typeOnly = options.typeOnly; + const parts = path.indexOf('.') === -1 ? [path] : path.split('.'); + let schemaType = null; + let type = 'adhocOrUndefined'; + + const schema = getSchemaDiscriminatorByValue(doc.schema, doc.get(doc.schema.options.discriminatorKey)) || doc.schema; + + for (let i = 0; i < parts.length; ++i) { + const subpath = parts.slice(0, i + 1).join('.'); + schemaType = schema.path(subpath); + if (schemaType == null) { + type = 'adhocOrUndefined'; + continue; + } + if (schemaType.instance === 'Mixed') { + return typeOnly ? 'real' : schemaType; + } + type = schema.pathType(subpath); + if ((schemaType.$isSingleNested || schemaType.$isMongooseDocumentArrayElement) && + schemaType.schema.discriminators != null) { + const discriminators = schemaType.schema.discriminators; + const discriminatorKey = doc.get(subpath + '.' + + get(schemaType, 'schema.options.discriminatorKey')); + if (discriminatorKey == null || discriminators[discriminatorKey] == null) { + continue; + } + const rest = parts.slice(i + 1).join('.'); + return getEmbeddedDiscriminatorPath(doc.get(subpath), rest, options); + } + } - if (fields && exclude !== null) { - if (exclude === true) { - // apply defaults to all non-excluded fields - if (p in fields) { - continue; - } + // Are we getting the whole schema or just the type, 'real', 'nested', etc. + return typeOnly ? type : schemaType; +}; - try { - def = type.getDefault(doc, false); - } catch (err) { - doc.invalidate(p, err); - break; - } - if (typeof def !== "undefined") { - doc_[piece] = def; - doc.$__.activePaths.default(p); - } - } else if (included) { - // selected field - try { - def = type.getDefault(doc, false); - } catch (err) { - doc.invalidate(p, err); - break; - } +/***/ }), - if (typeof def !== "undefined") { - doc_[piece] = def; - doc.$__.activePaths.default(p); - } - } - } else { - try { - def = type.getDefault(doc, false); - } catch (err) { - doc.invalidate(p, err); - break; - } +/***/ 5232: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (typeof def !== "undefined") { - doc_[piece] = def; - doc.$__.activePaths.default(p); - } - } - } else { - doc_ = doc_[piece]; - } - } - } - } +"use strict"; - /** - * Builds the default doc structure - * - * @param {Object} obj - * @param {Object} [fields] - * @param {Boolean} [skipId] - * @api private - * @method $__buildDoc - * @memberOf Document - * @instance - */ - - Document.prototype.$__buildDoc = function ( - obj, - fields, - skipId, - exclude, - hasIncludedChildren - ) { - const doc = {}; - - const paths = Object.keys(this.$__schema.paths) - // Don't build up any paths that are underneath a map, we don't know - // what the keys will be - .filter((p) => !p.includes("$*")); - const plen = paths.length; - let ii = 0; - - for (; ii < plen; ++ii) { - const p = paths[ii]; - - if (p === "_id") { - if (skipId) { - continue; - } - if (obj && "_id" in obj) { - continue; - } - } - const path = this.$__schema.paths[p].splitPath(); - const len = path.length; - const last = len - 1; - let curPath = ""; - let doc_ = doc; - let included = false; +const utils = __nccwpck_require__(9232); - for (let i = 0; i < len; ++i) { - const piece = path[i]; +/** + * Using spread operator on a Mongoose document gives you a + * POJO that has a tendency to cause infinite recursion. So + * we use this function on `set()` to prevent that. + */ - curPath += (!curPath.length ? "" : ".") + piece; +module.exports = function handleSpreadDoc(v) { + if (utils.isPOJO(v) && v.$__ != null && v._doc != null) { + return v._doc; + } - // support excluding intermediary levels - if (exclude === true) { - if (curPath in fields) { - break; - } - } else if (exclude === false && fields && !included) { - if (curPath in fields) { - included = true; - } else if (!hasIncludedChildren[curPath]) { - break; - } - } + return v; +}; - if (i < last) { - doc_ = doc_[piece] || (doc_[piece] = {}); - } - } - } +/***/ }), - this._doc = doc; - }; +/***/ 9965: +/***/ ((module) => { - /*! - * Converts to POJO when you use the document for querying - */ +"use strict"; - Document.prototype.toBSON = function () { - return this.toObject(internalToObjectOptions); - }; - /** - * Initializes the document without setters or marking anything modified. - * - * Called internally after a document is returned from mongodb. Normally, - * you do **not** need to call this function on your own. - * - * This function triggers `init` [middleware](/docs/middleware.html). - * Note that `init` hooks are [synchronous](/docs/middleware.html#synchronous). - * - * @param {Object} doc document returned by mongo - * @api public - * @memberOf Document - * @instance - */ +module.exports = function each(arr, cb, done) { + if (arr.length === 0) { + return done(); + } - Document.prototype.init = function (doc, opts, fn) { - if (typeof opts === "function") { - fn = opts; - opts = null; - } + let remaining = arr.length; + let err = null; + for (const v of arr) { + cb(v, function(_err) { + if (err != null) { + return; + } + if (_err != null) { + err = _err; + return done(err); + } - this.$__init(doc, opts); + if (--remaining <= 0) { + return done(); + } + }); + } +}; - if (fn) { - fn(null, this); - } +/***/ }), - return this; - }; +/***/ 8730: +/***/ ((module) => { - /*! - * ignore - */ - - Document.prototype.$__init = function (doc, opts) { - this.isNew = false; - this.$init = true; - opts = opts || {}; - - // handle docs with populated paths - // If doc._id is not null or undefined - if (doc._id != null && opts.populated && opts.populated.length) { - const id = String(doc._id); - for (const item of opts.populated) { - if (item.isVirtual) { - this.populated(item.path, utils.getValue(item.path, doc), item); - } else { - this.populated(item.path, item._docs[id], item); - } +"use strict"; - if (item._childDocs == null) { - continue; - } - for (const child of item._childDocs) { - if (child == null || child.$__ == null) { - continue; - } - child.$__.parent = this; - } - item._childDocs = []; - } - } - init(this, doc, this._doc, opts); +/*! + * Simplified lodash.get to work around the annoying null quirk. See: + * https://github.com/lodash/lodash/issues/3659 + */ - markArraySubdocsPopulated(this, opts.populated); +module.exports = function get(obj, path, def) { + let parts; + let isPathArray = false; + if (typeof path === 'string') { + if (path.indexOf('.') === -1) { + const _v = getProperty(obj, path); + if (_v == null) { + return def; + } + return _v; + } - this.emit("init", this); - this.constructor.emit("init", this); + parts = path.split('.'); + } else { + isPathArray = true; + parts = path; - this.$__._id = this._id; - return this; - }; + if (parts.length === 1) { + const _v = getProperty(obj, parts[0]); + if (_v == null) { + return def; + } + return _v; + } + } + let rest = path; + let cur = obj; + for (const part of parts) { + if (cur == null) { + return def; + } - /*! - * If populating a path within a document array, make sure each - * subdoc within the array knows its subpaths are populated. - * - * ####Example: - * const doc = await Article.findOne().populate('comments.author'); - * doc.comments[0].populated('author'); // Should be set - */ - - function markArraySubdocsPopulated(doc, populated) { - if (doc._id == null || populated == null || populated.length === 0) { - return; - } + // `lib/cast.js` depends on being able to get dotted paths in updates, + // like `{ $set: { 'a.b': 42 } }` + if (!isPathArray && cur[rest] != null) { + return cur[rest]; + } - const id = String(doc._id); - for (const item of populated) { - if (item.isVirtual) { - continue; - } - const path = item.path; - const pieces = path.split("."); - for (let i = 0; i < pieces.length - 1; ++i) { - const subpath = pieces.slice(0, i + 1).join("."); - const rest = pieces.slice(i + 1).join("."); - const val = doc.get(subpath); - if (val == null) { - continue; - } + cur = getProperty(cur, part); - if (val.isMongooseDocumentArray) { - for (let j = 0; j < val.length; ++j) { - val[j].populated( - rest, - item._docs[id] == null ? [] : item._docs[id][j], - item - ); - } - break; - } - } - } - } + if (!isPathArray) { + rest = rest.substr(part.length + 1); + } + } - /*! - * Init helper. - * - * @param {Object} self document instance - * @param {Object} obj raw mongodb doc - * @param {Object} doc object we are initializing - * @api private - */ + return cur == null ? def : cur; +}; - function init(self, obj, doc, opts, prefix) { - prefix = prefix || ""; +function getProperty(obj, prop) { + if (obj == null) { + return obj; + } + if (obj instanceof Map) { + return obj.get(prop); + } + return obj[prop]; +} - const keys = Object.keys(obj); - const len = keys.length; - let schema; - let path; - let i; - let index = 0; +/***/ }), - while (index < len) { - _init(index++); - } +/***/ 7323: +/***/ ((module) => { - function _init(index) { - i = keys[index]; - path = prefix + i; - schema = self.$__schema.path(path); +"use strict"; - // Should still work if not a model-level discriminator, but should not be - // necessary. This is *only* to catch the case where we queried using the - // base model and the discriminated model has a projection - if ( - self.$__schema.$isRootDiscriminator && - !self.$__isSelected(path) - ) { - return; - } - if (!schema && utils.isPOJO(obj[i])) { - // assume nested object - if (!doc[i]) { - doc[i] = {}; - } - init(self, obj[i], doc[i], opts, path + "."); - } else if (!schema) { - doc[i] = obj[i]; - } else { - if (obj[i] === null) { - doc[i] = schema._castNullish(null); - } else if (obj[i] !== undefined) { - const intCache = obj[i].$__ || {}; - const wasPopulated = intCache.wasPopulated || null; - - if (schema && !wasPopulated) { - try { - doc[i] = schema.cast(obj[i], self, true); - } catch (e) { - self.invalidate( - e.path, - new ValidatorError({ - path: e.path, - message: e.message, - type: "cast", - value: e.value, - reason: e, - }) - ); - } - } else { - doc[i] = obj[i]; - } - } - // mark as hydrated - if (!self.isModified(path)) { - self.$__.activePaths.init(path); - } - } - } - } +/*! + * If `val` is an object, returns constructor name, if possible. Otherwise returns undefined. + */ - /** - * Sends an update command with this document `_id` as the query selector. - * - * ####Example: - * - * weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback); - * - * ####Valid options: - * - * - same as in [Model.update](#model_Model.update) - * - * @see Model.update #model_Model.update - * @param {Object} doc - * @param {Object} options - * @param {Function} callback - * @return {Query} - * @api public - * @memberOf Document - * @instance - */ - - Document.prototype.update = function update() { - const args = utils.args(arguments); - args.unshift({ _id: this._id }); - const query = this.constructor.update.apply(this.constructor, args); - - if (this.$session() != null) { - if (!("session" in query.options)) { - query.options.session = this.$session(); - } - } +module.exports = function getConstructorName(val) { + if (val == null) { + return void 0; + } + if (typeof val.constructor !== 'function') { + return void 0; + } + return val.constructor.name; +}; + +/***/ }), + +/***/ 3039: +/***/ ((module) => { + +"use strict"; + +function getDefaultBulkwriteResult() { + return { + result: { + ok: 1, + writeErrors: [], + writeConcernErrors: [], + insertedIds: [], + nInserted: 0, + nUpserted: 0, + nMatched: 0, + nModified: 0, + nRemoved: 0, + upserted: [] + }, + insertedCount: 0, + matchedCount: 0, + modifiedCount: 0, + deletedCount: 0, + upsertedCount: 0, + upsertedIds: {}, + insertedIds: {}, + n: 0 + }; +} - return query; - }; +module.exports = getDefaultBulkwriteResult; - /** - * Sends an updateOne command with this document `_id` as the query selector. - * - * ####Example: - * - * weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback); - * - * ####Valid options: - * - * - same as in [Model.updateOne](#model_Model.updateOne) - * - * @see Model.updateOne #model_Model.updateOne - * @param {Object} doc - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Function} callback - * @return {Query} - * @api public - * @memberOf Document - * @instance - */ - - Document.prototype.updateOne = function updateOne( - doc, - options, - callback - ) { - const query = this.constructor.updateOne( - { _id: this._id }, - doc, - options - ); - query.pre((cb) => { - this.constructor._middleware.execPre("updateOne", this, [this], cb); - }); - query.post((cb) => { - this.constructor._middleware.execPost( - "updateOne", - this, - [this], - {}, - cb - ); - }); +/***/ }), - if (this.$session() != null) { - if (!("session" in query.options)) { - query.options.session = this.$session(); - } - } +/***/ 6621: +/***/ ((module) => { - if (callback != null) { - return query.exec(callback); - } +"use strict"; - return query; - }; - /** - * Sends a replaceOne command with this document `_id` as the query selector. - * - * ####Valid options: - * - * - same as in [Model.replaceOne](https://mongoosejs.com/docs/api/model.html#model_Model.replaceOne) - * - * @see Model.replaceOne #model_Model.replaceOne - * @param {Object} doc - * @param {Object} options - * @param {Function} callback - * @return {Query} - * @api public - * @memberOf Document - * @instance - */ - - Document.prototype.replaceOne = function replaceOne() { - const args = utils.args(arguments); - args.unshift({ _id: this._id }); - return this.constructor.replaceOne.apply(this.constructor, args); - }; +module.exports = function(fn) { + if (fn.name) { + return fn.name; + } + return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1]; +}; - /** - * Getter/setter around the session associated with this document. Used to - * automatically set `session` if you `save()` a doc that you got from a - * query with an associated session. - * - * ####Example: - * - * const session = MyModel.startSession(); - * const doc = await MyModel.findOne().session(session); - * doc.$session() === session; // true - * doc.$session(null); - * doc.$session() === null; // true - * - * If this is a top-level document, setting the session propagates to all child - * docs. - * - * @param {ClientSession} [session] overwrite the current session - * @return {ClientSession} - * @method $session - * @api public - * @memberOf Document - */ - - Document.prototype.$session = function $session(session) { - if (arguments.length === 0) { - if (this.$__.session != null && this.$__.session.hasEnded) { - this.$__.session = null; - return null; - } - return this.$__.session; - } - if (session != null && session.hasEnded) { - throw new MongooseError( - "Cannot set a document's session to a session that has ended. Make sure you haven't " + - "called `endSession()` on the session you are passing to `$session()`." - ); - } +/***/ }), - this.$__.session = session; +/***/ 4830: +/***/ ((module) => { - if (!this.ownerDocument) { - const subdocs = this.$getAllSubdocs(); - for (const child of subdocs) { - child.$session(session); - } - } +"use strict"; +/*! + * Centralize this so we can more easily work around issues with people + * stubbing out `process.nextTick()` in tests using sinon: + * https://github.com/sinonjs/lolex#automatically-incrementing-mocked-time + * See gh-6074 + */ - return session; - }; - /** - * Overwrite all values in this document with the values of `obj`, except - * for immutable properties. Behaves similarly to `set()`, except for it - * unsets all properties that aren't in `obj`. - * - * @param {Object} obj the object to overwrite this document with - * @method overwrite - * @name overwrite - * @memberOf Document - * @instance - * @api public - */ - - Document.prototype.overwrite = function overwrite(obj) { - const keys = Array.from( - new Set(Object.keys(this._doc).concat(Object.keys(obj))) - ); - for (const key of keys) { - if (key === "_id") { - continue; - } - // Explicitly skip version key - if ( - this.$__schema.options.versionKey && - key === this.$__schema.options.versionKey - ) { - continue; - } - if ( - this.$__schema.options.discriminatorKey && - key === this.$__schema.options.discriminatorKey - ) { - continue; - } - this.$set(key, obj[key]); - } +const nextTick = process.nextTick.bind(process); - return this; - }; +module.exports = function immediate(cb) { + return nextTick(cb); +}; - /** - * Alias for `set()`, used internally to avoid conflicts - * - * @param {String|Object} path path or object of key/vals to set - * @param {Any} val the value to set - * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes - * @param {Object} [options] optionally specify options that modify the behavior of the set - * @method $set - * @name $set - * @memberOf Document - * @instance - * @api public - */ - - Document.prototype.$set = function $set(path, val, type, options) { - if (utils.isPOJO(type)) { - options = type; - type = undefined; - } - options = options || {}; - const merge = options.merge; - const adhoc = type && type !== true; - const constructing = type === true; - const typeKey = this.$__schema.options.typeKey; - let adhocs; - let keys; - let i = 0; - let pathtype; - let key; - let prefix; - - const strict = - "strict" in options ? options.strict : this.$__.strictMode; - - if (adhoc) { - adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); - adhocs[path] = this.$__schema.interpretAsType( - path, - type, - this.$__schema.options - ); - } +/***/ }), - if (path == null) { - const _ = path; - path = val; - val = _; - } else if (typeof path !== "string") { - // new Document({ key: val }) - if (path instanceof Document) { - if (path.$__isNested) { - path = path.toObject(); - } else { - path = path._doc; - } - } - if (path == null) { - const _ = path; - path = val; - val = _; - } +/***/ 7720: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - prefix = val ? val + "." : ""; - keys = Object.keys(path); - const len = keys.length; +"use strict"; - // `_skipMinimizeTopLevel` is because we may have deleted the top-level - // nested key to ensure key order. - const _skipMinimizeTopLevel = get( - options, - "_skipMinimizeTopLevel", - false - ); - if (len === 0 && _skipMinimizeTopLevel) { - delete options._skipMinimizeTopLevel; - if (val) { - this.$set(val, {}); - } - return this; - } - for (let i = 0; i < len; ++i) { - key = keys[i]; - const pathName = prefix + key; - pathtype = this.$__schema.pathType(pathName); - - // On initial set, delete any nested keys if we're going to overwrite - // them to ensure we keep the user's key order. - if ( - type === true && - !prefix && - path[key] != null && - pathtype === "nested" && - this._doc[key] != null && - Object.keys(this._doc[key]).length === 0 - ) { - delete this._doc[key]; - // Make sure we set `{}` back even if we minimize re: gh-8565 - options = Object.assign({}, options, { - _skipMinimizeTopLevel: true, - }); - } else { - // Make sure we set `{_skipMinimizeTopLevel: false}` if don't have overwrite: gh-10441 - options = Object.assign({}, options, { - _skipMinimizeTopLevel: false, - }); - } +const get = __nccwpck_require__(8730); - const someCondition = - typeof path[key] === "object" && - !utils.isNativeObject(path[key]) && - !utils.isMongooseType(path[key]) && - path[key] != null && - pathtype !== "virtual" && - pathtype !== "real" && - pathtype !== "adhocOrUndefined" && - !(this.$__path(pathName) instanceof MixedSchema) && - !( - this.$__schema.paths[pathName] && - this.$__schema.paths[pathName].options && - this.$__schema.paths[pathName].options.ref - ); +module.exports = function isDefaultIdIndex(index) { + if (Array.isArray(index)) { + // Mongoose syntax + const keys = Object.keys(index[0]); + return keys.length === 1 && keys[0] === '_id' && index[0]._id !== 'hashed'; + } - if (someCondition) { - this.$__.$setCalled.add(prefix + key); - this.$set(path[key], prefix + key, constructing, options); - } else if (strict) { - // Don't overwrite defaults with undefined keys (gh-3981) (gh-9039) - if ( - constructing && - path[key] === void 0 && - this.get(pathName) !== void 0 - ) { - continue; - } + if (typeof index !== 'object') { + return false; + } - if (pathtype === "adhocOrUndefined") { - pathtype = getEmbeddedDiscriminatorPath(this, pathName, { - typeOnly: true, - }); - } + const key = get(index, 'key', {}); + return Object.keys(key).length === 1 && key.hasOwnProperty('_id'); +}; - if (pathtype === "real" || pathtype === "virtual") { - // Check for setting single embedded schema to document (gh-3535) - let p = path[key]; - if ( - this.$__schema.paths[pathName] && - this.$__schema.paths[pathName].$isSingleNested && - path[key] instanceof Document - ) { - p = p.toObject({ virtuals: false, transform: false }); - } - this.$set(prefix + key, p, constructing, options); - } else if ( - pathtype === "nested" && - path[key] instanceof Document - ) { - this.$set( - prefix + key, - path[key].toObject({ transform: false }), - constructing, - options - ); - } else if (strict === "throw") { - if (pathtype === "nested") { - throw new ObjectExpectedError(key, path[key]); - } else { - throw new StrictModeError(key); - } - } - } else if (path[key] !== void 0) { - this.$set(prefix + key, path[key], constructing, options); - } - } +/***/ }), - return this; - } else { - this.$__.$setCalled.add(path); - } +/***/ 4749: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - let pathType = this.$__schema.pathType(path); - if (pathType === "adhocOrUndefined") { - pathType = getEmbeddedDiscriminatorPath(this, path, { - typeOnly: true, - }); - } +"use strict"; - // Assume this is a Mongoose document that was copied into a POJO using - // `Object.assign()` or `{...doc}` - val = handleSpreadDoc(val); - - if (pathType === "nested" && val) { - if (typeof val === "object" && val != null) { - const hasPriorVal = - this.$__.savedState != null && - this.$__.savedState.hasOwnProperty(path); - if ( - this.$__.savedState != null && - !this.isNew && - !this.$__.savedState.hasOwnProperty(path) - ) { - const priorVal = this.$__getValue(path); - this.$__.savedState[path] = priorVal; - - const keys = Object.keys(priorVal || {}); - for (const key of keys) { - this.$__.savedState[path + "." + key] = priorVal[key]; - } - } - if (!merge) { - this.$__setValue(path, null); - cleanModifiedSubpaths(this, path); - } else { - return this.$set(val, path, constructing); - } +const get = __nccwpck_require__(8730); +const utils = __nccwpck_require__(9232); +/** + * Given a Mongoose index definition (key + options objects) and a MongoDB server + * index definition, determine if the two indexes are equal. + * + * @param {Object} key the Mongoose index spec + * @param {Object} options the Mongoose index definition's options + * @param {Object} dbIndex the index in MongoDB as returned by `listIndexes()` + * @api private + */ - const keys = Object.keys(val); - this.$__setValue(path, {}); - for (const key of keys) { - this.$set(path + "." + key, val[key], constructing); - } +module.exports = function isIndexEqual(key, options, dbIndex) { + // Special case: text indexes have a special format in the db. For example, + // `{ name: 'text' }` becomes: + // { + // v: 2, + // key: { _fts: 'text', _ftsx: 1 }, + // name: 'name_text', + // ns: 'test.tests', + // background: true, + // weights: { name: 1 }, + // default_language: 'english', + // language_override: 'language', + // textIndexVersion: 3 + // } + if (dbIndex.textIndexVersion != null) { + delete dbIndex.key._fts; + delete dbIndex.key._ftsx; + const weights = { ...dbIndex.weights, ...dbIndex.key }; + if (Object.keys(weights).length !== Object.keys(key).length) { + return false; + } + for (const prop of Object.keys(weights)) { + if (!(prop in key)) { + return false; + } + const weight = weights[prop]; + if (weight !== get(options, 'weights.' + prop) && !(weight === 1 && get(options, 'weights.' + prop) == null)) { + return false; + } + } - if ( - hasPriorVal && - utils.deepEqual(this.$__.savedState[path], val) - ) { - this.unmarkModified(path); - } else { - this.markModified(path); - } - cleanModifiedSubpaths(this, path, { skipDocArrays: true }); - return this; - } - this.invalidate( - path, - new MongooseError.CastError("Object", val, path) - ); - return this; - } + if (options['default_language'] !== dbIndex['default_language']) { + return dbIndex['default_language'] === 'english' && options['default_language'] == null; + } - let schema; - const parts = path.indexOf(".") === -1 ? [path] : path.split("."); + return true; + } - // Might need to change path for top-level alias - if (typeof this.$__schema.aliases[parts[0]] == "string") { - parts[0] = this.$__schema.aliases[parts[0]]; + const optionKeys = [ + 'unique', + 'partialFilterExpression', + 'sparse', + 'expireAfterSeconds', + 'collation' + ]; + for (const key of optionKeys) { + if (!(key in options) && !(key in dbIndex)) { + continue; + } + if (key === 'collation') { + if (options[key] == null || dbIndex[key] == null) { + return options[key] == null && dbIndex[key] == null; + } + const definedKeys = Object.keys(options.collation); + const schemaCollation = options.collation; + const dbCollation = dbIndex.collation; + for (const opt of definedKeys) { + if (get(schemaCollation, opt) !== get(dbCollation, opt)) { + return false; } + } + } else if (!utils.deepEqual(options[key], dbIndex[key])) { + return false; + } + } - if (pathType === "adhocOrUndefined" && strict) { - // check for roots that are Mixed types - let mixed; - - for (i = 0; i < parts.length; ++i) { - const subpath = parts.slice(0, i + 1).join("."); - - // If path is underneath a virtual, bypass everything and just set it. - if ( - i + 1 < parts.length && - this.$__schema.pathType(subpath) === "virtual" - ) { - mpath.set(path, val, this); - return this; - } + const schemaIndexKeys = Object.keys(key); + const dbIndexKeys = Object.keys(dbIndex.key); + if (schemaIndexKeys.length !== dbIndexKeys.length) { + return false; + } + for (let i = 0; i < schemaIndexKeys.length; ++i) { + if (schemaIndexKeys[i] !== dbIndexKeys[i]) { + return false; + } + if (!utils.deepEqual(key[schemaIndexKeys[i]], dbIndex.key[dbIndexKeys[i]])) { + return false; + } + } - schema = this.$__schema.path(subpath); - if (schema == null) { - continue; - } + return true; +}; - if (schema instanceof MixedSchema) { - // allow changes to sub paths of mixed types - mixed = true; - break; - } - } - if (schema == null) { - // Check for embedded discriminators - schema = getEmbeddedDiscriminatorPath(this, path); - } +/***/ }), - if (!mixed && !schema) { - if (strict === "throw") { - throw new StrictModeError(path); - } - return this; - } - } else if (pathType === "virtual") { - schema = this.$__schema.virtualpath(path); - schema.applySetters(val, this); - return this; - } else { - schema = this.$__path(path); - } - - // gh-4578, if setting a deeply nested path that doesn't exist yet, create it - let cur = this._doc; - let curPath = ""; - for (i = 0; i < parts.length - 1; ++i) { - cur = cur[parts[i]]; - curPath += (curPath.length > 0 ? "." : "") + parts[i]; - if (!cur) { - this.$set(curPath, {}); - // Hack re: gh-5800. If nested field is not selected, it probably exists - // so `MongoError: cannot use the part (nested of nested.num) to - // traverse the element ({nested: null})` is not likely. If user gets - // that error, its their fault for now. We should reconsider disallowing - // modifying not selected paths for 6.x - if (!this.$__isSelected(curPath)) { - this.unmarkModified(curPath); - } - cur = this.$__getValue(curPath); - } - } +/***/ 6073: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - let pathToMark; +"use strict"; - // When using the $set operator the path to the field must already exist. - // Else mongodb throws: "LEFT_SUBFIELD only supports Object" - if (parts.length <= 1) { - pathToMark = path; - } else { - for (i = 0; i < parts.length; ++i) { - const subpath = parts.slice(0, i + 1).join("."); - if (this.get(subpath, null, { getters: false }) === null) { - pathToMark = subpath; - break; - } - } +const { inspect } = __nccwpck_require__(1669); - if (!pathToMark) { - pathToMark = path; - } - } +module.exports = function isAsyncFunction(v) { + if (typeof v !== 'function') { + return; + } - // if this doc is being constructed we should not trigger getters - const priorVal = (() => { - if (this.$__.$options.priorDoc != null) { - return this.$__.$options.priorDoc.$__getValue(path); - } - if (constructing) { - return void 0; - } - return this.$__getValue(path); - })(); - - if (!schema) { - this.$__set( - pathToMark, - path, - constructing, - parts, - schema, - val, - priorVal - ); - return this; - } + return inspect(v).startsWith('[AsyncFunction:'); +}; - // If overwriting a subdocument path, make sure to clear out - // any errors _before_ setting, so new errors that happen - // get persisted. Re: #9080 - if (schema.$isSingleNested || schema.$isMongooseArray) { - _markValidSubpaths(this, path); - } +/***/ }), - if (schema.$isSingleNested && val != null && merge) { - if (val instanceof Document) { - val = val.toObject({ virtuals: false, transform: false }); - } - const keys = Object.keys(val); - for (const key of keys) { - this.$set(path + "." + key, val[key], constructing, options); - } +/***/ 8275: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return this; - } +"use strict"; - let shouldSet = true; - try { - // If the user is trying to set a ref path to a document with - // the correct model name, treat it as populated - const refMatches = (() => { - if (schema.options == null) { - return false; - } - if (!(val instanceof Document)) { - return false; - } - const model = val.constructor; - - // Check ref - const ref = schema.options.ref; - if ( - ref != null && - (ref === model.modelName || ref === model.baseModelName) - ) { - return true; - } - - // Check refPath - const refPath = schema.options.refPath; - if (refPath == null) { - return false; - } - const modelName = val.get(refPath); - return ( - modelName === model.modelName || modelName === model.baseModelName - ); - })(); - let didPopulate = false; - if (refMatches && val instanceof Document) { - this.populated(path, val._id, { - [populateModelSymbol]: val.constructor, - }); - val.$__.wasPopulated = true; - didPopulate = true; - } +const get = __nccwpck_require__(8730); - let popOpts; - if ( - schema.options && - Array.isArray(schema.options[typeKey]) && - schema.options[typeKey].length && - schema.options[typeKey][0].ref && - _isManuallyPopulatedArray(val, schema.options[typeKey][0].ref) - ) { - popOpts = { [populateModelSymbol]: val[0].constructor }; - this.populated( - path, - val.map(function (v) { - return v._id; - }), - popOpts - ); +/*! + * Get the bson type, if it exists + */ - for (const doc of val) { - doc.$__.wasPopulated = true; - } - didPopulate = true; - } +function isBsonType(obj, typename) { + return get(obj, '_bsontype', void 0) === typename; +} - if (this.$__schema.singleNestedPaths[path] == null) { - // If this path is underneath a single nested schema, we'll call the setter - // later in `$__set()` because we don't take `_doc` when we iterate through - // a single nested doc. That's to make sure we get the correct context. - // Otherwise we would double-call the setter, see gh-7196. - val = schema.applySetters(val, this, false, priorVal); - } +module.exports = isBsonType; - if ( - schema.$isMongooseDocumentArray && - Array.isArray(val) && - val.length > 0 && - val[0] != null && - val[0].$__ != null && - val[0].$__.populated != null - ) { - const populatedPaths = Object.keys(val[0].$__.populated); - for (const populatedPath of populatedPaths) { - this.populated( - path + "." + populatedPath, - val.map((v) => v.populated(populatedPath)), - val[0].$__.populated[populatedPath].options - ); - } - didPopulate = true; - } - if (!didPopulate && this.$__.populated) { - // If this array partially contains populated documents, convert them - // all to ObjectIds re: #8443 - if (Array.isArray(val) && this.$__.populated[path]) { - for (let i = 0; i < val.length; ++i) { - if (val[i] instanceof Document) { - val[i] = val[i]._id; - } - } - } - delete this.$__.populated[path]; - } +/***/ }), - if (schema.$isSingleNested && val != null) { - _checkImmutableSubpaths(val, schema, priorVal); - } +/***/ 7104: +/***/ ((module) => { - this.$markValid(path); - } catch (e) { - if ( - e instanceof MongooseError.StrictModeError && - e.isImmutableError - ) { - this.invalidate(path, e); - } else if (e instanceof MongooseError.CastError) { - this.invalidate(e.path, e); - if (e.$originalErrorPath) { - this.invalidate( - path, - new MongooseError.CastError( - schema.instance, - val, - path, - e.$originalErrorPath - ) - ); - } - } else { - this.invalidate( - path, - new MongooseError.CastError(schema.instance, val, path, e) - ); - } - shouldSet = false; - } +"use strict"; - if (shouldSet) { - this.$__set( - pathToMark, - path, - constructing, - parts, - schema, - val, - priorVal - ); - if (this.$__.savedState != null) { - if (!this.isNew && !this.$__.savedState.hasOwnProperty(path)) { - this.$__.savedState[path] = priorVal; - } else if ( - this.$__.savedState.hasOwnProperty(path) && - utils.deepEqual(val, this.$__.savedState[path]) - ) { - this.unmarkModified(path); - } - } - } +/*! + * Returns if `v` is a mongoose object that has a `toObject()` method we can use. + * + * This is for compatibility with libs like Date.js which do foolish things to Natives. + * + * @param {any} v + * @api private + */ - if ( - schema.$isSingleNested && - (this.isDirectModified(path) || val == null) - ) { - cleanModifiedSubpaths(this, path); - } +module.exports = function(v) { + if (v == null) { + return false; + } - return this; - }; + return v.$__ != null || // Document + v.isMongooseArray || // Array or Document Array + v.isMongooseBuffer || // Buffer + v.$isMongooseMap; // Map +}; - /*! - * ignore - */ +/***/ }), - function _isManuallyPopulatedArray(val, ref) { - if (!Array.isArray(val)) { - return false; - } - if (val.length === 0) { - return false; - } +/***/ 273: +/***/ ((module) => { - for (const el of val) { - if (!(el instanceof Document)) { - return false; - } - const modelName = el.constructor.modelName; - if (modelName == null) { - return false; - } - if ( - el.constructor.modelName != ref && - el.constructor.baseModelName != ref - ) { - return false; - } - } +"use strict"; - return true; - } - /** - * Sets the value of a path, or many paths. - * - * ####Example: - * - * // path, value - * doc.set(path, value) - * - * // object - * doc.set({ - * path : value - * , path2 : { - * path : value - * } - * }) - * - * // on-the-fly cast to number - * doc.set(path, value, Number) - * - * // on-the-fly cast to string - * doc.set(path, value, String) - * - * // changing strict mode behavior - * doc.set(path, value, { strict: false }); - * - * @param {String|Object} path path or object of key/vals to set - * @param {Any} val the value to set - * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes - * @param {Object} [options] optionally specify options that modify the behavior of the set - * @api public - * @method set - * @memberOf Document - * @instance - */ - - Document.prototype.set = Document.prototype.$set; - - /** - * Determine if we should mark this change as modified. - * - * @return {Boolean} - * @api private - * @method $__shouldModify - * @memberOf Document - * @instance - */ - - Document.prototype.$__shouldModify = function ( - pathToMark, - path, - constructing, - parts, - schema, - val, - priorVal - ) { - if (this.isNew) { - return true; - } - - // Re: the note about gh-7196, `val` is the raw value without casting or - // setters if the full path is under a single nested subdoc because we don't - // want to double run setters. So don't set it as modified. See gh-7264. - if (this.$__schema.singleNestedPaths[path] != null) { - return false; - } +/*! + * Determines if `arg` is an object. + * + * @param {Object|Array|String|Function|RegExp|any} arg + * @api private + * @return {Boolean} + */ - if (val === void 0 && !this.$__isSelected(path)) { - // when a path is not selected in a query, its initial - // value will be undefined. - return true; - } +module.exports = function(arg) { + if (Buffer.isBuffer(arg)) { + return true; + } + return Object.prototype.toString.call(arg) === '[object Object]'; +}; - if (val === void 0 && path in this.$__.activePaths.states.default) { - // we're just unsetting the default value which was never saved - return false; - } +/***/ }), - // gh-3992: if setting a populated field to a doc, don't mark modified - // if they have the same _id - if ( - this.populated(path) && - val instanceof Document && - deepEqual(val._id, priorVal) - ) { - return false; - } +/***/ 224: +/***/ ((module) => { - if (!deepEqual(val, priorVal || utils.getValue(path, this))) { - return true; - } +"use strict"; - if ( - !constructing && - val !== null && - val !== undefined && - path in this.$__.activePaths.states.default && - deepEqual(val, schema.getDefault(this, constructing)) - ) { - // a path with a default was $unset on the server - // and the user is setting it to the same value again - return true; - } - return false; - }; +function isPromise(val) { + return !!val && (typeof val === 'object' || typeof val === 'function') && typeof val.then === 'function'; +} - /** - * Handles the actual setting of the value and marking the path modified if appropriate. - * - * @api private - * @method $__set - * @memberOf Document - * @instance - */ - - Document.prototype.$__set = function ( - pathToMark, - path, - constructing, - parts, - schema, - val, - priorVal - ) { - Embedded = Embedded || __nccwpck_require__(4433); - - const shouldModify = this.$__shouldModify( - pathToMark, - path, - constructing, - parts, - schema, - val, - priorVal - ); - const _this = this; +module.exports = isPromise; - if (shouldModify) { - this.markModified(pathToMark); +/***/ }), - // handle directly setting arrays (gh-1126) - MongooseArray || (MongooseArray = __nccwpck_require__(6628)); - if (val && val.isMongooseArray) { - val._registerAtomic("$set", val); +/***/ 5373: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Update embedded document parent references (gh-5189) - if (val.isMongooseDocumentArray) { - val.forEach(function (item) { - item && item.__parentArray && (item.__parentArray = val); - }); - } +"use strict"; - // Small hack for gh-1638: if we're overwriting the entire array, ignore - // paths that were modified before the array overwrite - this.$__.activePaths.forEach(function (modifiedPath) { - if (modifiedPath.startsWith(path + ".")) { - _this.$__.activePaths.ignore(modifiedPath); - } - }); - } - } - let obj = this._doc; - let i = 0; - const l = parts.length; - let cur = ""; +const symbols = __nccwpck_require__(1205); +const promiseOrCallback = __nccwpck_require__(4046); - for (; i < l; i++) { - const next = i + 1; - const last = next === l; - cur += cur ? "." + parts[i] : parts[i]; - if (specialProperties.has(parts[i])) { - return; - } +/*! + * ignore + */ - if (last) { - if (obj instanceof Map) { - obj.set(parts[i], val); - } else { - obj[parts[i]] = val; - } - } else { - if (utils.isPOJO(obj[parts[i]])) { - obj = obj[parts[i]]; - } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) { - obj = obj[parts[i]]; - } else if (obj[parts[i]] && obj[parts[i]].$isSingleNested) { - obj = obj[parts[i]]; - } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) { - obj = obj[parts[i]]; - } else { - obj[parts[i]] = obj[parts[i]] || {}; - obj = obj[parts[i]]; - } - } - } - }; +module.exports = applyHooks; - /** - * Gets a raw value from a path (no getters) - * - * @param {String} path - * @api private - */ +/*! + * ignore + */ - Document.prototype.$__getValue = function (path) { - return utils.getValue(path, this._doc); - }; +applyHooks.middlewareFunctions = [ + 'deleteOne', + 'save', + 'validate', + 'remove', + 'updateOne', + 'init' +]; + +/*! + * Register hooks for this model + * + * @param {Model} model + * @param {Schema} schema + */ - /** - * Sets a raw value for a path (no casting, setters, transformations) - * - * @param {String} path - * @param {Object} value - * @api private - */ +function applyHooks(model, schema, options) { + options = options || {}; - Document.prototype.$__setValue = function (path, val) { - utils.setValue(path, val, this._doc); - return this; - }; + const kareemOptions = { + useErrorHandlers: true, + numCallbackParams: 1, + nullResultByDefault: true, + contextParameter: true + }; + const objToDecorate = options.decorateDoc ? model : model.prototype; + + model.$appliedHooks = true; + for (const key of Object.keys(schema.paths)) { + const type = schema.paths[key]; + let childModel = null; + if (type.$isSingleNested) { + childModel = type.caster; + } else if (type.$isMongooseDocumentArray) { + childModel = type.Constructor; + } else { + continue; + } - /** - * Returns the value of a path. - * - * ####Example - * - * // path - * doc.get('age') // 47 - * - * // dynamic casting to a string - * doc.get('age', String) // "47" - * - * @param {String} path - * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for on-the-fly attributes - * @param {Object} [options] - * @param {Boolean} [options.virtuals=false] Apply virtuals before getting this path - * @param {Boolean} [options.getters=true] If false, skip applying getters and just get the raw value - * @api public - */ - - Document.prototype.get = function (path, type, options) { - let adhoc; - options = options || {}; - if (type) { - adhoc = this.$__schema.interpretAsType( - path, - type, - this.$__schema.options - ); - } + if (childModel.$appliedHooks) { + continue; + } - let schema = this.$__path(path); - if (schema == null) { - schema = this.$__schema.virtualpath(path); - } - if (schema instanceof MixedSchema) { - const virtual = this.$__schema.virtualpath(path); - if (virtual != null) { - schema = virtual; - } - } - const pieces = path.indexOf(".") === -1 ? [path] : path.split("."); - let obj = this._doc; + applyHooks(childModel, type.schema, options); + if (childModel.discriminators != null) { + const keys = Object.keys(childModel.discriminators); + for (const key of keys) { + applyHooks(childModel.discriminators[key], + childModel.discriminators[key].schema, options); + } + } + } - if (schema instanceof VirtualType) { - return schema.applyGetters(void 0, this); - } + // Built-in hooks rely on hooking internal functions in order to support + // promises and make it so that `doc.save.toString()` provides meaningful + // information. - // Might need to change path for top-level alias - if (typeof this.$__schema.aliases[pieces[0]] == "string") { - pieces[0] = this.$__schema.aliases[pieces[0]]; - } + const middleware = schema.s.hooks. + filter(hook => { + if (hook.name === 'updateOne' || hook.name === 'deleteOne') { + return !!hook['document']; + } + if (hook.name === 'remove' || hook.name === 'init') { + return hook['document'] == null || !!hook['document']; + } + if (hook.query != null || hook.document != null) { + return hook.document !== false; + } + return true; + }). + filter(hook => { + // If user has overwritten the method, don't apply built-in middleware + if (schema.methods[hook.name]) { + return !hook.fn[symbols.builtInMiddleware]; + } - for (let i = 0, l = pieces.length; i < l; i++) { - if (obj && obj._doc) { - obj = obj._doc; - } + return true; + }); - if (obj == null) { - obj = void 0; - } else if (obj instanceof Map) { - obj = obj.get(pieces[i], { getters: false }); - } else if (i === l - 1) { - obj = utils.getValue(pieces[i], obj); - } else { - obj = obj[pieces[i]]; - } - } + model._middleware = middleware; - if (adhoc) { - obj = adhoc.cast(obj); - } + objToDecorate.$__originalValidate = objToDecorate.$__originalValidate || objToDecorate.$__validate; - if (schema != null && options.getters !== false) { - obj = schema.applyGetters(obj, this); - } else if (this.$__schema.nested[path] && options.virtuals) { - // Might need to apply virtuals if this is a nested path - return applyVirtuals(this, utils.clone(obj) || {}, { path: path }); - } + for (const method of ['save', 'validate', 'remove', 'deleteOne']) { + const toWrap = method === 'validate' ? '$__originalValidate' : `$__${method}`; + const wrapped = middleware. + createWrapper(method, objToDecorate[toWrap], null, kareemOptions); + objToDecorate[`$__${method}`] = wrapped; + } + objToDecorate.$__init = middleware. + createWrapperSync('init', objToDecorate.$__init, null, kareemOptions); + + // Support hooks for custom methods + const customMethods = Object.keys(schema.methods); + const customMethodOptions = Object.assign({}, kareemOptions, { + // Only use `checkForPromise` for custom methods, because mongoose + // query thunks are not as consistent as I would like about returning + // a nullish value rather than the query. If a query thunk returns + // a query, `checkForPromise` causes infinite recursion + checkForPromise: true + }); + for (const method of customMethods) { + if (!middleware.hasHooks(method)) { + // Don't wrap if there are no hooks for the custom method to avoid + // surprises. Also, `createWrapper()` enforces consistent async, + // so wrapping a sync method would break it. + continue; + } + const originalMethod = objToDecorate[method]; + objToDecorate[method] = function() { + const args = Array.prototype.slice.call(arguments); + const cb = args.slice(-1).pop(); + const argsWithoutCallback = typeof cb === 'function' ? + args.slice(0, args.length - 1) : args; + return promiseOrCallback(cb, callback => { + return this[`$__${method}`].apply(this, + argsWithoutCallback.concat([callback])); + }, model.events); + }; + objToDecorate[`$__${method}`] = middleware. + createWrapper(method, originalMethod, null, customMethodOptions); + } +} - return obj; - }; +/***/ }), - /*! - * ignore - */ +/***/ 3543: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Document.prototype[getSymbol] = Document.prototype.get; +"use strict"; - /** - * Returns the schematype for the given `path`. - * - * @param {String} path - * @api private - * @method $__path - * @memberOf Document - * @instance - */ - Document.prototype.$__path = function (path) { - const adhocs = this.$__.adhocPaths; - const adhocType = - adhocs && adhocs.hasOwnProperty(path) ? adhocs[path] : null; +const get = __nccwpck_require__(8730); +const utils = __nccwpck_require__(9232); - if (adhocType) { - return adhocType; - } - return this.$__schema.path(path); - }; +/*! + * Register methods for this model + * + * @param {Model} model + * @param {Schema} schema + */ - /** - * Marks the path as having pending changes to write to the db. - * - * _Very helpful when using [Mixed](./schematypes.html#mixed) types._ - * - * ####Example: - * - * doc.mixed.type = 'changed'; - * doc.markModified('mixed.type'); - * doc.save() // changes to mixed.type are now persisted - * - * @param {String} path the path to mark modified - * @param {Document} [scope] the scope to run validators with - * @api public - */ - - Document.prototype.markModified = function (path, scope) { - this.$__.activePaths.modify(path); - if (scope != null && !this.ownerDocument) { - this.$__.pathsToScopes[path] = scope; +module.exports = function applyMethods(model, schema) { + function apply(method, schema) { + Object.defineProperty(model.prototype, method, { + get: function() { + const h = {}; + for (const k in schema.methods[method]) { + h[k] = schema.methods[method][k].bind(this); } - }; - - /** - * Clears the modified state on the specified path. - * - * ####Example: - * - * doc.foo = 'bar'; - * doc.unmarkModified('foo'); - * doc.save(); // changes to foo will not be persisted - * - * @param {String} path the path to unmark modified - * @api public - */ - - Document.prototype.unmarkModified = function (path) { - this.$__.activePaths.init(path); - delete this.$__.pathsToScopes[path]; - }; + return h; + }, + configurable: true + }); + } + for (const method of Object.keys(schema.methods)) { + const fn = schema.methods[method]; + if (schema.tree.hasOwnProperty(method)) { + throw new Error('You have a method and a property in your schema both ' + + 'named "' + method + '"'); + } + if (schema.reserved[method] && + !get(schema, `methodOptions.${method}.suppressWarning`, false)) { + utils.warn(`mongoose: the method name "${method}" is used by mongoose ` + + 'internally, overwriting it may cause bugs. If you\'re sure you know ' + + 'what you\'re doing, you can suppress this error by using ' + + `\`schema.method('${method}', fn, { suppressWarning: true })\`.`); + } + if (typeof fn === 'function') { + model.prototype[method] = fn; + } else { + apply(method, schema); + } + } - /** - * Don't run validation on this path or persist changes to this path. - * - * ####Example: - * - * doc.foo = null; - * doc.$ignore('foo'); - * doc.save(); // changes to foo will not be persisted and validators won't be run - * - * @memberOf Document - * @instance - * @method $ignore - * @param {String} path the path to ignore - * @api public - */ - - Document.prototype.$ignore = function (path) { - this.$__.activePaths.ignore(path); - }; + // Recursively call `applyMethods()` on child schemas + model.$appliedMethods = true; + for (const key of Object.keys(schema.paths)) { + const type = schema.paths[key]; + if (type.$isSingleNested && !type.caster.$appliedMethods) { + applyMethods(type.caster, type.schema); + } + if (type.$isMongooseDocumentArray && !type.Constructor.$appliedMethods) { + applyMethods(type.Constructor, type.schema); + } + } +}; - /** - * Returns the list of paths that have been directly modified. A direct - * modified path is a path that you explicitly set, whether via `doc.foo = 'bar'`, - * `Object.assign(doc, { foo: 'bar' })`, or `doc.set('foo', 'bar')`. - * - * A path `a` may be in `modifiedPaths()` but not in `directModifiedPaths()` - * because a child of `a` was directly modified. - * - * ####Example - * const schema = new Schema({ foo: String, nested: { bar: String } }); - * const Model = mongoose.model('Test', schema); - * await Model.create({ foo: 'original', nested: { bar: 'original' } }); - * - * const doc = await Model.findOne(); - * doc.nested.bar = 'modified'; - * doc.directModifiedPaths(); // ['nested.bar'] - * doc.modifiedPaths(); // ['nested', 'nested.bar'] - * - * @return {Array} - * @api public - */ - - Document.prototype.directModifiedPaths = function () { - return Object.keys(this.$__.activePaths.states.modify); - }; - /** - * Returns true if the given path is nullish or only contains empty objects. - * Useful for determining whether this subdoc will get stripped out by the - * [minimize option](/docs/guide.html#minimize). - * - * ####Example: - * const schema = new Schema({ nested: { foo: String } }); - * const Model = mongoose.model('Test', schema); - * const doc = new Model({}); - * doc.$isEmpty('nested'); // true - * doc.nested.$isEmpty(); // true - * - * doc.nested.foo = 'bar'; - * doc.$isEmpty('nested'); // false - * doc.nested.$isEmpty(); // false - * - * @memberOf Document - * @instance - * @api public - * @method $isEmpty - * @return {Boolean} - */ - - Document.prototype.$isEmpty = function (path) { - const isEmptyOptions = { - minimize: true, - virtuals: false, - getters: false, - transform: false, - }; +/***/ }), - if (arguments.length > 0) { - const v = this.get(path); - if (v == null) { - return true; - } - if (typeof v !== "object") { - return false; - } - if (utils.isPOJO(v)) { - return _isEmpty(v); - } - return Object.keys(v.toObject(isEmptyOptions)).length === 0; - } +/***/ 3739: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return Object.keys(this.toObject(isEmptyOptions)).length === 0; - }; +"use strict"; - function _isEmpty(v) { - if (v == null) { - return true; - } - if (typeof v !== "object" || Array.isArray(v)) { - return false; - } - for (const key of Object.keys(v)) { - if (!_isEmpty(v[key])) { - return false; - } - } - return true; - } - /** - * Returns the list of paths that have been modified. - * - * @param {Object} [options] - * @param {Boolean} [options.includeChildren=false] if true, returns children of modified paths as well. For example, if false, the list of modified paths for `doc.colors = { primary: 'blue' };` will **not** contain `colors.primary`. If true, `modifiedPaths()` will return an array that contains `colors.primary`. - * @return {Array} - * @api public - */ +const middlewareFunctions = __nccwpck_require__(7378).middlewareFunctions; +const promiseOrCallback = __nccwpck_require__(4046); - Document.prototype.modifiedPaths = function (options) { - options = options || {}; - const directModifiedPaths = Object.keys( - this.$__.activePaths.states.modify - ); - const _this = this; - return directModifiedPaths.reduce(function (list, path) { - const parts = path.split("."); - list = list.concat( - parts - .reduce(function (chains, part, i) { - return chains.concat(parts.slice(0, i).concat(part).join(".")); - }, []) - .filter(function (chain) { - return list.indexOf(chain) === -1; - }) - ); +module.exports = function applyStaticHooks(model, hooks, statics) { + const kareemOptions = { + useErrorHandlers: true, + numCallbackParams: 1 + }; - if (!options.includeChildren) { - return list; - } + hooks = hooks.filter(hook => { + // If the custom static overwrites an existing query middleware, don't apply + // middleware to it by default. This avoids a potential backwards breaking + // change with plugins like `mongoose-delete` that use statics to overwrite + // built-in Mongoose functions. + if (middlewareFunctions.indexOf(hook.name) !== -1) { + return !!hook.model; + } + return hook.model !== false; + }); + + model.$__insertMany = hooks.createWrapper('insertMany', + model.$__insertMany, model, kareemOptions); + + for (const key of Object.keys(statics)) { + if (hooks.hasHooks(key)) { + const original = model[key]; + + model[key] = function() { + const numArgs = arguments.length; + const lastArg = numArgs > 0 ? arguments[numArgs - 1] : null; + const cb = typeof lastArg === 'function' ? lastArg : null; + const args = Array.prototype.slice. + call(arguments, 0, cb == null ? numArgs : numArgs - 1); + // Special case: can't use `Kareem#wrap()` because it doesn't currently + // support wrapped functions that return a promise. + return promiseOrCallback(cb, callback => { + hooks.execPre(key, model, args, function(err) { + if (err != null) { + return callback(err); + } - let cur = _this.get(path); - if (cur != null && typeof cur === "object") { - if (cur._doc) { - cur = cur._doc; - } - if (Array.isArray(cur)) { - const len = cur.length; - for (let i = 0; i < len; ++i) { - if (list.indexOf(path + "." + i) === -1) { - list.push(path + "." + i); - if (cur[i] != null && cur[i].$__) { - const modified = cur[i].modifiedPaths(); - for (const childPath of modified) { - list.push(path + "." + i + "." + childPath); - } - } - } - } - } else { - Object.keys(cur) - .filter(function (key) { - return list.indexOf(path + "." + key) === -1; - }) - .forEach(function (key) { - list.push(path + "." + key); - }); + let postCalled = 0; + const ret = original.apply(model, args.concat(post)); + if (ret != null && typeof ret.then === 'function') { + ret.then(res => post(null, res), err => post(err)); } - } - return list; - }, []); - }; + function post(error, res) { + if (postCalled++ > 0) { + return; + } - Document.prototype[documentModifiedPaths] = - Document.prototype.modifiedPaths; - - /** - * Returns true if any of the given paths is modified, else false. If no arguments, returns `true` if any path - * in this document is modified. - * - * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified. - * - * ####Example - * - * doc.set('documents.0.title', 'changed'); - * doc.isModified() // true - * doc.isModified('documents') // true - * doc.isModified('documents.0.title') // true - * doc.isModified('documents otherProp') // true - * doc.isDirectModified('documents') // false - * - * @param {String} [path] optional - * @return {Boolean} - * @api public - */ - - Document.prototype.isModified = function (paths, modifiedPaths) { - if (paths) { - if (!Array.isArray(paths)) { - paths = paths.split(" "); - } - const modified = modifiedPaths || this[documentModifiedPaths](); - const directModifiedPaths = Object.keys( - this.$__.activePaths.states.modify - ); - const isModifiedChild = paths.some(function (path) { - return !!~modified.indexOf(path); - }); + if (error != null) { + return callback(error); + } - return ( - isModifiedChild || - paths.some(function (path) { - return directModifiedPaths.some(function (mod) { - return mod === path || path.startsWith(mod + "."); + hooks.execPost(key, model, [res], function(error) { + if (error != null) { + return callback(error); + } + callback(null, res); }); - }) - ); - } - - return this.$__.activePaths.some("modify"); + } + }); + }, model.events); }; + } + } +}; - Document.prototype[documentIsModified] = Document.prototype.isModified; +/***/ }), - /** - * Checks if a path is set to its default. - * - * ####Example - * - * MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} }); - * const m = new MyModel(); - * m.$isDefault('name'); // true - * - * @memberOf Document - * @instance - * @method $isDefault - * @param {String} [path] - * @return {Boolean} - * @api public - */ +/***/ 5220: +/***/ ((module) => { - Document.prototype.$isDefault = function (path) { - if (path == null) { - return this.$__.activePaths.some("default"); - } +"use strict"; - if (typeof path === "string" && path.indexOf(" ") === -1) { - return this.$__.activePaths.states.default.hasOwnProperty(path); - } - let paths = path; - if (!Array.isArray(paths)) { - paths = paths.split(" "); - } +/*! + * Register statics for this model + * @param {Model} model + * @param {Schema} schema + */ +module.exports = function applyStatics(model, schema) { + for (const i in schema.statics) { + model[i] = schema.statics[i]; + } +}; - return paths.some((path) => - this.$__.activePaths.states.default.hasOwnProperty(path) - ); - }; - /** - * Getter/setter, determines whether the document was removed or not. - * - * ####Example: - * product.remove(function (err, product) { - * product.$isDeleted(); // true - * product.remove(); // no-op, doesn't send anything to the db - * - * product.$isDeleted(false); - * product.$isDeleted(); // false - * product.remove(); // will execute a remove against the db - * }) - * - * @param {Boolean} [val] optional, overrides whether mongoose thinks the doc is deleted - * @return {Boolean} whether mongoose thinks this doc is deleted. - * @method $isDeleted - * @memberOf Document - * @instance - * @api public - */ - - Document.prototype.$isDeleted = function (val) { - if (arguments.length === 0) { - return !!this.$__.isDeleted; - } - - this.$__.isDeleted = !!val; - return this; - }; +/***/ }), - /** - * Returns true if `path` was directly set and modified, else false. - * - * ####Example - * - * doc.set('documents.0.title', 'changed'); - * doc.isDirectModified('documents.0.title') // true - * doc.isDirectModified('documents') // false - * - * @param {String|Array} path - * @return {Boolean} - * @api public - */ +/***/ 4531: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Document.prototype.isDirectModified = function (path) { - if (path == null) { - return this.$__.activePaths.some("modify"); - } +"use strict"; - if (typeof path === "string" && path.indexOf(" ") === -1) { - return this.$__.activePaths.states.modify.hasOwnProperty(path); - } - let paths = path; - if (!Array.isArray(paths)) { - paths = paths.split(" "); - } +const getDiscriminatorByValue = __nccwpck_require__(8689); +const applyTimestampsToChildren = __nccwpck_require__(1975); +const applyTimestampsToUpdate = __nccwpck_require__(1162); +const cast = __nccwpck_require__(9179); +const castUpdate = __nccwpck_require__(3303); +const setDefaultsOnInsert = __nccwpck_require__(5937); - return paths.some((path) => - this.$__.activePaths.states.modify.hasOwnProperty(path) - ); - }; +/*! + * Given a model and a bulkWrite op, return a thunk that handles casting and + * validating the individual op. + */ - /** - * Checks if `path` is in the `init` state, that is, it was set by `Document#init()` and not modified since. - * - * @param {String} path - * @return {Boolean} - * @api public - */ +module.exports = function castBulkWrite(originalModel, op, options) { + const now = originalModel.base.now(); - Document.prototype.isInit = function (path) { - if (path == null) { - return this.$__.activePaths.some("init"); - } + if (op['insertOne']) { + return (callback) => { + const model = decideModelByObject(originalModel, op['insertOne']['document']); - if (typeof path === "string" && path.indexOf(" ") === -1) { - return this.$__.activePaths.states.init.hasOwnProperty(path); + const doc = new model(op['insertOne']['document']); + if (model.schema.options.timestamps) { + doc.initializeTimestamps(); + } + if (options.session != null) { + doc.$session(options.session); + } + op['insertOne']['document'] = doc; + op['insertOne']['document'].$validate({ __noPromise: true }, function(error) { + if (error) { + return callback(error, null); } - - let paths = path; - if (!Array.isArray(paths)) { - paths = paths.split(" "); + callback(null); + }); + }; + } else if (op['updateOne']) { + return (callback) => { + try { + if (!op['updateOne']['filter']) { + throw new Error('Must provide a filter object.'); + } + if (!op['updateOne']['update']) { + throw new Error('Must provide an update object.'); } - return paths.some((path) => - this.$__.activePaths.states.init.hasOwnProperty(path) - ); - }; + const model = decideModelByObject(originalModel, op['updateOne']['filter']); + const schema = model.schema; + const strict = options.strict != null ? options.strict : model.schema.options.strict; - /** - * Checks if `path` was selected in the source query which initialized this document. - * - * ####Example - * - * Thing.findOne().select('name').exec(function (err, doc) { - * doc.isSelected('name') // true - * doc.isSelected('age') // false - * }) - * - * @param {String|Array} path - * @return {Boolean} - * @api public - */ + _addDiscriminatorToObject(schema, op['updateOne']['filter']); - Document.prototype.isSelected = function isSelected(path) { - if (this.$__.selected == null) { - return true; + if (model.schema.$timestamps != null && op['updateOne'].timestamps !== false) { + const createdAt = model.schema.$timestamps.createdAt; + const updatedAt = model.schema.$timestamps.updatedAt; + applyTimestampsToUpdate(now, createdAt, updatedAt, op['updateOne']['update'], {}); } - if (path === "_id") { - return this.$__.selected._id !== 0; - } + applyTimestampsToChildren(now, op['updateOne']['update'], model.schema); - if (path.indexOf(" ") !== -1) { - path = path.split(" "); - } - if (Array.isArray(path)) { - return path.some((p) => this.$__isSelected(p)); + if (op['updateOne'].setDefaultsOnInsert !== false) { + setDefaultsOnInsert(op['updateOne']['filter'], model.schema, op['updateOne']['update'], { + setDefaultsOnInsert: true, + upsert: op['updateOne'].upsert + }); } - const paths = Object.keys(this.$__.selected); - let inclusive = null; + op['updateOne']['filter'] = cast(model.schema, op['updateOne']['filter'], { + strict: strict, + upsert: op['updateOne'].upsert + }); + + op['updateOne']['update'] = castUpdate(model.schema, op['updateOne']['update'], { + strict: strict, + overwrite: false, + upsert: op['updateOne'].upsert + }, model, op['updateOne']['filter']); + } catch (error) { + return callback(error, null); + } - if (paths.length === 1 && paths[0] === "_id") { - // only _id was selected. - return this.$__.selected._id === 0; + callback(null); + }; + } else if (op['updateMany']) { + return (callback) => { + try { + if (!op['updateMany']['filter']) { + throw new Error('Must provide a filter object.'); } - - for (const cur of paths) { - if (cur === "_id") { - continue; - } - if (!isDefiningProjection(this.$__.selected[cur])) { - continue; - } - inclusive = !!this.$__.selected[cur]; - break; + if (!op['updateMany']['update']) { + throw new Error('Must provide an update object.'); } - if (inclusive === null) { - return true; + const model = decideModelByObject(originalModel, op['updateMany']['filter']); + const schema = model.schema; + const strict = options.strict != null ? options.strict : model.schema.options.strict; + + if (op['updateMany'].setDefaultsOnInsert !== false) { + setDefaultsOnInsert(op['updateMany']['filter'], model.schema, op['updateMany']['update'], { + setDefaultsOnInsert: true, + upsert: op['updateMany'].upsert + }); } - if (path in this.$__.selected) { - return inclusive; + if (model.schema.$timestamps != null && op['updateMany'].timestamps !== false) { + const createdAt = model.schema.$timestamps.createdAt; + const updatedAt = model.schema.$timestamps.updatedAt; + applyTimestampsToUpdate(now, createdAt, updatedAt, op['updateMany']['update'], {}); } - const pathDot = path + "."; + applyTimestampsToChildren(now, op['updateMany']['update'], model.schema); - for (const cur of paths) { - if (cur === "_id") { - continue; - } + _addDiscriminatorToObject(schema, op['updateMany']['filter']); - if (cur.startsWith(pathDot)) { - return inclusive || cur !== pathDot; - } + op['updateMany']['filter'] = cast(model.schema, op['updateMany']['filter'], { + strict: strict, + upsert: op['updateMany'].upsert + }); - if (pathDot.startsWith(cur + ".")) { - return inclusive; - } - } + op['updateMany']['update'] = castUpdate(model.schema, op['updateMany']['update'], { + strict: strict, + overwrite: false, + upsert: op['updateMany'].upsert + }, model, op['updateMany']['filter']); + } catch (error) { + return callback(error, null); + } - return !inclusive; - }; + callback(null); + }; + } else if (op['replaceOne']) { + return (callback) => { + const model = decideModelByObject(originalModel, op['replaceOne']['filter']); + const schema = model.schema; + const strict = options.strict != null ? options.strict : model.schema.options.strict; - Document.prototype.$__isSelected = Document.prototype.isSelected; + _addDiscriminatorToObject(schema, op['replaceOne']['filter']); + try { + op['replaceOne']['filter'] = cast(model.schema, op['replaceOne']['filter'], { + strict: strict, + upsert: op['replaceOne'].upsert + }); + } catch (error) { + return callback(error, null); + } - /** - * Checks if `path` was explicitly selected. If no projection, always returns - * true. - * - * ####Example - * - * Thing.findOne().select('nested.name').exec(function (err, doc) { - * doc.isDirectSelected('nested.name') // true - * doc.isDirectSelected('nested.otherName') // false - * doc.isDirectSelected('nested') // false - * }) - * - * @param {String} path - * @return {Boolean} - * @api public - */ + // set `skipId`, otherwise we get "_id field cannot be changed" + const doc = new model(op['replaceOne']['replacement'], strict, true); + if (model.schema.options.timestamps) { + doc.initializeTimestamps(); + } + if (options.session != null) { + doc.$session(options.session); + } + op['replaceOne']['replacement'] = doc; - Document.prototype.isDirectSelected = function isDirectSelected(path) { - if (this.$__.selected == null) { - return true; + op['replaceOne']['replacement'].$validate({ __noPromise: true }, function(error) { + if (error) { + return callback(error, null); } + op['replaceOne']['replacement'] = op['replaceOne']['replacement'].toBSON(); + callback(null); + }); + }; + } else if (op['deleteOne']) { + return (callback) => { + const model = decideModelByObject(originalModel, op['deleteOne']['filter']); + const schema = model.schema; - if (path === "_id") { - return this.$__.selected._id !== 0; - } + _addDiscriminatorToObject(schema, op['deleteOne']['filter']); - if (path.indexOf(" ") !== -1) { - path = path.split(" "); - } - if (Array.isArray(path)) { - return path.some((p) => this.isDirectSelected(p)); - } + try { + op['deleteOne']['filter'] = cast(model.schema, + op['deleteOne']['filter']); + } catch (error) { + return callback(error, null); + } - const paths = Object.keys(this.$__.selected); - let inclusive = null; + callback(null); + }; + } else if (op['deleteMany']) { + return (callback) => { + const model = decideModelByObject(originalModel, op['deleteMany']['filter']); + const schema = model.schema; - if (paths.length === 1 && paths[0] === "_id") { - // only _id was selected. - return this.$__.selected._id === 0; - } + _addDiscriminatorToObject(schema, op['deleteMany']['filter']); - for (const cur of paths) { - if (cur === "_id") { - continue; - } - if (!isDefiningProjection(this.$__.selected[cur])) { - continue; - } - inclusive = !!this.$__.selected[cur]; - break; - } + try { + op['deleteMany']['filter'] = cast(model.schema, + op['deleteMany']['filter']); + } catch (error) { + return callback(error, null); + } - if (inclusive === null) { - return true; - } + callback(null); + }; + } else { + return (callback) => { + callback(new Error('Invalid op passed to `bulkWrite()`'), null); + }; + } +}; - if (this.$__.selected.hasOwnProperty(path)) { - return inclusive; - } +function _addDiscriminatorToObject(schema, obj) { + if (schema == null) { + return; + } + if (schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) { + obj[schema.discriminatorMapping.key] = schema.discriminatorMapping.value; + } +} - return !inclusive; - }; +/*! + * gets discriminator model if discriminator key is present in object + */ - /** - * Executes registered validation rules for this document. - * - * ####Note: - * - * This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`. - * - * ####Example: - * - * doc.validate(function (err) { - * if (err) handleError(err); - * else // validation passed - * }); - * - * @param {Array|String} [pathsToValidate] list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list. - * @param {Object} [options] internal options - * @param {Boolean} [options.validateModifiedOnly=false] if `true` mongoose validates only modified paths. - * @param {Array|string} [options.pathsToSkip] list of paths to skip. If set, Mongoose will validate every modified path that is not in this list. - * @param {Function} [callback] optional callback called after validation completes, passing an error if one occurred - * @return {Promise} Promise - * @api public - */ - - Document.prototype.validate = function ( - pathsToValidate, - options, - callback - ) { - let parallelValidate; - this.$op = "validate"; - - if (this.ownerDocument != null) { - // Skip parallel validate check for subdocuments - } else if (this.$__.validating) { - parallelValidate = new ParallelValidateError(this, { - parentStack: options && options.parentStack, - conflictStack: this.$__.validating.stack, - }); - } else { - this.$__.validating = new ParallelValidateError(this, { - parentStack: options && options.parentStack, - }); - } +function decideModelByObject(model, object) { + const discriminatorKey = model.schema.options.discriminatorKey; + if (object != null && object.hasOwnProperty(discriminatorKey)) { + model = getDiscriminatorByValue(model.discriminators, object[discriminatorKey]) || model; + } + return model; +} - if (arguments.length === 1) { - if ( - typeof arguments[0] === "object" && - !Array.isArray(arguments[0]) - ) { - options = arguments[0]; - callback = null; - pathsToValidate = null; - } else if (typeof arguments[0] === "function") { - callback = arguments[0]; - options = null; - pathsToValidate = null; - } - } else if (typeof pathsToValidate === "function") { - callback = pathsToValidate; - options = null; - pathsToValidate = null; - } else if (typeof options === "function") { - callback = options; - options = pathsToValidate; - pathsToValidate = null; - } - if (options && typeof options.pathsToSkip === "string") { - const isOnePathOnly = options.pathsToSkip.indexOf(" ") === -1; - options.pathsToSkip = isOnePathOnly - ? [options.pathsToSkip] - : options.pathsToSkip.split(" "); - } - - return promiseOrCallback( - callback, - (cb) => { - if (parallelValidate != null) { - return cb(parallelValidate); - } - - this.$__validate(pathsToValidate, options, (error) => { - this.$op = null; - cb(error); - }); - }, - this.constructor.events - ); - }; - /*! - * ignore - */ +/***/ }), - function _evaluateRequiredFunctions(doc) { - Object.keys(doc.$__.activePaths.states.require).forEach((path) => { - const p = doc.$__schema.path(path); +/***/ 1462: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (p != null && typeof p.originalRequiredValue === "function") { - doc.$__.cachedRequired[path] = p.originalRequiredValue.call( - doc, - doc - ); - } - }); - } +"use strict"; - /*! - * ignore - */ - function _getPathsToValidate(doc) { - const skipSchemaValidators = {}; +const Mixed = __nccwpck_require__(7495); +const defineKey = __nccwpck_require__(2096)/* .defineKey */ .c; +const get = __nccwpck_require__(8730); +const utils = __nccwpck_require__(9232); - _evaluateRequiredFunctions(doc); - // only validate required fields when necessary - let paths = new Set( - Object.keys(doc.$__.activePaths.states.require).filter(function ( - path - ) { - if (!doc.$__isSelected(path) && !doc.isModified(path)) { - return false; - } - if (path in doc.$__.cachedRequired) { - return doc.$__.cachedRequired[path]; - } - return true; - }) - ); +const CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = { + toJSON: true, + toObject: true, + _id: true, + id: true +}; - Object.keys(doc.$__.activePaths.states.init).forEach(addToPaths); - Object.keys(doc.$__.activePaths.states.modify).forEach(addToPaths); - Object.keys(doc.$__.activePaths.states.default).forEach(addToPaths); - function addToPaths(p) { - paths.add(p); - } - - const subdocs = doc.$getAllSubdocs(); - const modifiedPaths = doc.modifiedPaths(); - for (const subdoc of subdocs) { - if (subdoc.$basePath) { - // Remove child paths for now, because we'll be validating the whole - // subdoc - for (const p of paths) { - if (p === null || p.startsWith(subdoc.$basePath + ".")) { - paths.delete(p); - } - } +/*! + * ignore + */ - if ( - doc.isModified(subdoc.$basePath, modifiedPaths) && - !doc.isDirectModified(subdoc.$basePath) && - !doc.$isDefault(subdoc.$basePath) - ) { - paths.add(subdoc.$basePath); +module.exports = function discriminator(model, name, schema, tiedValue, applyPlugins) { + if (!(schema && schema.instanceOfSchema)) { + throw new Error('You must pass a valid discriminator Schema'); + } - skipSchemaValidators[subdoc.$basePath] = true; - } - } - } + if (model.schema.discriminatorMapping && + !model.schema.discriminatorMapping.isRoot) { + throw new Error('Discriminator "' + name + + '" can only be a discriminator of the root model'); + } - // from here on we're not removing items from paths - - // gh-661: if a whole array is modified, make sure to run validation on all - // the children as well - for (const path of paths) { - const _pathType = doc.$__schema.path(path); - if ( - !_pathType || - !_pathType.$isMongooseArray || - // To avoid potential performance issues, skip doc arrays whose children - // are not required. `getPositionalPathType()` may be slow, so avoid - // it unless we have a case of #6364 - (_pathType.$isMongooseDocumentArray && - !get(_pathType, "schemaOptions.required")) - ) { - continue; - } + if (applyPlugins) { + const applyPluginsToDiscriminators = get(model.base, + 'options.applyPluginsToDiscriminators', false); + // Even if `applyPluginsToDiscriminators` isn't set, we should still apply + // global plugins to schemas embedded in the discriminator schema (gh-7370) + model.base._applyPlugins(schema, { + skipTopLevel: !applyPluginsToDiscriminators + }); + } - const val = doc.$__getValue(path); - _pushNestedArrayPaths(val, paths, path); - } + const key = model.schema.options.discriminatorKey; - function _pushNestedArrayPaths(val, paths, path) { - if (val != null) { - const numElements = val.length; - for (let j = 0; j < numElements; ++j) { - if (Array.isArray(val[j])) { - _pushNestedArrayPaths(val[j], paths, path + "." + j); - } else { - paths.add(path + "." + j); - } - } - } - } + const existingPath = model.schema.path(key); + if (existingPath != null) { + if (!utils.hasUserDefinedProperty(existingPath.options, 'select')) { + existingPath.options.select = true; + } + existingPath.options.$skipDiscriminatorCheck = true; + } else { + const baseSchemaAddition = {}; + baseSchemaAddition[key] = { + default: void 0, + select: true, + $skipDiscriminatorCheck: true + }; + baseSchemaAddition[key][model.schema.options.typeKey] = String; + model.schema.add(baseSchemaAddition); + defineKey({ + prop: key, + prototype: model.prototype, + options: model.schema.options + }); + } - const flattenOptions = { skipArrays: true }; - for (const pathToCheck of paths) { - if (doc.$__schema.nested[pathToCheck]) { - let _v = doc.$__getValue(pathToCheck); - if (isMongooseObject(_v)) { - _v = _v.toObject({ transform: false }); - } - const flat = flatten( - _v, - pathToCheck, - flattenOptions, - doc.$__schema - ); - Object.keys(flat).forEach(addToPaths); - } - } + if (schema.path(key) && schema.path(key).options.$skipDiscriminatorCheck !== true) { + throw new Error('Discriminator "' + name + + '" cannot have field with name "' + key + '"'); + } - for (const path of paths) { - // Single nested paths (paths embedded under single nested subdocs) will - // be validated on their own when we call `validate()` on the subdoc itself. - // Re: gh-8468 - if (doc.$__schema.singleNestedPaths.hasOwnProperty(path)) { - paths.delete(path); - continue; - } - const _pathType = doc.$__schema.path(path); - if (!_pathType || !_pathType.$isSchemaMap) { - continue; - } + let value = name; + if ((typeof tiedValue === 'string' && tiedValue.length) || tiedValue != null) { + value = tiedValue; + } - const val = doc.$__getValue(path); - if (val == null) { - continue; - } - for (const key of val.keys()) { - paths.add(path + "." + key); - } - } + function merge(schema, baseSchema) { + // Retain original schema before merging base schema + schema._baseSchema = baseSchema; + if (baseSchema.paths._id && + baseSchema.paths._id.options && + !baseSchema.paths._id.options.auto) { + schema.remove('_id'); + } - paths = Array.from(paths); - return [paths, skipSchemaValidators]; - } + // Find conflicting paths: if something is a path in the base schema + // and a nested path in the child schema, overwrite the base schema path. + // See gh-6076 + const baseSchemaPaths = Object.keys(baseSchema.paths); + const conflictingPaths = []; - /*! - * ignore - */ + for (const path of baseSchemaPaths) { + if (schema.nested[path]) { + conflictingPaths.push(path); + continue; + } - Document.prototype.$__validate = function ( - pathsToValidate, - options, - callback - ) { - if (typeof pathsToValidate === "function") { - callback = pathsToValidate; - options = null; - pathsToValidate = null; - } else if (typeof options === "function") { - callback = options; - options = null; + if (path.indexOf('.') === -1) { + continue; + } + const sp = path.split('.').slice(0, -1); + let cur = ''; + for (const piece of sp) { + cur += (cur.length ? '.' : '') + piece; + if (schema.paths[cur] instanceof Mixed || + schema.singleNestedPaths[cur] instanceof Mixed) { + conflictingPaths.push(path); } + } + } + + utils.merge(schema, baseSchema, { + isDiscriminatorSchemaMerge: true, + omit: { discriminators: true, base: true }, + omitNested: conflictingPaths.reduce((cur, path) => { + cur['tree.' + path] = true; + return cur; + }, {}) + }); - const hasValidateModifiedOnlyOption = - options && - typeof options === "object" && - "validateModifiedOnly" in options; + // Clean up conflicting paths _after_ merging re: gh-6076 + for (const conflictingPath of conflictingPaths) { + delete schema.paths[conflictingPath]; + } - const pathsToSkip = get(options, "pathsToSkip", null); + // Rebuild schema models because schemas may have been merged re: #7884 + schema.childSchemas.forEach(obj => { + obj.model.prototype.$__setSchema(obj.schema); + }); - let shouldValidateModifiedOnly; - if (hasValidateModifiedOnlyOption) { - shouldValidateModifiedOnly = !!options.validateModifiedOnly; - } else { - shouldValidateModifiedOnly = - this.$__schema.options.validateModifiedOnly; + const obj = {}; + obj[key] = { + default: value, + select: true, + set: function(newName) { + if (newName === value || (Array.isArray(value) && utils.deepEqual(newName, value))) { + return value; } + throw new Error('Can\'t set discriminator key "' + key + '"'); + }, + $skipDiscriminatorCheck: true + }; + obj[key][schema.options.typeKey] = existingPath ? existingPath.options[schema.options.typeKey] : String; + schema.add(obj); - const _this = this; - const _complete = () => { - let validationError = this.$__.validationError; - this.$__.validationError = undefined; - - if (shouldValidateModifiedOnly && validationError != null) { - // Remove any validation errors that aren't from modified paths - const errors = Object.keys(validationError.errors); - for (const errPath of errors) { - if (!this.isModified(errPath)) { - delete validationError.errors[errPath]; - } - } - if (Object.keys(validationError.errors).length === 0) { - validationError = void 0; - } - } - this.$__.cachedRequired = {}; - this.emit("validate", _this); - this.constructor.emit("validate", _this); - - this.$__.validating = null; - if (validationError) { - for (const key in validationError.errors) { - // Make sure cast errors persist - if ( - !this[documentArrayParent] && - validationError.errors[key] instanceof MongooseError.CastError - ) { - this.invalidate(key, validationError.errors[key]); - } - } + schema.discriminatorMapping = { key: key, value: value, isRoot: false }; - return validationError; - } - }; + if (baseSchema.options.collection) { + schema.options.collection = baseSchema.options.collection; + } - // only validate required fields when necessary - const pathDetails = _getPathsToValidate(this); - let paths = shouldValidateModifiedOnly - ? pathDetails[0].filter((path) => this.isModified(path)) - : pathDetails[0]; - const skipSchemaValidators = pathDetails[1]; - if (typeof pathsToValidate === "string") { - pathsToValidate = pathsToValidate.split(" "); - } - if (Array.isArray(pathsToValidate)) { - paths = _handlePathsToValidate(paths, pathsToValidate); - } else if (pathsToSkip) { - paths = _handlePathsToSkip(paths, pathsToSkip); - } - if (paths.length === 0) { - return immediate(function () { - const error = _complete(); - if (error) { - return _this.$__schema.s.hooks.execPost( - "validate:error", - _this, - [_this], - { error: error }, - function (error) { - callback(error); - } - ); - } - callback(null, _this); - }); - } + const toJSON = schema.options.toJSON; + const toObject = schema.options.toObject; + const _id = schema.options._id; + const id = schema.options.id; - const validated = {}; - let total = 0; + const keys = Object.keys(schema.options); + schema.options.discriminatorKey = baseSchema.options.discriminatorKey; - for (const path of paths) { - validatePath(path); + for (const _key of keys) { + if (!CUSTOMIZABLE_DISCRIMINATOR_OPTIONS[_key]) { + // Special case: compiling a model sets `pluralization = true` by default. Avoid throwing an error + // for that case. See gh-9238 + if (_key === 'pluralization' && schema.options[_key] == true && baseSchema.options[_key] == null) { + continue; } - function validatePath(path) { - if (path == null || validated[path]) { - return; - } + if (!utils.deepEqual(schema.options[_key], baseSchema.options[_key])) { + throw new Error('Can\'t customize discriminator option ' + _key + + ' (can only modify ' + + Object.keys(CUSTOMIZABLE_DISCRIMINATOR_OPTIONS).join(', ') + + ')'); + } + } + } + schema.options = utils.clone(baseSchema.options); + if (toJSON) schema.options.toJSON = toJSON; + if (toObject) schema.options.toObject = toObject; + if (typeof _id !== 'undefined') { + schema.options._id = _id; + } + schema.options.id = id; + schema.s.hooks = model.schema.s.hooks.merge(schema.s.hooks); - validated[path] = true; - total++; + schema.plugins = Array.prototype.slice.call(baseSchema.plugins); + schema.callQueue = baseSchema.callQueue.concat(schema.callQueue); + delete schema._requiredpaths; // reset just in case Schema#requiredPaths() was called on either schema + } - immediate(function () { - const schemaType = _this.$__schema.path(path); + // merges base schema into new discriminator schema and sets new type field. + merge(schema, model.schema); - if (!schemaType) { - return --total || complete(); - } + if (!model.discriminators) { + model.discriminators = {}; + } - // If user marked as invalid or there was a cast error, don't validate - if (!_this.$isValid(path)) { - --total || complete(); - return; - } + if (!model.schema.discriminatorMapping) { + model.schema.discriminatorMapping = { key: key, value: null, isRoot: true }; + } + if (!model.schema.discriminators) { + model.schema.discriminators = {}; + } - // If setting a path under a mixed path, avoid using the mixed path validator (gh-10141) - if ( - schemaType[schemaMixedSymbol] != null && - path !== schemaType.path - ) { - return --total || complete(); - } + model.schema.discriminators[name] = schema; - let val = _this.$__getValue(path); + if (model.discriminators[name]) { + throw new Error('Discriminator with name "' + name + '" already exists'); + } - // If you `populate()` and get back a null value, required validators - // shouldn't fail (gh-8018). We should always fall back to the populated - // value. - let pop; - if (val == null && (pop = _this.populated(path))) { - val = pop; - } - const scope = - path in _this.$__.pathsToScopes - ? _this.$__.pathsToScopes[path] - : _this; + return schema; +}; - const doValidateOptions = { - skipSchemaValidators: skipSchemaValidators[path], - path: path, - validateModifiedOnly: shouldValidateModifiedOnly, - }; - schemaType.doValidate( - val, - function (err) { - if ( - err && - (!schemaType.$isMongooseDocumentArray || - err.$isArrayValidatorError) - ) { - if ( - schemaType.$isSingleNested && - err instanceof ValidationError && - schemaType.schema.options.storeSubdocValidationError === - false - ) { - return --total || complete(); - } - _this.invalidate(path, err, undefined, true); - } - --total || complete(); - }, - scope, - doValidateOptions - ); - }); - } - function complete() { - const error = _complete(); - if (error) { - return _this.$__schema.s.hooks.execPost( - "validate:error", - _this, - [_this], - { error: error }, - function (error) { - callback(error); - } - ); - } - callback(null, _this); - } - }; +/***/ }), - /*! - * ignore - */ +/***/ 7716: +/***/ ((module) => { - function _handlePathsToValidate(paths, pathsToValidate) { - const _pathsToValidate = new Set(pathsToValidate); - const parentPaths = new Map([]); - for (const path of pathsToValidate) { - if (path.indexOf(".") === -1) { - continue; - } - const pieces = path.split("."); - let cur = pieces[0]; - for (let i = 1; i < pieces.length; ++i) { - // Since we skip subpaths under single nested subdocs to - // avoid double validation, we need to add back the - // single nested subpath if the user asked for it (gh-8626) - parentPaths.set(cur, path); - cur = cur + "." + pieces[i]; - } - } +"use strict"; - const ret = []; - for (const path of paths) { - if (_pathsToValidate.has(path)) { - ret.push(path); - } else if (parentPaths.has(path)) { - ret.push(parentPaths.get(path)); - } - } - return ret; - } - - /*! - * ignore - */ - function _handlePathsToSkip(paths, pathsToSkip) { - pathsToSkip = new Set(pathsToSkip); - paths = paths.filter((p) => !pathsToSkip.has(p)); - return paths; - } - - /** - * Executes registered validation rules (skipping asynchronous validators) for this document. - * - * ####Note: - * - * This method is useful if you need synchronous validation. - * - * ####Example: - * - * const err = doc.validateSync(); - * if (err) { - * handleError(err); - * } else { - * // validation passed - * } - * - * @param {Array|string} pathsToValidate only validate the given paths - * @param {Object} [options] options for validation - * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths. - * @param {Array|string} [options.pathsToSkip] list of paths to skip. If set, Mongoose will validate every modified path that is not in this list. - * @return {ValidationError|undefined} ValidationError if there are errors during validation, or undefined if there is no error. - * @api public - */ - - Document.prototype.validateSync = function (pathsToValidate, options) { - const _this = this; - if ( - arguments.length === 1 && - typeof arguments[0] === "object" && - !Array.isArray(arguments[0]) - ) { - options = arguments[0]; - pathsToValidate = null; - } +module.exports = parallelLimit; - const hasValidateModifiedOnlyOption = - options && - typeof options === "object" && - "validateModifiedOnly" in options; +/*! + * ignore + */ - let shouldValidateModifiedOnly; - if (hasValidateModifiedOnlyOption) { - shouldValidateModifiedOnly = !!options.validateModifiedOnly; - } else { - shouldValidateModifiedOnly = - this.$__schema.options.validateModifiedOnly; - } +function parallelLimit(fns, limit, callback) { + let numInProgress = 0; + let numFinished = 0; + let error = null; - let pathsToSkip = options && options.pathsToSkip; + if (limit <= 0) { + throw new Error('Limit must be positive'); + } - if (typeof pathsToValidate === "string") { - const isOnePathOnly = pathsToValidate.indexOf(" ") === -1; - pathsToValidate = isOnePathOnly - ? [pathsToValidate] - : pathsToValidate.split(" "); - } else if ( - typeof pathsToSkip === "string" && - pathsToSkip.indexOf(" ") !== -1 - ) { - pathsToSkip = pathsToSkip.split(" "); - } + if (fns.length === 0) { + return callback(null, []); + } - // only validate required fields when necessary - const pathDetails = _getPathsToValidate(this); - let paths = shouldValidateModifiedOnly - ? pathDetails[0].filter((path) => this.isModified(path)) - : pathDetails[0]; - const skipSchemaValidators = pathDetails[1]; + for (let i = 0; i < fns.length && i < limit; ++i) { + _start(); + } - if (Array.isArray(pathsToValidate)) { - paths = _handlePathsToValidate(paths, pathsToValidate); - } else if (Array.isArray(pathsToSkip)) { - paths = _handlePathsToSkip(paths, pathsToSkip); - } - const validating = {}; + function _start() { + fns[numFinished + numInProgress](_done(numFinished + numInProgress)); + ++numInProgress; + } - paths.forEach(function (path) { - if (validating[path]) { - return; - } + const results = []; - validating[path] = true; + function _done(index) { + return (err, res) => { + --numInProgress; + ++numFinished; - const p = _this.$__schema.path(path); - if (!p) { - return; - } - if (!_this.$isValid(path)) { - return; - } + if (error != null) { + return; + } + if (err != null) { + error = err; + return callback(error); + } - const val = _this.$__getValue(path); - const err = p.doValidateSync(val, _this, { - skipSchemaValidators: skipSchemaValidators[path], - path: path, - validateModifiedOnly: shouldValidateModifiedOnly, - }); - if ( - err && - (!p.$isMongooseDocumentArray || err.$isArrayValidatorError) - ) { - if ( - p.$isSingleNested && - err instanceof ValidationError && - p.schema.options.storeSubdocValidationError === false - ) { - return; - } - _this.invalidate(path, err, undefined, true); - } - }); + results[index] = res; - const err = _this.$__.validationError; - _this.$__.validationError = undefined; - _this.emit("validate", _this); - _this.constructor.emit("validate", _this); + if (numFinished === fns.length) { + return callback(null, results); + } else if (numFinished + numInProgress < fns.length) { + _start(); + } + }; + } +} - if (err) { - for (const key in err.errors) { - // Make sure cast errors persist - if (err.errors[key] instanceof MongooseError.CastError) { - _this.invalidate(key, err.errors[key]); - } - } - } - return err; - }; +/***/ }), - /** - * Marks a path as invalid, causing validation to fail. - * - * The `errorMsg` argument will become the message of the `ValidationError`. - * - * The `value` argument (if passed) will be available through the `ValidationError.value` property. - * - * doc.invalidate('size', 'must be less than 20', 14); +/***/ 5842: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - * doc.validate(function (err) { - * console.log(err) - * // prints - * { message: 'Validation failed', - * name: 'ValidationError', - * errors: - * { size: - * { message: 'must be less than 20', - * name: 'ValidatorError', - * path: 'size', - * type: 'user defined', - * value: 14 } } } - * }) - * - * @param {String} path the field to invalidate. For array elements, use the `array.i.field` syntax, where `i` is the 0-based index in the array. - * @param {String|Error} errorMsg the error which states the reason `path` was invalid - * @param {Object|String|Number|any} value optional invalid value - * @param {String} [kind] optional `kind` property for the error - * @return {ValidationError} the current ValidationError, with all currently invalidated paths - * @api public - */ +"use strict"; - Document.prototype.invalidate = function (path, err, val, kind) { - if (!this.$__.validationError) { - this.$__.validationError = new ValidationError(this); - } - if (this.$__.validationError.errors[path]) { - return; - } +const MongooseError = __nccwpck_require__(5953); +const setDottedPath = __nccwpck_require__(1707); +const util = __nccwpck_require__(1669); - if (!err || typeof err === "string") { - err = new ValidatorError({ - path: path, - message: err, - type: kind || "user defined", - value: val, - }); - } +/** + * Given an object that may contain dotted paths, flatten the paths out. + * For example: `flattenObjectWithDottedPaths({ a: { 'b.c': 42 } })` => `{ a: { b: { c: 42 } } }` + */ - if (this.$__.validationError === err) { - return this.$__.validationError; +module.exports = function flattenObjectWithDottedPaths(obj) { + if (obj == null || typeof obj !== 'object' || Array.isArray(obj)) { + return; + } + // Avoid Mongoose docs + if (obj.$__) { + return; + } + const keys = Object.keys(obj); + for (const key of keys) { + const val = obj[key]; + if (key.indexOf('.') !== -1) { + try { + delete obj[key]; + setDottedPath(obj, key, val); + } catch (err) { + if (!(err instanceof TypeError)) { + throw err; } + throw new MongooseError(`Conflicting dotted paths when setting document path, key: "${key}", value: ${util.inspect(val)}`); + } + continue; + } - this.$__.validationError.addError(path, err); - return this.$__.validationError; - }; + flattenObjectWithDottedPaths(obj[key]); + } +}; - /** - * Marks a path as valid, removing existing validation errors. - * - * @param {String} path the field to mark as valid - * @api public - * @memberOf Document - * @instance - * @method $markValid - */ - - Document.prototype.$markValid = function (path) { - if ( - !this.$__.validationError || - !this.$__.validationError.errors[path] - ) { - return; - } +/***/ }), - delete this.$__.validationError.errors[path]; - if (Object.keys(this.$__.validationError.errors).length === 0) { - this.$__.validationError = null; - } - }; +/***/ 8123: +/***/ ((module) => { - /*! - * ignore - */ +"use strict"; - function _markValidSubpaths(doc, path) { - if (!doc.$__.validationError) { - return; - } - const keys = Object.keys(doc.$__.validationError.errors); - for (const key of keys) { - if (key.startsWith(path + ".")) { - delete doc.$__.validationError.errors[key]; - } - } - if (Object.keys(doc.$__.validationError.errors).length === 0) { - doc.$__.validationError = null; - } - } +module.exports = function parentPaths(path) { + const pieces = path.split('.'); + let cur = ''; + const ret = []; + for (let i = 0; i < pieces.length; ++i) { + cur += (cur.length > 0 ? '.' : '') + pieces[i]; + ret.push(cur); + } - /*! - * ignore - */ + return ret; +}; - function _checkImmutableSubpaths(subdoc, schematype, priorVal) { - const schema = schematype.schema; - if (schema == null) { - return; - } +/***/ }), - for (const key of Object.keys(schema.paths)) { - const path = schema.paths[key]; - if (path.$immutableSetter == null) { - continue; - } - const oldVal = priorVal == null ? void 0 : priorVal.$__getValue(key); - // Calling immutableSetter with `oldVal` even though it expects `newVal` - // is intentional. That's because `$immutableSetter` compares its param - // to the current value. - path.$immutableSetter.call(subdoc, oldVal); - } - } - - /** - * Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`, - * or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation **only** with the modifications to the database, it does not replace the whole document in the latter case. - * - * ####Example: - * - * product.sold = Date.now(); - * product = await product.save(); - * - * If save is successful, the returned promise will fulfill with the document - * saved. - * - * ####Example: - * - * const newProduct = await product.save(); - * newProduct === product; // true - * - * @param {Object} [options] options optional options - * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). - * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead. - * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. - * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths. - * @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) - * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) - * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern). - * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names) - * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`. - * @param {Function} [fn] optional callback - * @method save - * @memberOf Document - * @instance - * @throws {DocumentNotFoundError} if this [save updates an existing document](api.html#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating). - * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise. - * @api public - * @see middleware http://mongoosejs.com/docs/middleware.html - */ - - /** - * Checks if a path is invalid - * - * @param {String|Array} path the field to check - * @method $isValid - * @memberOf Document - * @instance - * @api private - */ - - Document.prototype.$isValid = function (path) { - if ( - this.$__.validationError == null || - Object.keys(this.$__.validationError.errors).length === 0 - ) { - return true; - } - if (path == null) { - return false; - } +/***/ 1707: +/***/ ((module) => { - if (path.indexOf(" ") !== -1) { - path = path.split(" "); - } - if (Array.isArray(path)) { - return path.some((p) => this.$__.validationError.errors[p] == null); - } +"use strict"; - return this.$__.validationError.errors[path] == null; - }; - /** - * Resets the internal modified state of this document. - * - * @api private - * @return {Document} - * @method $__reset - * @memberOf Document - * @instance - */ - - Document.prototype.$__reset = function reset() { - let _this = this; - DocumentArray || (DocumentArray = __nccwpck_require__(55)); - - this.$__.activePaths - .map("init", "modify", function (i) { - return _this.$__getValue(i); - }) - .filter(function (val) { - return ( - val && - val instanceof Array && - val.isMongooseDocumentArray && - val.length - ); - }) - .forEach(function (array) { - let i = array.length; - while (i--) { - const doc = array[i]; - if (!doc) { - continue; - } - doc.$__reset(); - } +module.exports = function setDottedPath(obj, path, val) { + const parts = path.indexOf('.') === -1 ? [path] : path.split('.'); + let cur = obj; + for (const part of parts.slice(0, -1)) { + if (cur[part] == null) { + cur[part] = {}; + } - _this.$__.activePaths.init(array.$path()); + cur = cur[part]; + } - array[arrayAtomicsBackupSymbol] = array[arrayAtomicsSymbol]; - array[arrayAtomicsSymbol] = {}; - }); + const last = parts[parts.length - 1]; + cur[last] = val; +}; - this.$__.activePaths - .map("init", "modify", function (i) { - return _this.$__getValue(i); - }) - .filter(function (val) { - return val && val.$isSingleNested; - }) - .forEach(function (doc) { - doc.$__reset(); - if (doc.$__parent === _this) { - _this.$__.activePaths.init(doc.$basePath); - } else if (doc.$__parent != null && doc.$__parent.ownerDocument) { - // If map path underneath subdocument, may end up with a case where - // map path is modified but parent still needs to be reset. See gh-10295 - doc.$__parent.$__reset(); - } - }); +/***/ }), - // clear atomics - this.$__dirty().forEach(function (dirt) { - const type = dirt.value; +/***/ 2145: +/***/ ((module, exports) => { - if (type && type[arrayAtomicsSymbol]) { - type[arrayAtomicsBackupSymbol] = type[arrayAtomicsSymbol]; - type[arrayAtomicsSymbol] = {}; - } - }); +"use strict"; - this.$__.backup = {}; - this.$__.backup.activePaths = { - modify: Object.assign({}, this.$__.activePaths.states.modify), - default: Object.assign({}, this.$__.activePaths.states.default), - }; - this.$__.backup.validationError = this.$__.validationError; - this.$__.backup.errors = this.errors; - - // Clear 'dirty' cache - this.$__.activePaths.clear("modify"); - this.$__.activePaths.clear("default"); - this.$__.validationError = undefined; - this.errors = undefined; - _this = this; - this.$__schema.requiredPaths().forEach(function (path) { - _this.$__.activePaths.require(path); - }); - return this; - }; +module.exports = pluralize; - /*! - * ignore - */ +/** + * Pluralization rules. + */ - Document.prototype.$__undoReset = function $__undoReset() { - if (this.$__.backup == null || this.$__.backup.activePaths == null) { - return; - } +exports.pluralization = [ + [/(m)an$/gi, '$1en'], + [/(pe)rson$/gi, '$1ople'], + [/(child)$/gi, '$1ren'], + [/^(ox)$/gi, '$1en'], + [/(ax|test)is$/gi, '$1es'], + [/(octop|vir)us$/gi, '$1i'], + [/(alias|status)$/gi, '$1es'], + [/(bu)s$/gi, '$1ses'], + [/(buffal|tomat|potat)o$/gi, '$1oes'], + [/([ti])um$/gi, '$1a'], + [/sis$/gi, 'ses'], + [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'], + [/(hive)$/gi, '$1s'], + [/([^aeiouy]|qu)y$/gi, '$1ies'], + [/(x|ch|ss|sh)$/gi, '$1es'], + [/(matr|vert|ind)ix|ex$/gi, '$1ices'], + [/([m|l])ouse$/gi, '$1ice'], + [/(kn|w|l)ife$/gi, '$1ives'], + [/(quiz)$/gi, '$1zes'], + [/^goose$/i, 'geese'], + [/s$/gi, 's'], + [/([^a-z])$/, '$1'], + [/$/gi, 's'] +]; +const rules = exports.pluralization; + +/** + * Uncountable words. + * + * These words are applied while processing the argument to `toCollectionName`. + * @api public + */ - this.$__.activePaths.states.modify = this.$__.backup.activePaths.modify; - this.$__.activePaths.states.default = - this.$__.backup.activePaths.default; +exports.uncountables = [ + 'advice', + 'energy', + 'excretion', + 'digestion', + 'cooperation', + 'health', + 'justice', + 'labour', + 'machinery', + 'equipment', + 'information', + 'pollution', + 'sewage', + 'paper', + 'money', + 'species', + 'series', + 'rain', + 'rice', + 'fish', + 'sheep', + 'moose', + 'deer', + 'news', + 'expertise', + 'status', + 'media' +]; +const uncountables = exports.uncountables; + +/*! + * Pluralize function. + * + * @author TJ Holowaychuk (extracted from _ext.js_) + * @param {String} string to pluralize + * @api private + */ - this.$__.validationError = this.$__.backup.validationError; - this.errors = this.$__.backup.errors; +function pluralize(str) { + let found; + str = str.toLowerCase(); + if (!~uncountables.indexOf(str)) { + found = rules.filter(function(rule) { + return str.match(rule[0]); + }); + if (found[0]) { + return str.replace(found[0][0], found[0][1]); + } + } + return str; +} - for (const dirt of this.$__dirty()) { - const type = dirt.value; +/***/ }), - if ( - type && - type[arrayAtomicsSymbol] && - type[arrayAtomicsBackupSymbol] - ) { - type[arrayAtomicsSymbol] = type[arrayAtomicsBackupSymbol]; - } - } +/***/ 694: +/***/ ((module) => { - for (const subdoc of this.$getAllSubdocs()) { - subdoc.$__undoReset(); - } - }; +"use strict"; - /** - * Returns this documents dirty paths / vals. - * - * @api private - * @method $__dirty - * @memberOf Document - * @instance - */ - Document.prototype.$__dirty = function () { - const _this = this; +module.exports = function SkipPopulateValue(val) { + if (!(this instanceof SkipPopulateValue)) { + return new SkipPopulateValue(val); + } - let all = this.$__.activePaths.map("modify", function (path) { - return { - path: path, - value: _this.$__getValue(path), - schema: _this.$__path(path), - }; - }); - // gh-2558: if we had to set a default and the value is not undefined, - // we have to save as well - all = all.concat( - this.$__.activePaths.map("default", function (path) { - if (path === "_id" || _this.$__getValue(path) == null) { - return; - } - return { - path: path, - value: _this.$__getValue(path), - schema: _this.$__path(path), - }; - }) - ); + this.val = val; + return this; +}; - // Sort dirty paths in a flat hierarchy. - all.sort(function (a, b) { - return a.path < b.path ? -1 : a.path > b.path ? 1 : 0; - }); +/***/ }), - // Ignore "foo.a" if "foo" is dirty already. - const minimal = []; - let lastPath; - let top; +/***/ 8490: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - all.forEach(function (item) { - if (!item) { - return; - } - if (lastPath == null || item.path.indexOf(lastPath) !== 0) { - lastPath = item.path + "."; - minimal.push(item); - top = item; - } else if ( - top != null && - top.value != null && - top.value[arrayAtomicsSymbol] != null && - top.value.hasAtomics() - ) { - // special case for top level MongooseArrays - // the `top` array itself and a sub path of `top` are being modified. - // the only way to honor all of both modifications is through a $set - // of entire array. - top.value[arrayAtomicsSymbol] = {}; - top.value[arrayAtomicsSymbol].$set = top.value; - } - }); - top = lastPath = null; - return minimal; - }; +"use strict"; - /** - * Assigns/compiles `schema` into this documents prototype. - * - * @param {Schema} schema - * @api private - * @method $__setSchema - * @memberOf Document - * @instance - */ - - Document.prototype.$__setSchema = function (schema) { - schema.plugin(idGetter, { deduplicate: true }); - compile(schema.tree, this, undefined, schema.options); - - // Apply default getters if virtual doesn't have any (gh-6262) - for (const key of Object.keys(schema.virtuals)) { - schema.virtuals[key]._applyDefaultGetters(); - } - if (schema.path("schema") == null) { - this.schema = schema; - } - this.$__schema = schema; - this[documentSchemaSymbol] = schema; - }; - /** - * Get active path that were changed and are arrays - * - * @api private - * @method $__getArrayPathsToValidate - * @memberOf Document - * @instance - */ - - Document.prototype.$__getArrayPathsToValidate = function () { - DocumentArray || (DocumentArray = __nccwpck_require__(55)); - - // validate all document arrays. - return this.$__.activePaths - .map( - "init", - "modify", - function (i) { - return this.$__getValue(i); - }.bind(this) - ) - .filter(function (val) { - return ( - val && - val instanceof Array && - val.isMongooseDocumentArray && - val.length - ); - }) - .reduce(function (seed, array) { - return seed.concat(array); - }, []) - .filter(function (doc) { - return doc; - }); - }; +const leanPopulateMap = __nccwpck_require__(914); +const modelSymbol = __nccwpck_require__(3240).modelSymbol; +const utils = __nccwpck_require__(9232); - /** - * Get all subdocs (by bfs) - * - * @api public - * @method $getAllSubdocs - * @memberOf Document - * @instance - */ - - Document.prototype.$getAllSubdocs = function $getAllSubdocs() { - DocumentArray || (DocumentArray = __nccwpck_require__(55)); - Embedded = Embedded || __nccwpck_require__(4433); - - function docReducer(doc, seed, path) { - let val = doc; - let isNested = false; - if (path) { - if ( - doc instanceof Document && - doc[documentSchemaSymbol].paths[path] - ) { - val = doc._doc[path]; - } else if ( - doc instanceof Document && - doc[documentSchemaSymbol].nested[path] - ) { - val = doc._doc[path]; - isNested = true; - } else { - val = doc[path]; - } - } - if (val instanceof Embedded) { - seed.push(val); - } else if (val instanceof Map) { - seed = Array.from(val.keys()).reduce(function (seed, path) { - return docReducer(val.get(path), seed, null); - }, seed); - } else if (val && val.$isSingleNested) { - seed = Object.keys(val._doc).reduce(function (seed, path) { - return docReducer(val._doc, seed, path); - }, seed); - seed.push(val); - } else if (val && val.isMongooseDocumentArray) { - val.forEach(function _docReduce(doc) { - if (!doc || !doc._doc) { - return; - } - seed = Object.keys(doc._doc).reduce(function (seed, path) { - return docReducer(doc._doc, seed, path); - }, seed); - if (doc instanceof Embedded) { - seed.push(doc); - } - }); - } else if (isNested && val != null) { - for (const path of Object.keys(val)) { - docReducer(val, seed, path); - } - } - return seed; - } +module.exports = assignRawDocsToIdStructure; - const subDocs = []; - for (const path of Object.keys(this._doc)) { - docReducer(this, subDocs, path); - } +/*! + * Assign `vals` returned by mongo query to the `rawIds` + * structure returned from utils.getVals() honoring + * query sort order if specified by user. + * + * This can be optimized. + * + * Rules: + * + * if the value of the path is not an array, use findOne rules, else find. + * for findOne the results are assigned directly to doc path (including null results). + * for find, if user specified sort order, results are assigned directly + * else documents are put back in original order of array if found in results + * + * @param {Array} rawIds + * @param {Array} vals + * @param {Boolean} sort + * @api private + */ - return subDocs; - }; +function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, recursed) { + // honor user specified sort order + const newOrder = []; + const sorting = options.sort && rawIds.length > 1; + const nullIfNotFound = options.$nullIfNotFound; + let doc; + let sid; + let id; + + if (rawIds.isMongooseArrayProxy) { + rawIds = rawIds.__array; + } - /*! - * Runs queued functions - */ + for (let i = 0; i < rawIds.length; ++i) { + id = rawIds[i]; - function applyQueue(doc) { - const q = doc.$__schema && doc.$__schema.callQueue; - if (!q.length) { - return; - } + if (Array.isArray(id)) { + // handle [ [id0, id2], [id3] ] + assignRawDocsToIdStructure(id, resultDocs, resultOrder, options, true); + newOrder.push(id); + continue; + } + + if (id === null && !sorting) { + // keep nulls for findOne unless sorting, which always + // removes them (backward compat) + newOrder.push(id); + continue; + } - for (const pair of q) { - if (pair[0] !== "pre" && pair[0] !== "post" && pair[0] !== "on") { - doc[pair[0]].apply(doc, pair[1]); + sid = String(id); + + doc = resultDocs[sid]; + // If user wants separate copies of same doc, use this option + if (options.clone && doc != null) { + if (options.lean) { + const _model = leanPopulateMap.get(doc); + doc = utils.clone(doc); + leanPopulateMap.set(doc, _model); + } else { + doc = doc.constructor.hydrate(doc._doc); + } + } + + if (recursed) { + if (doc) { + if (sorting) { + const _resultOrder = resultOrder[sid]; + if (Array.isArray(_resultOrder) && Array.isArray(doc) && _resultOrder.length === doc.length) { + newOrder.push(doc); + } else { + newOrder[_resultOrder] = doc; } + } else { + newOrder.push(doc); } + } else if (id != null && id[modelSymbol] != null) { + newOrder.push(id); + } else { + newOrder.push(options.retainNullValues || nullIfNotFound ? null : id); } + } else { + // apply findOne behavior - if document in results, assign, else assign null + newOrder[i] = doc || null; + } + } - /*! - * ignore - */ + rawIds.length = 0; + if (newOrder.length) { + // reassign the documents based on corrected order - Document.prototype.$__handleReject = function handleReject(err) { - // emit on the Model if listening - if (this.listeners("error").length) { - this.emit("error", err); - } else if ( - this.constructor.listeners && - this.constructor.listeners("error").length - ) { - this.constructor.emit("error", err); - } - }; + // forEach skips over sparse entries in arrays so we + // can safely use this to our advantage dealing with sorted + // result sets too. + newOrder.forEach(function(doc, i) { + rawIds[i] = doc; + }); + } +} + +/***/ }), + +/***/ 6414: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const MongooseMap = __nccwpck_require__(9390); +const SkipPopulateValue = __nccwpck_require__(694); +const assignRawDocsToIdStructure = __nccwpck_require__(8490); +const get = __nccwpck_require__(8730); +const getVirtual = __nccwpck_require__(6371); +const leanPopulateMap = __nccwpck_require__(914); +const lookupLocalFields = __nccwpck_require__(1296); +const markArraySubdocsPopulated = __nccwpck_require__(3515); +const mpath = __nccwpck_require__(8586); +const sift = __nccwpck_require__(2865).default; +const utils = __nccwpck_require__(9232); +const { populateModelSymbol } = __nccwpck_require__(3240); + +module.exports = function assignVals(o) { + // Options that aren't explicitly listed in `populateOptions` + const userOptions = Object.assign({}, get(o, 'allOptions.options.options'), get(o, 'allOptions.options')); + // `o.options` contains options explicitly listed in `populateOptions`, like + // `match` and `limit`. + const populateOptions = Object.assign({}, o.options, userOptions, { + justOne: o.justOne + }); + populateOptions.$nullIfNotFound = o.isVirtual; + const populatedModel = o.populatedModel; + + const originalIds = [].concat(o.rawIds); + + // replace the original ids in our intermediate _ids structure + // with the documents found by query + o.allIds = [].concat(o.allIds); + assignRawDocsToIdStructure(o.rawIds, o.rawDocs, o.rawOrder, populateOptions); + + // now update the original documents being populated using the + // result structure that contains real documents. + const docs = o.docs; + const rawIds = o.rawIds; + const options = o.options; + const count = o.count && o.isVirtual; + let i; + + function setValue(val) { + if (count) { + return val; + } + if (val instanceof SkipPopulateValue) { + return val.val; + } + if (val === void 0) { + return val; + } - /** - * Internal helper for toObject() and toJSON() that doesn't manipulate options - * - * @api private - * @method $toObject - * @memberOf Document - * @instance - */ - - Document.prototype.$toObject = function (options, json) { - let defaultOptions = { - transform: true, - flattenDecimals: true, - }; + const _allIds = o.allIds[i]; - const path = json ? "toJSON" : "toObject"; - const baseOptions = get(this, "constructor.base.options." + path, {}); - const schemaOptions = get(this, "$__schema.options", {}); - // merge base default options with Schema's set default options if available. - // `clone` is necessary here because `utils.options` directly modifies the second input. - defaultOptions = utils.options(defaultOptions, clone(baseOptions)); - defaultOptions = utils.options( - defaultOptions, - clone(schemaOptions[path] || {}) - ); + if (o.justOne === true && Array.isArray(val)) { + // Might be an embedded discriminator (re: gh-9244) with multiple models, so make sure to pick the right + // model before assigning. + const ret = []; + for (const doc of val) { + const _docPopulatedModel = leanPopulateMap.get(doc); + if (_docPopulatedModel == null || _docPopulatedModel === populatedModel) { + ret.push(doc); + } + } + // Since we don't want to have to create a new mongoosearray, make sure to + // modify the array in place + while (val.length > ret.length) { + Array.prototype.pop.apply(val, []); + } + for (let i = 0; i < ret.length; ++i) { + val[i] = ret[i]; + } - // If options do not exist or is not an object, set it to empty object - options = utils.isPOJO(options) ? clone(options) : {}; - options._calledWithOptions = - options._calledWithOptions || clone(options); + return valueFilter(val[0], options, populateOptions, _allIds); + } else if (o.justOne === false && !Array.isArray(val)) { + return valueFilter([val], options, populateOptions, _allIds); + } + return valueFilter(val, options, populateOptions, _allIds); + } - let _minimize; - if (options._calledWithOptions.minimize != null) { - _minimize = options.minimize; - } else if (defaultOptions.minimize != null) { - _minimize = defaultOptions.minimize; - } else { - _minimize = schemaOptions.minimize; - } + for (i = 0; i < docs.length; ++i) { + const _path = o.path.endsWith('.$*') ? o.path.slice(0, -3) : o.path; + const existingVal = mpath.get(_path, docs[i], lookupLocalFields); + if (existingVal == null && !getVirtual(o.originalModel.schema, _path)) { + continue; + } - let flattenMaps; - if (options._calledWithOptions.flattenMaps != null) { - flattenMaps = options.flattenMaps; - } else if (defaultOptions.flattenMaps != null) { - flattenMaps = defaultOptions.flattenMaps; - } else { - flattenMaps = schemaOptions.flattenMaps; - } - - // The original options that will be passed to `clone()`. Important because - // `clone()` will recursively call `$toObject()` on embedded docs, so we - // need the original options the user passed in, plus `_isNested` and - // `_parentOptions` for checking whether we need to depopulate. - const cloneOptions = Object.assign(utils.clone(options), { - _isNested: true, - json: json, - minimize: _minimize, - flattenMaps: flattenMaps, - }); + let valueToSet; + if (count) { + valueToSet = numDocs(rawIds[i]); + } else if (Array.isArray(o.match)) { + valueToSet = Array.isArray(rawIds[i]) ? + rawIds[i].filter(sift(o.match[i])) : + [rawIds[i]].filter(sift(o.match[i]))[0]; + } else { + valueToSet = rawIds[i]; + } - if (utils.hasUserDefinedProperty(options, "getters")) { - cloneOptions.getters = options.getters; - } - if (utils.hasUserDefinedProperty(options, "virtuals")) { - cloneOptions.virtuals = options.virtuals; - } + // If we're populating a map, the existing value will be an object, so + // we need to transform again + const originalSchema = o.originalModel.schema; + const isDoc = get(docs[i], '$__', null) != null; + let isMap = isDoc ? + existingVal instanceof Map : + utils.isPOJO(existingVal); + // If we pass the first check, also make sure the local field's schematype + // is map (re: gh-6460) + isMap = isMap && get(originalSchema._getSchema(_path), '$isSchemaMap'); + if (!o.isVirtual && isMap) { + const _keys = existingVal instanceof Map ? + Array.from(existingVal.keys()) : + Object.keys(existingVal); + valueToSet = valueToSet.reduce((cur, v, i) => { + cur.set(_keys[i], v); + return cur; + }, new Map()); + } - const depopulate = - options.depopulate || - get(options, "_parentOptions.depopulate", false); - // _isNested will only be true if this is not the top level document, we - // should never depopulate - if (depopulate && options._isNested && this.$__.wasPopulated) { - // populated paths that we set to a document - return clone(this._id, cloneOptions); + if (isDoc && Array.isArray(valueToSet)) { + for (const val of valueToSet) { + if (val != null && val.$__ != null) { + val.$__.parent = docs[i]; } + } + } else if (isDoc && valueToSet != null && valueToSet.$__ != null) { + valueToSet.$__.parent = docs[i]; + } + + if (o.isVirtual && isDoc) { + docs[i].$populated(_path, o.justOne ? originalIds[0] : originalIds, o.allOptions); + // If virtual populate and doc is already init-ed, need to walk through + // the actual doc to set rather than setting `_doc` directly + if (Array.isArray(valueToSet)) { + valueToSet = valueToSet.map(v => v == null ? void 0 : v); + } + mpath.set(_path, valueToSet, docs[i], void 0, setValue, false); + continue; + } - // merge default options with input options. - options = utils.options(defaultOptions, options); - options._isNested = true; - options.json = json; - options.minimize = _minimize; + const parts = _path.split('.'); + let cur = docs[i]; + const curPath = parts[0]; + for (let j = 0; j < parts.length - 1; ++j) { + // If we get to an array with a dotted path, like `arr.foo`, don't set + // `foo` on the array. + if (Array.isArray(cur) && !utils.isArrayIndex(parts[j])) { + break; + } - cloneOptions._parentOptions = options; - cloneOptions._skipSingleNestedGetters = true; + if (parts[j] === '$*') { + break; + } - const gettersOptions = Object.assign({}, cloneOptions); - gettersOptions._skipSingleNestedGetters = false; + if (cur[parts[j]] == null) { + // If nothing to set, avoid creating an unnecessary array. Otherwise + // we'll end up with a single doc in the array with only defaults. + // See gh-8342, gh-8455 + const schematype = originalSchema._getSchema(curPath); + if (valueToSet == null && schematype != null && schematype.$isMongooseArray) { + break; + } + cur[parts[j]] = {}; + } + cur = cur[parts[j]]; + // If the property in MongoDB is a primitive, we won't be able to populate + // the nested path, so skip it. See gh-7545 + if (typeof cur !== 'object') { + break; + } + } + if (docs[i].$__) { + o.allOptions.options[populateModelSymbol] = o.allOptions.model; + docs[i].$populated(_path, o.unpopulatedValues[i], o.allOptions.options); - // remember the root transform function - // to save it from being overwritten by sub-transform functions - const originalTransform = options.transform; + if (valueToSet instanceof Map && !valueToSet.$isMongooseMap) { + valueToSet = new MongooseMap(valueToSet, _path, docs[i], docs[i].schema.path(_path).$__schemaType); + } + } - let ret = clone(this._doc, cloneOptions) || {}; + // If lean, need to check that each individual virtual respects + // `justOne`, because you may have a populated virtual with `justOne` + // underneath an array. See gh-6867 + mpath.set(_path, valueToSet, docs[i], lookupLocalFields, setValue, false); - if (options.getters) { - applyGetters(this, ret, gettersOptions); + if (docs[i].$__) { + markArraySubdocsPopulated(docs[i], [o.allOptions.options]); + } + } +}; + +function numDocs(v) { + if (Array.isArray(v)) { + // If setting underneath an array of populated subdocs, we may have an + // array of arrays. See gh-7573 + if (v.some(el => Array.isArray(el))) { + return v.map(el => numDocs(el)); + } + return v.length; + } + return v == null ? 0 : 1; +} - if (options.minimize) { - ret = minimize(ret) || {}; - } - } +/*! + * 1) Apply backwards compatible find/findOne behavior to sub documents + * + * find logic: + * a) filter out non-documents + * b) remove _id from sub docs when user specified + * + * findOne + * a) if no doc found, set to null + * b) remove _id from sub docs when user specified + * + * 2) Remove _ids when specified by users query. + * + * background: + * _ids are left in the query even when user excludes them so + * that population mapping can occur. + */ - if ( - options.virtuals || - (options.getters && options.virtuals !== false) - ) { - applyVirtuals(this, ret, gettersOptions, options); - } +function valueFilter(val, assignmentOpts, populateOptions, allIds) { + const userSpecifiedTransform = typeof populateOptions.transform === 'function'; + const transform = userSpecifiedTransform ? populateOptions.transform : noop; + if (Array.isArray(val)) { + // find logic + const ret = []; + const numValues = val.length; + for (let i = 0; i < numValues; ++i) { + let subdoc = val[i]; + const _allIds = Array.isArray(allIds) ? allIds[i] : allIds; + if (!isPopulatedObject(subdoc) && (!populateOptions.retainNullValues || subdoc != null) && !userSpecifiedTransform) { + continue; + } else if (userSpecifiedTransform) { + subdoc = transform(isPopulatedObject(subdoc) ? subdoc : null, _allIds); + } + maybeRemoveId(subdoc, assignmentOpts); + ret.push(subdoc); + if (assignmentOpts.originalLimit && + ret.length >= assignmentOpts.originalLimit) { + break; + } + } - if (options.versionKey === false && this.$__schema.options.versionKey) { - delete ret[this.$__schema.options.versionKey]; - } + // Since we don't want to have to create a new mongoosearray, make sure to + // modify the array in place + while (val.length > ret.length) { + Array.prototype.pop.apply(val, []); + } + for (let i = 0; i < ret.length; ++i) { + if (val.isMongooseArrayProxy) { + val.set(i, ret[i], true); + } else { + val[i] = ret[i]; + } + } + return val; + } - let transform = options.transform; + // findOne + if (isPopulatedObject(val) || utils.isPOJO(val)) { + maybeRemoveId(val, assignmentOpts); + return transform(val, allIds); + } + if (val instanceof Map) { + return val; + } - // In the case where a subdocument has its own transform function, we need to - // check and see if the parent has a transform (options.transform) and if the - // child schema has a transform (this.schema.options.toObject) In this case, - // we need to adjust options.transform to be the child schema's transform and - // not the parent schema's - if (transform) { - applySchemaTypeTransforms(this, ret); - } + if (populateOptions.justOne === false) { + return []; + } - if (options.useProjection) { - omitDeselectedFields(this, ret); - } + return val == null ? transform(val, allIds) : transform(null, allIds); +} - if (transform === true || (schemaOptions.toObject && transform)) { - const opts = options.json - ? schemaOptions.toJSON - : schemaOptions.toObject; +/*! + * Remove _id from `subdoc` if user specified "lean" query option + */ - if (opts) { - transform = - typeof options.transform === "function" - ? options.transform - : opts.transform; - } - } else { - options.transform = originalTransform; - } +function maybeRemoveId(subdoc, assignmentOpts) { + if (subdoc != null && assignmentOpts.excludeId) { + if (typeof subdoc.$__setValue === 'function') { + delete subdoc._doc._id; + } else { + delete subdoc._id; + } + } +} - if (typeof transform === "function") { - const xformed = transform(this, ret, options); - if (typeof xformed !== "undefined") { - ret = xformed; - } - } +/*! + * Determine if `obj` is something we can set a populated path to. Can be a + * document, a lean document, or an array/map that contains docs. + */ - return ret; - }; +function isPopulatedObject(obj) { + if (obj == null) { + return false; + } - /** - * Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). - * - * Buffers are converted to instances of [mongodb.Binary](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage. - * - * ####Options: - * - * - `getters` apply all getters (path and virtual getters), defaults to false - * - `aliases` apply all aliases if `virtuals=true`, defaults to true - * - `virtuals` apply virtual getters (can override `getters` option), defaults to false - * - `minimize` remove empty objects, defaults to true - * - `transform` a transform function to apply to the resulting document before returning - * - `depopulate` depopulate any populated paths, replacing them with their original refs, defaults to false - * - `versionKey` whether to include the version key, defaults to true - * - `flattenMaps` convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject(), defaults to false - * - `useProjection` set to `true` to omit fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. - * - * ####Getters/Virtuals - * - * Example of only applying path getters - * - * doc.toObject({ getters: true, virtuals: false }) - * - * Example of only applying virtual getters - * - * doc.toObject({ virtuals: true }) - * - * Example of applying both path and virtual getters - * - * doc.toObject({ getters: true }) - * - * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument. - * - * schema.set('toObject', { virtuals: true }) - * - * ####Transform - * - * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function. - * - * Transform functions receive three arguments - * - * function (doc, ret, options) {} - * - * - `doc` The mongoose document which is being converted - * - `ret` The plain object representation which has been converted - * - `options` The options in use (either schema options or the options passed inline) - * - * ####Example - * - * // specify the transform schema option - * if (!schema.options.toObject) schema.options.toObject = {}; - * schema.options.toObject.transform = function (doc, ret, options) { - * // remove the _id of every document before returning the result - * delete ret._id; - * return ret; - * } - * - * // without the transformation in the schema - * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } - * - * // with the transformation - * doc.toObject(); // { name: 'Wreck-it Ralph' } - * - * With transformations we can do a lot more than remove properties. We can even return completely new customized objects: - * - * if (!schema.options.toObject) schema.options.toObject = {}; - * schema.options.toObject.transform = function (doc, ret, options) { - * return { movie: ret.name } - * } - * - * // without the transformation in the schema - * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } - * - * // with the transformation - * doc.toObject(); // { movie: 'Wreck-it Ralph' } - * - * _Note: if a transform function returns `undefined`, the return value will be ignored._ - * - * Transformations may also be applied inline, overridding any transform set in the options: - * - * function xform (doc, ret, options) { - * return { inline: ret.name, custom: true } - * } - * - * // pass the transform as an inline option - * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true } - * - * If you want to skip transformations, use `transform: false`: - * - * schema.options.toObject.hide = '_id'; - * schema.options.toObject.transform = function (doc, ret, options) { - * if (options.hide) { - * options.hide.split(' ').forEach(function (prop) { - * delete ret[prop]; - * }); - * } - * return ret; - * } - * - * const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }); - * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' } - * doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' } - * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' } - * - * If you pass a transform in `toObject()` options, Mongoose will apply the transform - * to [subdocuments](/docs/subdocs.html) in addition to the top-level document. - * Similarly, `transform: false` skips transforms for all subdocuments. - * Note that this is behavior is different for transforms defined in the schema: - * if you define a transform in `schema.options.toObject.transform`, that transform - * will **not** apply to subdocuments. - * - * const memberSchema = new Schema({ name: String, email: String }); - * const groupSchema = new Schema({ members: [memberSchema], name: String, email }); - * const Group = mongoose.model('Group', groupSchema); - * - * const doc = new Group({ - * name: 'Engineering', - * email: 'dev@mongoosejs.io', - * members: [{ name: 'Val', email: 'val@mongoosejs.io' }] - * }); - * - * // Removes `email` from both top-level document **and** array elements - * // { name: 'Engineering', members: [{ name: 'Val' }] } - * doc.toObject({ transform: (doc, ret) => { delete ret.email; return ret; } }); - * - * Transforms, like all of these options, are also available for `toJSON`. See [this guide to `JSON.stringify()`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html) to learn why `toJSON()` and `toObject()` are separate functions. - * - * See [schema options](/docs/guide.html#toObject) for some more details. - * - * _During save, no custom options are applied to the document before being sent to the database._ - * - * @param {Object} [options] - * @param {Boolean} [options.getters=false] if true, apply all getters, including virtuals - * @param {Boolean} [options.virtuals=false] if true, apply virtuals, including aliases. Use `{ getters: true, virtuals: false }` to just apply getters, not virtuals - * @param {Boolean} [options.aliases=true] if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`. - * @param {Boolean} [options.minimize=true] if true, omit any empty objects from the output - * @param {Function|null} [options.transform=null] if set, mongoose will call this function to allow you to transform the returned object - * @param {Boolean} [options.depopulate=false] if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths. - * @param {Boolean} [options.versionKey=true] if false, exclude the version key (`__v` by default) from the output - * @param {Boolean} [options.flattenMaps=false] if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`. - * @param {Boolean} [options.useProjection=false] - If true, omits fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. - * @return {Object} js object - * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html - * @api public - * @memberOf Document - * @instance - */ - - Document.prototype.toObject = function (options) { - return this.$toObject(options); - }; + return Array.isArray(obj) || + obj.$isMongooseMap || + obj.$__ != null || + leanPopulateMap.has(obj); +} - /*! - * Minimizes an object, removing undefined values and empty objects - * - * @param {Object} object to minimize - * @return {Object} - */ - - function minimize(obj) { - const keys = Object.keys(obj); - let i = keys.length; - let hasKeys; - let key; - let val; - - while (i--) { - key = keys[i]; - val = obj[key]; - - if (utils.isObject(val) && !Buffer.isBuffer(val)) { - obj[key] = minimize(val); - } +function noop(v) { + return v; +} - if (undefined === obj[key]) { - delete obj[key]; - continue; - } +/***/ }), - hasKeys = true; - } +/***/ 5138: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return hasKeys ? obj : undefined; - } +"use strict"; - /*! - * Applies virtuals properties to `json`. - */ - function applyVirtuals(self, json, options, toObjectOptions) { - const schema = self.$__schema; - const paths = Object.keys(schema.virtuals); - let i = paths.length; - const numPaths = i; - let path; - let assignPath; - let cur = self._doc; - let v; - const aliases = get(toObjectOptions, "aliases", true); +const SkipPopulateValue = __nccwpck_require__(694); +const parentPaths = __nccwpck_require__(8123); +const { trusted } = __nccwpck_require__(7776); - let virtualsToApply = null; - if (Array.isArray(options.virtuals)) { - virtualsToApply = new Set(options.virtuals); - } else if (options.virtuals && options.virtuals.pathsToSkip) { - virtualsToApply = new Set(paths); - for (let i = 0; i < options.virtuals.pathsToSkip.length; i++) { - if (virtualsToApply.has(options.virtuals.pathsToSkip[i])) { - virtualsToApply.delete(options.virtuals.pathsToSkip[i]); - } - } - } +module.exports = function createPopulateQueryFilter(ids, _match, _foreignField, model, skipInvalidIds) { + const match = _formatMatch(_match); - if (!cur) { - return json; - } + if (_foreignField.size === 1) { + const foreignField = Array.from(_foreignField)[0]; + const foreignSchemaType = model.schema.path(foreignField); + if (foreignField !== '_id' || !match['_id']) { + ids = _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds); + match[foreignField] = trusted({ $in: ids }); + } - options = options || {}; - for (i = 0; i < numPaths; ++i) { - path = paths[i]; + const _parentPaths = parentPaths(foreignField); + for (let i = 0; i < _parentPaths.length - 1; ++i) { + const cur = _parentPaths[i]; + if (match[cur] != null && match[cur].$elemMatch != null) { + match[cur].$elemMatch[foreignField.slice(cur.length + 1)] = trusted({ $in: ids }); + delete match[foreignField]; + break; + } + } + } else { + const $or = []; + if (Array.isArray(match.$or)) { + match.$and = [{ $or: match.$or }, { $or: $or }]; + delete match.$or; + } else { + match.$or = $or; + } + for (const foreignField of _foreignField) { + if (foreignField !== '_id' || !match['_id']) { + const foreignSchemaType = model.schema.path(foreignField); + ids = _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds); + $or.push({ [foreignField]: { $in: ids } }); + } + } + } - if (virtualsToApply != null && !virtualsToApply.has(path)) { - continue; - } + return match; +}; - // Allow skipping aliases with `toObject({ virtuals: true, aliases: false })` - if (!aliases && schema.aliases.hasOwnProperty(path)) { - continue; - } +/*! + * Optionally filter out invalid ids that don't conform to foreign field's schema + * to avoid cast errors (gh-7706) + */ - // We may be applying virtuals to a nested object, for example if calling - // `doc.nestedProp.toJSON()`. If so, the path we assign to, `assignPath`, - // will be a trailing substring of the `path`. - assignPath = path; - if (options.path != null) { - if (!path.startsWith(options.path + ".")) { - continue; - } - assignPath = path.substr(options.path.length + 1); - } - const parts = assignPath.split("."); - v = clone(self.get(path), options); - if (v === void 0) { - continue; - } - const plen = parts.length; - cur = json; - for (let j = 0; j < plen - 1; ++j) { - cur[parts[j]] = cur[parts[j]] || {}; - cur = cur[parts[j]]; - } - cur[parts[plen - 1]] = v; - } +function _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds) { + ids = ids.filter(v => !(v instanceof SkipPopulateValue)); + if (!skipInvalidIds) { + return ids; + } + return ids.filter(id => { + try { + foreignSchemaType.cast(id); + return true; + } catch (err) { + return false; + } + }); +} - return json; - } +/*! + * Format `mod.match` given that it may be an array that we need to $or if + * the client has multiple docs with match functions + */ - /*! - * Applies virtuals properties to `json`. - * - * @param {Document} self - * @param {Object} json - * @return {Object} `json` - */ +function _formatMatch(match) { + if (Array.isArray(match)) { + if (match.length > 1) { + return { $or: [].concat(match.map(m => Object.assign({}, m))) }; + } + return Object.assign({}, match[0]); + } + return Object.assign({}, match); +} + +/***/ }), + +/***/ 1684: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const MongooseError = __nccwpck_require__(4327); +const SkipPopulateValue = __nccwpck_require__(694); +const get = __nccwpck_require__(8730); +const getDiscriminatorByValue = __nccwpck_require__(8689); +const getConstructorName = __nccwpck_require__(7323); +const getSchemaTypes = __nccwpck_require__(7604); +const getVirtual = __nccwpck_require__(6371); +const lookupLocalFields = __nccwpck_require__(1296); +const mpath = __nccwpck_require__(8586); +const modelNamesFromRefPath = __nccwpck_require__(76); +const utils = __nccwpck_require__(9232); + +const modelSymbol = __nccwpck_require__(3240).modelSymbol; +const populateModelSymbol = __nccwpck_require__(3240).populateModelSymbol; +const schemaMixedSymbol = __nccwpck_require__(1205).schemaMixedSymbol; + +module.exports = function getModelsMapForPopulate(model, docs, options) { + let doc; + const len = docs.length; + const map = []; + const modelNameFromQuery = options.model && options.model.modelName || options.model; + let schema; + let refPath; + let modelNames; + const available = {}; + + const modelSchema = model.schema; + + // Populating a nested path should always be a no-op re: #9073. + // People shouldn't do this, but apparently they do. + if (options._localModel != null && options._localModel.schema.nested[options.path]) { + return []; + } - function applyGetters(self, json, options) { - const schema = self.$__schema; - const paths = Object.keys(schema.paths); - let i = paths.length; - let path; - let cur = self._doc; - let v; + const _virtualRes = getVirtual(model.schema, options.path); + const virtual = _virtualRes == null ? null : _virtualRes.virtual; + if (virtual != null) { + return _virtualPopulate(model, docs, options, _virtualRes); + } - if (!cur) { - return json; - } + let allSchemaTypes = getSchemaTypes(model, modelSchema, null, options.path); + allSchemaTypes = Array.isArray(allSchemaTypes) ? allSchemaTypes : [allSchemaTypes].filter(v => v != null); - while (i--) { - path = paths[i]; + if (allSchemaTypes.length <= 0 && options.strictPopulate !== false && options._localModel != null) { + return new MongooseError('Cannot populate path `' + (options._fullPath || options.path) + + '` because it is not in your schema. Set the `strictPopulate` option ' + + 'to false to override.'); + } - const parts = path.split("."); - const plen = parts.length; - const last = plen - 1; - let branch = json; - let part; - cur = self._doc; + for (let i = 0; i < len; i++) { + doc = docs[i]; + let justOne = null; - if (!self.$__isSelected(path)) { - continue; - } + const docSchema = doc != null && doc.$__ != null ? doc.$__schema : modelSchema; + schema = getSchemaTypes(model, docSchema, doc, options.path); - for (let ii = 0; ii < plen; ++ii) { - part = parts[ii]; - v = cur[part]; - if (ii === last) { - const val = self.get(path); - branch[part] = clone(val, options); - } else if (v == null) { - if (part in cur) { - branch[part] = v; - } - break; - } else { - branch = branch[part] || (branch[part] = {}); - } - cur = v; - } - } + // Special case: populating a path that's a DocumentArray unless + // there's an explicit `ref` or `refPath` re: gh-8946 + if (schema != null && + schema.$isMongooseDocumentArray && + schema.options.ref == null && + schema.options.refPath == null) { + continue; + } + const isUnderneathDocArray = schema && schema.$isUnderneathDocArray; + if (isUnderneathDocArray && get(options, 'options.sort') != null) { + return new MongooseError('Cannot populate with `sort` on path ' + options.path + + ' because it is a subproperty of a document array'); + } - return json; - } + modelNames = null; + let isRefPath = false; + let normalizedRefPath = null; + let schemaOptions = null; + let modelNamesInOrder = null; - /*! - * Applies schema type transforms to `json`. - * - * @param {Document} self - * @param {Object} json - * @return {Object} `json` - */ + if (schema != null && schema.instance === 'Embedded' && schema.options.ref) { + const data = { + localField: options.path + '._id', + foreignField: '_id', + justOne: true + }; + const res = _getModelNames(doc, schema, modelNameFromQuery, model); - function applySchemaTypeTransforms(self, json) { - const schema = self.$__schema; - const paths = Object.keys(schema.paths || {}); - const cur = self._doc; + const unpopulatedValue = mpath.get(options.path, doc); + const id = mpath.get('_id', unpopulatedValue); + addModelNamesToMap(model, map, available, res.modelNames, options, data, id, doc, schemaOptions, unpopulatedValue); + continue; + } - if (!cur) { - return json; + if (Array.isArray(schema)) { + const schemasArray = schema; + for (const _schema of schemasArray) { + let _modelNames; + let res; + try { + res = _getModelNames(doc, _schema, modelNameFromQuery, model); + _modelNames = res.modelNames; + isRefPath = isRefPath || res.isRefPath; + normalizedRefPath = normalizedRefPath || res.refPath; + justOne = res.justOne; + } catch (error) { + return error; } - for (const path of paths) { - const schematype = schema.paths[path]; - if (typeof schematype.options.transform === "function") { - const val = self.get(path); - const transformedValue = schematype.options.transform.call( - self, - val - ); - throwErrorIfPromise(path, transformedValue); - utils.setValue(path, transformedValue, json); - } else if ( - schematype.$embeddedSchemaType != null && - typeof schematype.$embeddedSchemaType.options.transform === - "function" - ) { - const vals = [].concat(self.get(path)); - const transform = schematype.$embeddedSchemaType.options.transform; - for (let i = 0; i < vals.length; ++i) { - const transformedValue = transform.call(self, vals[i]); - vals[i] = transformedValue; - throwErrorIfPromise(path, transformedValue); - } - - json[path] = vals; + if (isRefPath && !res.isRefPath) { + continue; + } + if (!_modelNames) { + continue; + } + modelNames = modelNames || []; + for (const modelName of _modelNames) { + if (modelNames.indexOf(modelName) === -1) { + modelNames.push(modelName); } } - - return json; } - - function throwErrorIfPromise(path, transformedValue) { - if (isPromise(transformedValue)) { - throw new Error( - "`transform` function must be synchronous, but the transform on path `" + - path + - "` returned a promise." - ); + } else { + try { + const res = _getModelNames(doc, schema, modelNameFromQuery, model); + modelNames = res.modelNames; + isRefPath = res.isRefPath; + normalizedRefPath = normalizedRefPath || res.refPath; + justOne = res.justOne; + schemaOptions = get(schema, 'options.populate', null); + // Dedupe, because `refPath` can return duplicates of the same model name, + // and that causes perf issues. + if (isRefPath) { + modelNamesInOrder = modelNames; + modelNames = Array.from(new Set(modelNames)); } + } catch (error) { + return error; } - /*! - * ignore - */ + if (!modelNames) { + continue; + } + } - function omitDeselectedFields(self, json) { - const schema = self.$__schema; - const paths = Object.keys(schema.paths || {}); - const cur = self._doc; + const data = {}; + const localField = options.path; + const foreignField = '_id'; + + // `justOne = null` means we don't know from the schema whether the end + // result should be an array or a single doc. This can result from + // populating a POJO using `Model.populate()` + if ('justOne' in options && options.justOne !== void 0) { + justOne = options.justOne; + } else if (schema && !schema[schemaMixedSymbol]) { + // Skip Mixed types because we explicitly don't do casting on those. + if (options.path.endsWith('.' + schema.path) || options.path === schema.path) { + justOne = Array.isArray(schema) ? + schema.every(schema => !schema.$isMongooseArray) : + !schema.$isMongooseArray; + } + } - if (!cur) { - return json; - } + if (!modelNames) { + continue; + } - let selected = self.$__.selected; - if (selected === void 0) { - selected = {}; - queryhelpers.applyPaths(selected, schema); - } - if (selected == null || Object.keys(selected).length === 0) { - return json; - } + data.isVirtual = false; + data.justOne = justOne; + data.localField = localField; + data.foreignField = foreignField; - for (const path of paths) { - if (selected[path] != null && !selected[path]) { - delete json[path]; - } - } + // Get local fields + const ret = _getLocalFieldValues(doc, localField, model, options, null, schema); - return json; - } - - /** - * The return value of this method is used in calls to JSON.stringify(doc). - * - * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument. - * - * schema.set('toJSON', { virtuals: true }) - * - * See [schema options](/docs/guide.html#toJSON) for details. - * - * @param {Object} options - * @return {Object} - * @see Document#toObject #document_Document-toObject - * @see JSON.stringify() in JavaScript https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html - * @api public - * @memberOf Document - * @instance - */ - - Document.prototype.toJSON = function (options) { - return this.$toObject(options, true); - }; + const id = String(utils.getValue(foreignField, doc)); + options._docs[id] = Array.isArray(ret) ? ret.slice() : ret; - /** - * If this document is a subdocument or populated document, returns the document's - * parent. Returns `undefined` otherwise. - * - * @api public - * @method parent - * @memberOf Document - * @instance - */ - - Document.prototype.parent = function () { - return this.$__.parent; - }; + let match = get(options, 'match', null); - /** - * Alias for `parent()`. If this document is a subdocument or populated - * document, returns the document's parent. Returns `undefined` otherwise. - * - * @api public - * @method $parent - * @memberOf Document - * @instance - */ - - Document.prototype.$parent = Document.prototype.parent; - - /** - * Helper for console.log - * - * @api public - * @method inspect - * @memberOf Document - * @instance - */ - - Document.prototype.inspect = function (options) { - const isPOJO = utils.isPOJO(options); - let opts; - if (isPOJO) { - opts = options; - opts.minimize = false; - } - const ret = this.toObject(opts); + const hasMatchFunction = typeof match === 'function'; + if (hasMatchFunction) { + match = match.call(doc, doc); + } + data.match = match; + data.hasMatchFunction = hasMatchFunction; + data.isRefPath = isRefPath; + data.modelNamesInOrder = modelNamesInOrder; - if (ret == null) { - // If `toObject()` returns null, `this` is still an object, so if `inspect()` - // prints out null this can cause some serious confusion. See gh-7942. - return "MongooseDocument { " + ret + " }"; - } + if (isRefPath) { + const embeddedDiscriminatorModelNames = _findRefPathForDiscriminators(doc, + modelSchema, data, options, normalizedRefPath, ret); - return ret; - }; + modelNames = embeddedDiscriminatorModelNames || modelNames; + } - if (inspect.custom) { - /*! - * Avoid Node deprecation warning DEP0079 - */ + try { + addModelNamesToMap(model, map, available, modelNames, options, data, ret, doc, schemaOptions); + } catch (err) { + return err; + } + } + return map; - Document.prototype[inspect.custom] = Document.prototype.inspect; - } + function _getModelNames(doc, schema, modelNameFromQuery, model) { + let modelNames; + let isRefPath = false; + let justOne = null; - /** - * Helper for console.log - * - * @api public - * @method toString - * @memberOf Document - * @instance - */ + if (schema && schema.instance === 'Array') { + schema = schema.caster; + } + if (schema && schema.$isSchemaMap) { + schema = schema.$__schemaType; + } - Document.prototype.toString = function () { - const ret = this.inspect(); - if (typeof ret === "string") { - return ret; - } - return inspect(ret); - }; + const ref = schema && schema.options && schema.options.ref; + refPath = schema && schema.options && schema.options.refPath; + if (schema != null && + schema[schemaMixedSymbol] && + !ref && + !refPath && + !modelNameFromQuery) { + return { modelNames: null }; + } - /** - * Returns true if this document is equal to another document. - * - * Documents are considered equal when they have matching `_id`s, unless neither - * document has an `_id`, in which case this function falls back to using - * `deepEqual()`. - * - * @param {Document} doc a document to compare - * @return {Boolean} - * @api public - * @memberOf Document - * @instance - */ - - Document.prototype.equals = function (doc) { - if (!doc) { - return false; + if (modelNameFromQuery) { + modelNames = [modelNameFromQuery]; // query options + } else if (refPath != null) { + if (typeof refPath === 'function') { + const subdocPath = options.path.slice(0, options.path.length - schema.path.length - 1); + const vals = mpath.get(subdocPath, doc, lookupLocalFields); + const subdocsBeingPopulated = Array.isArray(vals) ? + utils.array.flatten(vals) : + (vals ? [vals] : []); + + modelNames = new Set(); + for (const subdoc of subdocsBeingPopulated) { + refPath = refPath.call(subdoc, subdoc, options.path); + modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection). + forEach(name => modelNames.add(name)); + } + modelNames = Array.from(modelNames); + } else { + modelNames = modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection); + } + + isRefPath = true; + } else { + let ref; + let refPath; + let schemaForCurrentDoc; + let discriminatorValue; + let modelForCurrentDoc = model; + const discriminatorKey = model.schema.options.discriminatorKey; + + if (!schema && discriminatorKey && (discriminatorValue = utils.getValue(discriminatorKey, doc))) { + // `modelNameForFind` is the discriminator value, so we might need + // find the discriminated model name + const discriminatorModel = getDiscriminatorByValue(model.discriminators, discriminatorValue) || model; + if (discriminatorModel != null) { + modelForCurrentDoc = discriminatorModel; + } else { + try { + modelForCurrentDoc = _getModelFromConn(model.db, discriminatorValue); + } catch (error) { + return error; + } } - const tid = this.$__getValue("_id"); - const docid = doc.$__ != null ? doc.$__getValue("_id") : doc; - if (!tid && !docid) { - return deepEqual(this, doc); - } - return tid && tid.equals ? tid.equals(docid) : tid === docid; - }; + schemaForCurrentDoc = modelForCurrentDoc.schema._getSchema(options.path); - /** - * Populates document references, executing the `callback` when complete. - * If you want to use promises instead, use this function with - * [`execPopulate()`](#document_Document-execPopulate) - * - * ####Example: - * - * doc - * .populate('company') - * .populate({ - * path: 'notes', - * match: /airline/, - * select: 'text', - * model: 'modelName' - * options: opts - * }, function (err, user) { - * assert(doc._id === user._id) // the document itself is passed - * }) - * - * // summary - * doc.populate(path) // not executed - * doc.populate(options); // not executed - * doc.populate(path, callback) // executed - * doc.populate(options, callback); // executed - * doc.populate(callback); // executed - * doc.populate(options).execPopulate() // executed, returns promise - * - * - * ####NOTE: - * - * Population does not occur unless a `callback` is passed *or* you explicitly - * call `execPopulate()`. - * Passing the same path a second time will overwrite the previous path options. - * See [Model.populate()](#model_Model.populate) for explaination of options. - * - * @see Model.populate #model_Model.populate - * @see Document.execPopulate #document_Document-execPopulate - * @param {String|Object} [path] The path to populate or an options object - * @param {Function} [callback] When passed, population is invoked - * @api public - * @return {Document} this - * @memberOf Document - * @instance - */ - - Document.prototype.populate = function populate() { - if (arguments.length === 0) { - return this; + if (schemaForCurrentDoc && schemaForCurrentDoc.caster) { + schemaForCurrentDoc = schemaForCurrentDoc.caster; } + } else { + schemaForCurrentDoc = schema; + } - const pop = this.$__.populate || (this.$__.populate = {}); - const args = utils.args(arguments); - let fn; + if (schemaForCurrentDoc != null) { + justOne = !schemaForCurrentDoc.$isMongooseArray && !schemaForCurrentDoc._arrayPath; + } - if (typeof args[args.length - 1] === "function") { - fn = args.pop(); - } + if ((ref = get(schemaForCurrentDoc, 'options.ref')) != null) { + if (schemaForCurrentDoc != null && + typeof ref === 'function' && + options.path.endsWith('.' + schemaForCurrentDoc.path)) { + // Ensure correct context for ref functions: subdoc, not top-level doc. See gh-8469 + modelNames = new Set(); - // allow `doc.populate(callback)` - if (args.length) { - // use hash to remove duplicate paths - const res = utils.populate.apply(null, args); - for (const populateOptions of res) { - pop[populateOptions.path] = populateOptions; + const subdocPath = options.path.slice(0, options.path.length - schemaForCurrentDoc.path.length - 1); + const vals = mpath.get(subdocPath, doc, lookupLocalFields); + const subdocsBeingPopulated = Array.isArray(vals) ? + utils.array.flatten(vals) : + (vals ? [vals] : []); + for (const subdoc of subdocsBeingPopulated) { + modelNames.add(handleRefFunction(ref, subdoc)); } - } - if (fn) { - const paths = utils.object.vals(pop); - this.$__.populate = undefined; - let topLevelModel = this.constructor; - if (this.$__isNested) { - topLevelModel = this.$__[scopeSymbol].constructor; - const nestedPath = this.$__.nestedPath; - paths.forEach(function (populateOptions) { - populateOptions.path = nestedPath + "." + populateOptions.path; - }); + if (subdocsBeingPopulated.length === 0) { + modelNames = [handleRefFunction(ref, doc)]; + } else { + modelNames = Array.from(modelNames); } + } else { + ref = handleRefFunction(ref, doc); + modelNames = [ref]; + } + } else if ((schemaForCurrentDoc = get(schema, 'options.refPath')) != null) { + isRefPath = true; + if (typeof refPath === 'function') { + const subdocPath = options.path.slice(0, options.path.length - schemaForCurrentDoc.path.length - 1); + const vals = mpath.get(subdocPath, doc, lookupLocalFields); + const subdocsBeingPopulated = Array.isArray(vals) ? + utils.array.flatten(vals) : + (vals ? [vals] : []); + + modelNames = new Set(); + for (const subdoc of subdocsBeingPopulated) { + refPath = refPath.call(subdoc, subdoc, options.path); + modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection). + forEach(name => modelNames.add(name)); + } + modelNames = Array.from(modelNames); + } else { + modelNames = modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection); + } + } + } - // Use `$session()` by default if the document has an associated session - // See gh-6754 - if (this.$session() != null) { - const session = this.$session(); - paths.forEach((path) => { - if (path.options == null) { - path.options = { session: session }; - return; - } - if (!("session" in path.options)) { - path.options.session = session; - } - }); - } + if (!modelNames) { + // `Model.populate()` on a POJO with no known local model. Default to using the `Model` + if (options._localModel == null) { + modelNames = [model.modelName]; + } else { + return { modelNames: modelNames, justOne: justOne, isRefPath: isRefPath, refPath: refPath }; + } + } - topLevelModel.populate(this, paths, fn); - } + if (!Array.isArray(modelNames)) { + modelNames = [modelNames]; + } - return this; - }; + return { modelNames: modelNames, justOne: justOne, isRefPath: isRefPath, refPath: refPath }; + } +}; - /** - * Gets all populated documents associated with this document. - * - * @api public - * @return {Array} array of populated documents. Empty array if there are no populated documents associated with this document. - * @memberOf Document - * @instance - */ - Document.prototype.$getPopulatedDocs = function $getPopulatedDocs() { - let keys = []; - if (this.$__.populated != null) { - keys = keys.concat(Object.keys(this.$__.populated)); - } - if (this.$$populatedVirtuals != null) { - keys = keys.concat(Object.keys(this.$$populatedVirtuals)); - } - let result = []; - for (const key of keys) { - const value = this.get(key); - if (Array.isArray(value)) { - result = result.concat(value); - } else if (value instanceof Document) { - result.push(value); - } - } - return result; - }; +/*! + * ignore + */ - /** - * Explicitly executes population and returns a promise. Useful for promises integration. - * - * ####Example: - * - * const promise = doc. - * populate('company'). - * populate({ - * path: 'notes', - * match: /airline/, - * select: 'text', - * model: 'modelName' - * options: opts - * }). - * execPopulate(); - * - * // summary - * doc.execPopulate().then(resolve, reject); - * - * // you can also use doc.execPopulate(options) as a shorthand for - * // doc.populate(options).execPopulate() - * - * - * ####Example: - * const promise = doc.execPopulate({ path: 'company', select: 'employees' }); - * - * // summary - * promise.then(resolve,reject); - * - * @see Document.populate #document_Document-populate - * @api public - * @param {Function} [callback] optional callback. If specified, a promise will **not** be returned - * @return {Promise} promise that resolves to the document when population is done - * @memberOf Document - * @instance - */ - - Document.prototype.execPopulate = function (callback) { - const isUsingShorthand = - callback != null && typeof callback !== "function"; - if (isUsingShorthand) { - return this.populate.apply(this, arguments).execPopulate(); - } - - return promiseOrCallback( - callback, - (cb) => { - this.populate(cb); - }, - this.constructor.events - ); - }; +function _virtualPopulate(model, docs, options, _virtualRes) { + const map = []; + const available = {}; + const virtual = _virtualRes.virtual; + + for (const doc of docs) { + let modelNames = null; + const data = {}; + + // localField and foreignField + let localField; + const virtualPrefix = _virtualRes.nestedSchemaPath ? + _virtualRes.nestedSchemaPath + '.' : ''; + if (typeof virtual.options.localField === 'function') { + localField = virtualPrefix + virtual.options.localField.call(doc, doc); + } else if (Array.isArray(virtual.options.localField)) { + localField = virtual.options.localField.map(field => virtualPrefix + field); + } else { + localField = virtualPrefix + virtual.options.localField; + } + data.count = virtual.options.count; - /** - * Gets _id(s) used during population of the given `path`. - * - * ####Example: - * - * Model.findOne().populate('author').exec(function (err, doc) { - * console.log(doc.author.name) // Dr.Seuss - * console.log(doc.populated('author')) // '5144cf8050f071d979c118a7' - * }) - * - * If the path was not populated, returns `undefined`. - * - * @param {String} path - * @return {Array|ObjectId|Number|Buffer|String|undefined} - * @memberOf Document - * @instance - * @api public - */ - - Document.prototype.populated = function (path, val, options) { - // val and options are internal - if (val == null || val === true) { - if (!this.$__.populated) { - return undefined; - } + if (virtual.options.skip != null && !options.hasOwnProperty('skip')) { + options.skip = virtual.options.skip; + } + if (virtual.options.limit != null && !options.hasOwnProperty('limit')) { + options.limit = virtual.options.limit; + } + if (virtual.options.perDocumentLimit != null && !options.hasOwnProperty('perDocumentLimit')) { + options.perDocumentLimit = virtual.options.perDocumentLimit; + } + let foreignField = virtual.options.foreignField; - // Map paths can be populated with either `path.$*` or just `path` - const _path = path.endsWith(".$*") - ? path.replace(/\.\$\*$/, "") - : path; + if (!localField || !foreignField) { + return new MongooseError('If you are populating a virtual, you must set the ' + + 'localField and foreignField options'); + } - const v = this.$__.populated[_path]; - if (v) { - return val === true ? v : v.value; - } - return undefined; - } - - this.$__.populated || (this.$__.populated = {}); - this.$__.populated[path] = { value: val, options: options }; - - // If this was a nested populate, make sure each populated doc knows - // about its populated children (gh-7685) - const pieces = path.split("."); - for (let i = 0; i < pieces.length - 1; ++i) { - const subpath = pieces.slice(0, i + 1).join("."); - const subdoc = this.get(subpath); - if (subdoc != null && subdoc.$__ != null && this.populated(subpath)) { - const rest = pieces.slice(i + 1).join("."); - subdoc.populated(rest, val, options); - // No need to continue because the above recursion should take care of - // marking the rest of the docs as populated - break; - } - } + if (typeof localField === 'function') { + localField = localField.call(doc, doc); + } + if (typeof foreignField === 'function') { + foreignField = foreignField.call(doc); + } - return val; - }; + data.isRefPath = false; - /** - * Takes a populated field and returns it to its unpopulated state. - * - * ####Example: - * - * Model.findOne().populate('author').exec(function (err, doc) { - * console.log(doc.author.name); // Dr.Seuss - * console.log(doc.depopulate('author')); - * console.log(doc.author); // '5144cf8050f071d979c118a7' - * }) - * - * If the path was not provided, then all populated fields are returned to their unpopulated state. - * - * @param {String} path - * @return {Document} this - * @see Document.populate #document_Document-populate - * @api public - * @memberOf Document - * @instance - */ - - Document.prototype.depopulate = function (path) { - if (typeof path === "string") { - path = path.split(" "); - } - - let populatedIds; - const virtualKeys = this.$$populatedVirtuals - ? Object.keys(this.$$populatedVirtuals) - : []; - const populated = get(this, "$__.populated", {}); - - if (arguments.length === 0) { - // Depopulate all - for (const virtualKey of virtualKeys) { - delete this.$$populatedVirtuals[virtualKey]; - delete this._doc[virtualKey]; - delete populated[virtualKey]; - } + // `justOne = null` means we don't know from the schema whether the end + // result should be an array or a single doc. This can result from + // populating a POJO using `Model.populate()` + let justOne = null; + if ('justOne' in options && options.justOne !== void 0) { + justOne = options.justOne; + } - const keys = Object.keys(populated); + if (virtual.options.refPath) { + modelNames = + modelNamesFromRefPath(virtual.options.refPath, doc, options.path); + justOne = !!virtual.options.justOne; + data.isRefPath = true; + } else if (virtual.options.ref) { + let normalizedRef; + if (typeof virtual.options.ref === 'function' && !virtual.options.ref[modelSymbol]) { + normalizedRef = virtual.options.ref.call(doc, doc); + } else { + normalizedRef = virtual.options.ref; + } + justOne = !!virtual.options.justOne; + // When referencing nested arrays, the ref should be an Array + // of modelNames. + if (Array.isArray(normalizedRef)) { + modelNames = normalizedRef; + } else { + modelNames = [normalizedRef]; + } + } - for (const key of keys) { - populatedIds = this.populated(key); - if (!populatedIds) { - continue; - } - delete populated[key]; - this.$set(key, populatedIds); - } - return this; - } + data.isVirtual = true; + data.virtual = virtual; + data.justOne = justOne; - for (const singlePath of path) { - populatedIds = this.populated(singlePath); - delete populated[singlePath]; + // `match` + let match = get(options, 'match', null) || + get(data, 'virtual.options.match', null) || + get(data, 'virtual.options.options.match', null); - if (virtualKeys.indexOf(singlePath) !== -1) { - delete this.$$populatedVirtuals[singlePath]; - delete this._doc[singlePath]; - } else if (populatedIds) { - this.$set(singlePath, populatedIds); - } - } - return this; - }; + let hasMatchFunction = typeof match === 'function'; + if (hasMatchFunction) { + match = match.call(doc, doc); + } - /** - * Returns the full path to this document. - * - * @param {String} [path] - * @return {String} - * @api private - * @method $__fullPath - * @memberOf Document - * @instance - */ - - Document.prototype.$__fullPath = function (path) { - // overridden in SubDocuments - return path || ""; - }; + if (Array.isArray(localField) && Array.isArray(foreignField) && localField.length === foreignField.length) { + match = Object.assign({}, match); + for (let i = 1; i < localField.length; ++i) { + match[foreignField[i]] = convertTo_id(mpath.get(localField[i], doc, lookupLocalFields), model.schema); + hasMatchFunction = true; + } - /** - * Returns the changes that happened to the document - * in the format that will be sent to MongoDB. - * - * #### Example: - * - * const userSchema = new Schema({ - * name: String, - * age: Number, - * country: String - * }); - * const User = mongoose.model('User', userSchema); - * const user = await User.create({ - * name: 'Hafez', - * age: 25, - * country: 'Egypt' - * }); - * - * // returns an empty object, no changes happened yet - * user.getChanges(); // { } - * - * user.country = undefined; - * user.age = 26; - * - * user.getChanges(); // { $set: { age: 26 }, { $unset: { country: 1 } } } - * - * await user.save(); - * - * user.getChanges(); // { } - * - * Modifying the object that `getChanges()` returns does not affect the document's - * change tracking state. Even if you `delete user.getChanges().$set`, Mongoose - * will still send a `$set` to the server. - * - * @return {Object} - * @api public - * @method getChanges - * @memberOf Document - * @instance - */ - - Document.prototype.getChanges = function () { - const delta = this.$__delta(); - const changes = delta ? delta[1] : {}; - return changes; - }; + localField = localField[0]; + foreignField = foreignField[0]; + } - /*! - * Module exports. - */ + data.localField = localField; + data.foreignField = foreignField; + data.match = match; + data.hasMatchFunction = hasMatchFunction; - Document.ValidationError = ValidationError; - module.exports = exports = Document; + // Get local fields + const ret = _getLocalFieldValues(doc, localField, model, options, virtual); - /***/ - }, + try { + addModelNamesToMap(model, map, available, modelNames, options, data, ret, doc); + } catch (err) { + return err; + } + } - /***/ 1860: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /* eslint-env browser */ - - /*! - * Module dependencies. - */ - const Document = __nccwpck_require__(6717); - const BrowserDocument = __nccwpck_require__(6830); - - let isBrowser = false; - - /** - * Returns the Document constructor for the current context - * - * @api private - */ - module.exports = function () { - if (isBrowser) { - return BrowserDocument; - } - return Document; - }; + return map; +} - /*! - * ignore - */ - module.exports.setBrowser = function (flag) { - isBrowser = flag; - }; +/*! + * ignore + */ - /***/ - }, +function addModelNamesToMap(model, map, available, modelNames, options, data, ret, doc, schemaOptions, unpopulatedValue) { + // `PopulateOptions#connection`: if the model is passed as a string, the + // connection matters because different connections have different models. + const connection = options.connection != null ? options.connection : model.db; - /***/ 2324: /***/ (module) => { - "use strict"; + unpopulatedValue = unpopulatedValue === void 0 ? ret : unpopulatedValue; + if (Array.isArray(unpopulatedValue)) { + unpopulatedValue = utils.cloneArrays(unpopulatedValue); + } - /*! - * ignore - */ + if (modelNames == null) { + return; + } - let driver = null; + let k = modelNames.length; + while (k--) { + const modelName = modelNames[k]; + if (modelName == null) { + continue; + } - module.exports.get = function () { - return driver; - }; + let Model; + if (options.model && options.model[modelSymbol]) { + Model = options.model; + } else if (modelName[modelSymbol]) { + Model = modelName; + } else { + try { + Model = _getModelFromConn(connection, modelName); + } catch (err) { + if (ret !== void 0) { + throw err; + } + Model = null; + } + } - module.exports.set = function (v) { - driver = v; - }; + let ids = ret; + const flat = Array.isArray(ret) ? utils.array.flatten(ret) : []; - /***/ - }, + const modelNamesForRefPath = data.modelNamesInOrder ? data.modelNamesInOrder : modelNames; + if (data.isRefPath && Array.isArray(ret) && flat.length === modelNamesForRefPath.length) { + ids = flat.filter((val, i) => modelNamesForRefPath[i] === modelName); + } - /***/ 8001: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ + const perDocumentLimit = options.perDocumentLimit == null ? + get(options, 'options.perDocumentLimit', null) : + options.perDocumentLimit; + + if (!available[modelName] || perDocumentLimit != null) { + const currentOptions = { + model: Model + }; + + if (data.isVirtual && get(data.virtual, 'options.options')) { + currentOptions.options = utils.clone(data.virtual.options.options); + } else if (schemaOptions != null) { + currentOptions.options = Object.assign({}, schemaOptions); + } + utils.merge(currentOptions, options); + + // Used internally for checking what model was used to populate this + // path. + options[populateModelSymbol] = Model; + + available[modelName] = { + model: Model, + options: currentOptions, + match: data.hasMatchFunction ? [data.match] : data.match, + docs: [doc], + ids: [ids], + allIds: [ret], + unpopulatedValues: [unpopulatedValue], + localField: new Set([data.localField]), + foreignField: new Set([data.foreignField]), + justOne: data.justOne, + isVirtual: data.isVirtual, + virtual: data.virtual, + count: data.count, + [populateModelSymbol]: Model + }; + map.push(available[modelName]); + } else { + available[modelName].localField.add(data.localField); + available[modelName].foreignField.add(data.foreignField); + available[modelName].docs.push(doc); + available[modelName].ids.push(ids); + available[modelName].allIds.push(ret); + available[modelName].unpopulatedValues.push(unpopulatedValue); + if (data.hasMatchFunction) { + available[modelName].match.push(data.match); + } + } + } +} - const mongodb = __nccwpck_require__(5517); - const ReadPref = mongodb.ReadPreference; +function _getModelFromConn(conn, modelName) { + /* If this connection has a parent from `useDb()`, bubble up to parent's models */ + if (conn.models[modelName] == null && conn._parent != null) { + return _getModelFromConn(conn._parent, modelName); + } - /*! - * Converts arguments to ReadPrefs the driver - * can understand. - * - * @param {String|Array} pref - * @param {Array} [tags] - */ + return conn.model(modelName); +} - module.exports = function readPref(pref, tags) { - if (Array.isArray(pref)) { - tags = pref[1]; - pref = pref[0]; - } +/*! + * ignore + */ - if (pref instanceof ReadPref) { - return pref; - } +function handleRefFunction(ref, doc) { + if (typeof ref === 'function' && !ref[modelSymbol]) { + return ref.call(doc, doc); + } + return ref; +} - switch (pref) { - case "p": - pref = "primary"; - break; - case "pp": - pref = "primaryPreferred"; - break; - case "s": - pref = "secondary"; - break; - case "sp": - pref = "secondaryPreferred"; - break; - case "n": - pref = "nearest"; - break; - } +/*! + * ignore + */ - return new ReadPref(pref, tags); - }; +function _getLocalFieldValues(doc, localField, model, options, virtual, schema) { + // Get Local fields + const localFieldPathType = model.schema._getPathType(localField); + const localFieldPath = localFieldPathType === 'real' ? + model.schema.path(localField) : + localFieldPathType.schema; + const localFieldGetters = localFieldPath && localFieldPath.getters ? + localFieldPath.getters : []; + + localField = localFieldPath != null && localFieldPath.instance === 'Embedded' ? localField + '._id' : localField; + + const _populateOptions = get(options, 'options', {}); + + const getters = 'getters' in _populateOptions ? + _populateOptions.getters : + get(virtual, 'options.getters', false); + if (localFieldGetters.length > 0 && getters) { + const hydratedDoc = (doc.$__ != null) ? doc : model.hydrate(doc); + const localFieldValue = utils.getValue(localField, doc); + if (Array.isArray(localFieldValue)) { + const localFieldHydratedValue = utils.getValue(localField.split('.').slice(0, -1), hydratedDoc); + return localFieldValue.map((localFieldArrVal, localFieldArrIndex) => + localFieldPath.applyGetters(localFieldArrVal, localFieldHydratedValue[localFieldArrIndex])); + } else { + return localFieldPath.applyGetters(localFieldValue, hydratedDoc); + } + } else { + return convertTo_id(mpath.get(localField, doc, lookupLocalFields), schema); + } +} - /***/ - }, +/*! + * Retrieve the _id of `val` if a Document or Array of Documents. + * + * @param {Array|Document|Any} val + * @return {Array|Document|Any} + */ - /***/ 4473: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; +function convertTo_id(val, schema) { + if (val != null && val.$__ != null) { + return val._id; + } + if (val != null && val._id != null && (schema == null || !schema.$isSchemaMap)) { + return val._id; + } - /*! - * Module dependencies. - */ + if (Array.isArray(val)) { + const rawVal = val.__array != null ? val.__array : val; + for (let i = 0; i < rawVal.length; ++i) { + if (rawVal[i] != null && rawVal[i].$__ != null) { + rawVal[i] = rawVal[i]._id; + } + } + if (val.isMongooseArray && val.$schema()) { + return val.$schema()._castForPopulate(val, val.$parent()); + } - const Binary = __nccwpck_require__(5517).Binary; + return [].concat(val); + } - module.exports = exports = Binary; + // `populate('map')` may be an object if populating on a doc that hasn't + // been hydrated yet + if (getConstructorName(val) === 'Object' && + // The intent here is we should only flatten the object if we expect + // to get a Map in the end. Avoid doing this for mixed types. + (schema == null || schema[schemaMixedSymbol] == null)) { + const ret = []; + for (const key of Object.keys(val)) { + ret.push(val[key]); + } + return ret; + } + // If doc has already been hydrated, e.g. `doc.populate('map')` + // then `val` will already be a map + if (val instanceof Map) { + return Array.from(val.values()); + } - /***/ - }, + return val; +} - /***/ 449: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const MongooseCollection = __nccwpck_require__(6798); - const MongooseError = __nccwpck_require__(5953); - const Collection = __nccwpck_require__(5517).Collection; - const ObjectId = __nccwpck_require__(3589); - const get = __nccwpck_require__(8730); - const getConstructorName = __nccwpck_require__(7323); - const sliced = __nccwpck_require__(9889); - const stream = __nccwpck_require__(2413); - const util = __nccwpck_require__(1669); - - /** - * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) collection implementation. - * - * All methods methods from the [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver are copied and wrapped in queue management. - * - * @inherits Collection - * @api private - */ - - function NativeCollection(name, conn, options) { - this.collection = null; - this.Promise = options.Promise || Promise; - this.modelName = options.modelName; - delete options.modelName; - this._closed = false; - MongooseCollection.apply(this, arguments); - } - - /*! - * Inherit from abstract Collection. - */ - - NativeCollection.prototype.__proto__ = MongooseCollection.prototype; - - /** - * Called when the connection opens. - * - * @api private - */ - - NativeCollection.prototype.onOpen = function () { - const _this = this; +/*! + * ignore + */ - // always get a new collection in case the user changed host:port - // of parent db instance when re-opening the connection. +function _findRefPathForDiscriminators(doc, modelSchema, data, options, normalizedRefPath, ret) { + // Re: gh-8452. Embedded discriminators may not have `refPath`, so clear + // out embedded discriminator docs that don't have a `refPath` on the + // populated path. + if (!data.isRefPath || normalizedRefPath == null) { + return; + } - if (!_this.opts.capped.size) { - // non-capped - callback(null, _this.conn.db.collection(_this.name)); - return _this.collection; + const pieces = normalizedRefPath.split('.'); + let cur = ''; + let modelNames = void 0; + for (let i = 0; i < pieces.length; ++i) { + const piece = pieces[i]; + cur = cur + (cur.length === 0 ? '' : '.') + piece; + const schematype = modelSchema.path(cur); + if (schematype != null && + schematype.$isMongooseArray && + schematype.caster.discriminators != null && + Object.keys(schematype.caster.discriminators).length > 0) { + const subdocs = utils.getValue(cur, doc); + const remnant = options.path.substr(cur.length + 1); + const discriminatorKey = schematype.caster.schema.options.discriminatorKey; + modelNames = []; + for (const subdoc of subdocs) { + const discriminatorName = utils.getValue(discriminatorKey, subdoc); + const discriminator = schematype.caster.discriminators[discriminatorName]; + const discriminatorSchema = discriminator && discriminator.schema; + if (discriminatorSchema == null) { + continue; } - - if (_this.opts.autoCreate === false) { - _this.collection = _this.conn.db.collection(_this.name); - MongooseCollection.prototype.onOpen.call(_this); - return _this.collection; + const _path = discriminatorSchema.path(remnant); + if (_path == null || _path.options.refPath == null) { + const docValue = utils.getValue(data.localField.substr(cur.length + 1), subdoc); + ret.forEach((v, i) => { + if (v === docValue) { + ret[i] = SkipPopulateValue(v); + } + }); + continue; } + const modelName = utils.getValue(pieces.slice(i + 1).join('.'), subdoc); + modelNames.push(modelName); + } + } + } - // capped - return _this.conn.db.collection(_this.name, function (err, c) { - if (err) return callback(err); + return modelNames; +} - // discover if this collection exists and if it is capped - _this.conn.db - .listCollections({ name: _this.name }) - .toArray(function (err, docs) { - if (err) { - return callback(err); - } - const doc = docs[0]; - const exists = !!doc; +/***/ }), - if (exists) { - if (doc.options && doc.options.capped) { - callback(null, c); - } else { - const msg = - "A non-capped collection exists with the name: " + - _this.name + - "\n\n" + - " To use this collection as a capped collection, please " + - "first convert it.\n" + - " http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped"; - err = new Error(msg); - callback(err); - } - } else { - // create - const opts = Object.assign({}, _this.opts.capped); - opts.capped = true; - _this.conn.db.createCollection(_this.name, opts, callback); - } - }); - }); +/***/ 7604: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function callback(err, collection) { - if (err) { - // likely a strict mode error - _this.conn.emit("error", err); - } else { - _this.collection = collection; - MongooseCollection.prototype.onOpen.call(_this); - } - } - }; +"use strict"; - /** - * Called when the connection closes - * - * @api private - */ - NativeCollection.prototype.onClose = function (force) { - MongooseCollection.prototype.onClose.call(this, force); - }; +/*! + * ignore + */ - /*! - * ignore - */ - - const syncCollectionMethods = { watch: true }; - - /*! - * Copy the collection methods and make them subject to queues - */ - - function iter(i) { - NativeCollection.prototype[i] = function () { - const collection = this.collection; - const args = Array.from(arguments); - const _this = this; - const debug = get(_this, "conn.base.options.debug"); - const lastArg = arguments[arguments.length - 1]; - const opId = new ObjectId(); - - // If user force closed, queueing will hang forever. See #5664 - if (this.conn.$wasForceClosed) { - const error = new MongooseError("Connection was force closed"); - if ( - args.length > 0 && - typeof args[args.length - 1] === "function" - ) { - args[args.length - 1](error); - return; - } else { - throw error; - } - } +const Mixed = __nccwpck_require__(7495); +const get = __nccwpck_require__(8730); +const getDiscriminatorByValue = __nccwpck_require__(8689); +const leanPopulateMap = __nccwpck_require__(914); +const mpath = __nccwpck_require__(8586); - let _args = args; - let callback = null; - if (this._shouldBufferCommands() && this.buffer) { - if (syncCollectionMethods[i]) { - throw new Error("Collection method " + i + " is synchronous"); - } +const populateModelSymbol = __nccwpck_require__(3240).populateModelSymbol; - this.conn.emit("buffer", { - _id: opId, - modelName: _this.modelName, - collectionName: _this.name, - method: i, - args: args, - }); +/*! + * Given a model and its schema, find all possible schema types for `path`, + * including searching through discriminators. If `doc` is specified, will + * use the doc's values for discriminator keys when searching, otherwise + * will search all discriminators. + * + * @param {Schema} schema + * @param {Object} doc POJO + * @param {string} path + */ - let callback; - let _args; - let promise = null; - let timeout = null; - if (typeof lastArg === "function") { - callback = function collectionOperationCallback() { - if (timeout != null) { - clearTimeout(timeout); - } - return lastArg.apply(this, arguments); - }; - _args = args.slice(0, args.length - 1).concat([callback]); - } else { - promise = new this.Promise((resolve, reject) => { - callback = function collectionOperationCallback(err, res) { - if (timeout != null) { - clearTimeout(timeout); - } - if (err != null) { - return reject(err); - } - resolve(res); - }; - _args = args.concat([callback]); - this.addQueue(i, _args); - }); - } +module.exports = function getSchemaTypes(model, schema, doc, path) { + const pathschema = schema.path(path); + const topLevelDoc = doc; + if (pathschema) { + return pathschema; + } - const bufferTimeoutMS = this._getBufferTimeoutMS(); - timeout = setTimeout(() => { - const removed = this.removeQueue(i, _args); - if (removed) { - const message = - "Operation `" + - this.name + - "." + - i + - "()` buffering timed out after " + - bufferTimeoutMS + - "ms"; - const err = new MongooseError(message); - this.conn.emit("buffer-end", { - _id: opId, - modelName: _this.modelName, - collectionName: _this.name, - method: i, - error: err, - }); - callback(err); - } - }, bufferTimeoutMS); + const discriminatorKey = schema.discriminatorMapping && + schema.discriminatorMapping.key; + if (discriminatorKey && model != null) { + if (doc != null && doc[discriminatorKey] != null) { + const discriminator = getDiscriminatorByValue(model.discriminators, doc[discriminatorKey]); + schema = discriminator ? discriminator.schema : schema; + } else if (model.discriminators != null) { + return Object.keys(model.discriminators).reduce((arr, name) => { + const disc = model.discriminators[name]; + return arr.concat(getSchemaTypes(disc, disc.schema, null, path)); + }, []); + } + } - if (typeof lastArg === "function") { - this.addQueue(i, _args); - return; - } + function search(parts, schema, subdoc, nestedPath) { + let p = parts.length + 1; + let foundschema; + let trypath; - return promise; - } else if ( - !syncCollectionMethods[i] && - typeof lastArg === "function" - ) { - callback = function collectionOperationCallback(err, res) { - if (err != null) { - _this.conn.emit("operation-end", { - _id: opId, - modelName: _this.modelName, - collectionName: _this.name, - method: i, - error: err, - }); - } else { - _this.conn.emit("operation-end", { - _id: opId, - modelName: _this.modelName, - collectionName: _this.name, - method: i, - result: res, - }); + while (p--) { + trypath = parts.slice(0, p).join('.'); + foundschema = schema.path(trypath); + if (foundschema == null) { + continue; + } + + if (foundschema.caster) { + // array of Mixed? + if (foundschema.caster instanceof Mixed) { + return foundschema.caster; + } + + let schemas = null; + if (foundschema.schema != null && foundschema.schema.discriminators != null) { + const discriminators = foundschema.schema.discriminators; + const discriminatorKeyPath = trypath + '.' + + foundschema.schema.options.discriminatorKey; + const keys = subdoc ? mpath.get(discriminatorKeyPath, subdoc) || [] : []; + schemas = Object.keys(discriminators). + reduce(function(cur, discriminator) { + const tiedValue = discriminators[discriminator].discriminatorMapping.value; + if (doc == null || keys.indexOf(discriminator) !== -1 || keys.indexOf(tiedValue) !== -1) { + cur.push(discriminators[discriminator]); } - return lastArg.apply(this, arguments); - }; - _args = args.slice(0, args.length - 1).concat([callback]); - } + return cur; + }, []); + } - if (debug) { - if (typeof debug === "function") { - debug.apply( - _this, - [_this.name, i].concat(sliced(args, 0, args.length - 1)) - ); - } else if (debug instanceof stream.Writable) { - this.$printToStream(_this.name, i, args, debug); - } else { - const color = debug.color == null ? true : debug.color; - const shell = debug.shell == null ? false : debug.shell; - this.$print(_this.name, i, args, color, shell); + // Now that we found the array, we need to check if there + // are remaining document paths to look up for casting. + // Also we need to handle array.$.path since schema.path + // doesn't work for that. + // If there is no foundschema.schema we are dealing with + // a path like array.$ + if (p !== parts.length && foundschema.schema) { + let ret; + if (parts[p] === '$') { + if (p + 1 === parts.length) { + // comments.$ + return foundschema; + } + // comments.$.comments.$.title + ret = search( + parts.slice(p + 1), + schema, + subdoc ? mpath.get(trypath, subdoc) : null, + nestedPath.concat(parts.slice(0, p)) + ); + if (ret) { + ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || + !foundschema.schema.$isSingleNested; } + return ret; } - this.conn.emit("operation-start", { - _id: opId, - modelName: _this.modelName, - collectionName: this.name, - method: i, - params: _args, - }); - - try { - if (collection == null) { - const message = - "Cannot call `" + - this.name + - "." + - i + - "()` before initial connection " + - "is complete if `bufferCommands = false`. Make sure you `await mongoose.connect()` if " + - "you have `bufferCommands = false`."; - throw new MongooseError(message); - } - const ret = collection[i].apply(collection, _args); - if (ret != null && typeof ret.then === "function") { - return ret.then( - (res) => { - this.conn.emit("operation-end", { - _id: opId, - modelName: this.modelName, - collectionName: this.name, - method: i, - result: res, - }); - return res; - }, - (err) => { - this.conn.emit("operation-end", { - _id: opId, - modelName: this.modelName, - collectionName: this.name, - method: i, - error: err, - }); - throw err; - } + if (schemas != null && schemas.length > 0) { + ret = []; + for (const schema of schemas) { + const _ret = search( + parts.slice(p), + schema, + subdoc ? mpath.get(trypath, subdoc) : null, + nestedPath.concat(parts.slice(0, p)) ); + if (_ret != null) { + _ret.$isUnderneathDocArray = _ret.$isUnderneathDocArray || + !foundschema.schema.$isSingleNested; + if (_ret.$isUnderneathDocArray) { + ret.$isUnderneathDocArray = true; + } + ret.push(_ret); + } } return ret; - } catch (error) { - // Collection operation may throw because of max bson size, catch it here - // See gh-3906 - if (typeof callback === "function") { - callback(error); - } else { - this.conn.emit("operation-end", { - _id: opId, - modelName: _this.modelName, - collectionName: this.name, - method: i, - error: error, - }); - } - if (typeof lastArg === "function") { - lastArg(error); - } else { - throw error; - } - } - }; - } - - for (const key of Object.keys(Collection.prototype)) { - // Janky hack to work around gh-3005 until we can get rid of the mongoose - // collection abstraction - const descriptor = Object.getOwnPropertyDescriptor( - Collection.prototype, - key - ); - // Skip properties with getters because they may throw errors (gh-8528) - if (descriptor.get !== undefined) { - continue; - } - if (typeof Collection.prototype[key] !== "function") { - continue; - } + } else { + ret = search( + parts.slice(p), + foundschema.schema, + subdoc ? mpath.get(trypath, subdoc) : null, + nestedPath.concat(parts.slice(0, p)) + ); - iter(key); - } - - /** - * Debug print helper - * - * @api public - * @method $print - */ - - NativeCollection.prototype.$print = function ( - name, - i, - args, - color, - shell - ) { - const moduleName = color ? "\x1B[0;36mMongoose:\x1B[0m " : "Mongoose: "; - const functionCall = [name, i].join("."); - const _args = []; - for (let j = args.length - 1; j >= 0; --j) { - if (this.$format(args[j]) || _args.length) { - _args.unshift(this.$format(args[j], color, shell)); + if (ret) { + ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || + !foundschema.schema.$isSingleNested; + } + return ret; } - } - const params = "(" + _args.join(", ") + ")"; - - console.info(moduleName + functionCall + params); - }; - - /** - * Debug print helper - * - * @api public - * @method $print - */ - - NativeCollection.prototype.$printToStream = function ( - name, - i, - args, - stream - ) { - const functionCall = [name, i].join("."); - const _args = []; - for (let j = args.length - 1; j >= 0; --j) { - if (this.$format(args[j]) || _args.length) { - _args.unshift(this.$format(args[j])); + } else if (p !== parts.length && + foundschema.$isMongooseArray && + foundschema.casterConstructor.$isMongooseArray) { + // Nested arrays. Drill down to the bottom of the nested array. + let type = foundschema; + while (type.$isMongooseArray && !type.$isMongooseDocumentArray) { + type = type.casterConstructor; } - } - const params = "(" + _args.join(", ") + ")"; - - stream.write(functionCall + params, "utf8"); - }; - - /** - * Formatter for debug print args - * - * @api public - * @method $format - */ - - NativeCollection.prototype.$format = function (arg, color, shell) { - const type = typeof arg; - if (type === "function" || type === "undefined") return ""; - return format(arg, false, color, shell); - }; - /*! - * Debug print helper - */ + const ret = search( + parts.slice(p), + type.schema, + null, + nestedPath.concat(parts.slice(0, p)) + ); + if (ret != null) { + return ret; + } - function inspectable(representation) { - const ret = { - inspect: function () { - return representation; - }, - }; - if (util.inspect.custom) { - ret[util.inspect.custom] = ret.inspect; - } - return ret; - } - function map(o) { - return format(o, true); - } - function formatObjectId(x, key) { - x[key] = inspectable('ObjectId("' + x[key].toHexString() + '")'); - } - function formatDate(x, key, shell) { - if (shell) { - x[key] = inspectable('ISODate("' + x[key].toUTCString() + '")'); - } else { - x[key] = inspectable('new Date("' + x[key].toUTCString() + '")'); - } - } - function format(obj, sub, color, shell) { - if (obj && typeof obj.toBSON === "function") { - obj = obj.toBSON(); - } - if (obj == null) { - return obj; - } - - const clone = __nccwpck_require__(5092); - let x = clone(obj, { transform: false }); - const constructorName = getConstructorName(x); - - if (constructorName === "Binary") { - x = "BinData(" + x.sub_type + ', "' + x.toString("base64") + '")'; - } else if (constructorName === "ObjectID") { - x = inspectable('ObjectId("' + x.toHexString() + '")'); - } else if (constructorName === "Date") { - x = inspectable('new Date("' + x.toUTCString() + '")'); - } else if (constructorName === "Object") { - const keys = Object.keys(x); - const numKeys = keys.length; - let key; - for (let i = 0; i < numKeys; ++i) { - key = keys[i]; - if (x[key]) { - let error; - if (typeof x[key].toBSON === "function") { - try { - // `session.toBSON()` throws an error. This means we throw errors - // in debug mode when using transactions, see gh-6712. As a - // workaround, catch `toBSON()` errors, try to serialize without - // `toBSON()`, and rethrow if serialization still fails. - x[key] = x[key].toBSON(); - } catch (_error) { - error = _error; - } - } - const _constructorName = getConstructorName(x[key]); - if (_constructorName === "Binary") { - x[key] = - "BinData(" + - x[key].sub_type + - ', "' + - x[key].buffer.toString("base64") + - '")'; - } else if (_constructorName === "Object") { - x[key] = format(x[key], true); - } else if (_constructorName === "ObjectID") { - formatObjectId(x, key); - } else if (_constructorName === "Date") { - formatDate(x, key, shell); - } else if (_constructorName === "ClientSession") { - x[key] = inspectable( - 'ClientSession("' + - get(x[key], "id.id.buffer", "").toString("hex") + - '")' - ); - } else if (Array.isArray(x[key])) { - x[key] = x[key].map(map); - } else if (error != null) { - // If there was an error with `toBSON()` and the object wasn't - // already converted to a string representation, rethrow it. - // Open to better ideas on how to handle this. - throw error; + if (type.schema.discriminators) { + const discriminatorPaths = []; + for (const discriminatorName of Object.keys(type.schema.discriminators)) { + const _schema = type.schema.discriminators[discriminatorName] || type.schema; + const ret = search(parts.slice(p), _schema, null, nestedPath.concat(parts.slice(0, p))); + if (ret != null) { + discriminatorPaths.push(ret); } } + if (discriminatorPaths.length > 0) { + return discriminatorPaths; + } } } - if (sub) { - return x; - } - - return util - .inspect(x, false, 10, color) - .replace(/\n/g, "") - .replace(/\s{2,}/g, " "); } - /** - * Retrieves information about this collections indexes. - * - * @param {Function} callback - * @method getIndexes - * @api public - */ + const fullPath = nestedPath.concat([trypath]).join('.'); + if (topLevelDoc != null && topLevelDoc.$__ && topLevelDoc.$populated(fullPath) && p < parts.length) { + const model = doc.$__.populated[fullPath].options[populateModelSymbol]; + if (model != null) { + const ret = search( + parts.slice(p), + model.schema, + subdoc ? mpath.get(trypath, subdoc) : null, + nestedPath.concat(parts.slice(0, p)) + ); - NativeCollection.prototype.getIndexes = - NativeCollection.prototype.indexInformation; + if (ret) { + ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || + !model.schema.$isSingleNested; + } + return ret; + } + } - /*! - * Module exports. - */ + const _val = get(topLevelDoc, trypath); + if (_val != null) { + const model = Array.isArray(_val) && _val.length > 0 ? + leanPopulateMap.get(_val[0]) : + leanPopulateMap.get(_val); + // Populated using lean, `leanPopulateMap` value is the foreign model + const schema = model != null ? model.schema : null; + if (schema != null) { + const ret = search( + parts.slice(p), + schema, + subdoc ? mpath.get(trypath, subdoc) : null, + nestedPath.concat(parts.slice(0, p)) + ); - module.exports = NativeCollection; + if (ret != null) { + ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || + !schema.$isSingleNested; + return ret; + } + } + } + return foundschema; + } + } + // look for arrays + const parts = path.split('.'); + for (let i = 0; i < parts.length; ++i) { + if (parts[i] === '$') { + // Re: gh-5628, because `schema.path()` doesn't take $ into account. + parts[i] = '0'; + } + } + return search(parts, schema, doc, []); +}; - /***/ - }, - /***/ 4766: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ - - const MongooseConnection = __nccwpck_require__(370); - const STATES = __nccwpck_require__(932); - const immediate = __nccwpck_require__(4830); - const setTimeout = __nccwpck_require__(82) /* .setTimeout */.i; - - /** - * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation. - * - * @inherits Connection - * @api private - */ - - function NativeConnection() { - MongooseConnection.apply(this, arguments); - this._listening = false; - } - - /** - * Expose the possible connection states. - * @api public - */ - - NativeConnection.STATES = STATES; - - /*! - * Inherits from Connection. - */ - - NativeConnection.prototype.__proto__ = MongooseConnection.prototype; - - /** - * Switches to a different database using the same connection pool. - * - * Returns a new connection object, with the new db. If you set the `useCache` - * option, `useDb()` will cache connections by `name`. - * - * **Note:** Calling `close()` on a `useDb()` connection will close the base connection as well. - * - * @param {String} name The database name - * @param {Object} [options] - * @param {Boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object. - * @param {Boolean} [options.noListener=false] If true, the new connection object won't listen to any events on the base connection. This is better for memory usage in cases where you're calling `useDb()` for every request. - * @return {Connection} New Connection Object - * @api public - */ - - NativeConnection.prototype.useDb = function (name, options) { - // Return immediately if cached - options = options || {}; - if (options.useCache && this.relatedDbs[name]) { - return this.relatedDbs[name]; - } - - // we have to manually copy all of the attributes... - const newConn = new this.constructor(); - newConn.name = name; - newConn.base = this.base; - newConn.collections = {}; - newConn.models = {}; - newConn.replica = this.replica; - newConn.config = Object.assign({}, this.config, newConn.config); - newConn.name = this.name; - newConn.options = this.options; - newConn._readyState = this._readyState; - newConn._closeCalled = this._closeCalled; - newConn._hasOpened = this._hasOpened; - newConn._listening = false; - - newConn.host = this.host; - newConn.port = this.port; - newConn.user = this.user; - newConn.pass = this.pass; - - // First, when we create another db object, we are not guaranteed to have a - // db object to work with. So, in the case where we have a db object and it - // is connected, we can just proceed with setting everything up. However, if - // we do not have a db or the state is not connected, then we need to wait on - // the 'open' event of the connection before doing the rest of the setup - // the 'connected' event is the first time we'll have access to the db object +/***/ }), - const _this = this; +/***/ 6371: +/***/ ((module) => { - newConn.client = _this.client; +"use strict"; - if (this.db && this._readyState === STATES.connected) { - wireup(); - } else { - this.once("connected", wireup); - } - function wireup() { - newConn.client = _this.client; - const _opts = {}; - if (options.hasOwnProperty("noListener")) { - _opts.noListener = options.noListener; - } - newConn.db = _this.client.db(name, _opts); - newConn.onOpen(); - // setup the events appropriately - if (options.noListener !== true) { - listen(newConn); - } - } +module.exports = getVirtual; - newConn.name = name; +/*! + * ignore + */ - // push onto the otherDbs stack, this is used when state changes - if (options.noListener !== true) { - this.otherDbs.push(newConn); - } - newConn.otherDbs.push(this); +function getVirtual(schema, name) { + if (schema.virtuals[name]) { + return { virtual: schema.virtuals[name], path: void 0 }; + } - // push onto the relatedDbs cache, this is used when state changes - if (options && options.useCache) { - this.relatedDbs[newConn.name] = newConn; - newConn.relatedDbs = this.relatedDbs; - } + const parts = name.split('.'); + let cur = ''; + let nestedSchemaPath = ''; + for (let i = 0; i < parts.length; ++i) { + cur += (cur.length > 0 ? '.' : '') + parts[i]; + if (schema.virtuals[cur]) { + if (i === parts.length - 1) { + return { virtual: schema.virtuals[cur], path: nestedSchemaPath }; + } + continue; + } - return newConn; - }; + if (schema.nested[cur]) { + continue; + } - /*! - * Register listeners for important events and bubble appropriately. - */ + if (schema.paths[cur] && schema.paths[cur].schema) { + schema = schema.paths[cur].schema; + const rest = parts.slice(i + 1).join('.'); - function listen(conn) { - if (conn._listening) { - return; + if (schema.virtuals[rest]) { + if (i === parts.length - 2) { + return { + virtual: schema.virtuals[rest], + nestedSchemaPath: [nestedSchemaPath, cur].filter(v => !!v).join('.') + }; } - conn._listening = true; + continue; + } - conn.client.on("close", function (force) { - if (conn._closeCalled) { - return; - } - conn._closeCalled = conn.client._closeCalled; - - // the driver never emits an `open` event. auto_reconnect still - // emits a `close` event but since we never get another - // `open` we can't emit close - if (conn.db.serverConfig.autoReconnect) { - conn.readyState = STATES.disconnected; - conn.emit("close"); - return; + if (i + 1 < parts.length && schema.discriminators) { + for (const key of Object.keys(schema.discriminators)) { + const res = getVirtual(schema.discriminators[key], rest); + if (res != null) { + const _path = [nestedSchemaPath, cur, res.nestedSchemaPath]. + filter(v => !!v).join('.'); + return { + virtual: res.virtual, + nestedSchemaPath: _path + }; } - conn.onClose(force); - }); - conn.client.on("error", function (err) { - conn.emit("error", err); - }); - - if (!conn.client.s.options.useUnifiedTopology) { - conn.db.on("reconnect", function () { - conn.readyState = STATES.connected; - conn.emit("reconnect"); - conn.emit("reconnected"); - conn.onOpen(); - }); - conn.db.on("open", function (err, db) { - if ( - STATES.disconnected === conn.readyState && - db && - db.databaseName - ) { - conn.readyState = STATES.connected; - conn.emit("reconnect"); - conn.emit("reconnected"); - } - }); } - - conn.client.on("timeout", function (err) { - conn.emit("timeout", err); - }); - conn.client.on("parseError", function (err) { - conn.emit("parseError", err); - }); } - /** - * Closes the connection - * - * @param {Boolean} [force] - * @param {Function} [fn] - * @return {Connection} this - * @api private - */ - - NativeConnection.prototype.doClose = function (force, fn) { - if (this.client == null) { - immediate(() => fn()); - return this; - } - - this.client.close(force, (err, res) => { - // Defer because the driver will wait at least 1ms before finishing closing - // the pool, see https://github.com/mongodb-js/mongodb-core/blob/a8f8e4ce41936babc3b9112bf42d609779f03b39/lib/connection/pool.js#L1026-L1030. - // If there's queued operations, you may still get some background work - // after the callback is called. - setTimeout(() => fn(err, res), 1); - }); - return this; - }; + nestedSchemaPath += (nestedSchemaPath.length > 0 ? '.' : '') + cur; + cur = ''; + continue; + } - /*! - * Module exports. - */ + if (schema.discriminators) { + for (const discriminatorKey of Object.keys(schema.discriminators)) { + const virtualFromDiscriminator = getVirtual(schema.discriminators[discriminatorKey], name); + if (virtualFromDiscriminator) return virtualFromDiscriminator; + } + } - module.exports = NativeConnection; + return null; + } +} - /***/ - }, - /***/ 5869: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * ignore - */ +/***/ }), - module.exports = __nccwpck_require__(5517).Decimal128; +/***/ 914: +/***/ ((module) => { - /***/ - }, +"use strict"; - /***/ 2676: /***/ ( - __unused_webpack_module, - exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module exports. - */ - - exports.Binary = __nccwpck_require__(4473); - exports.Collection = __nccwpck_require__(449); - exports.Decimal128 = __nccwpck_require__(5869); - exports.ObjectId = __nccwpck_require__(3589); - exports.ReadPreference = __nccwpck_require__(8001); - exports.getConnection = () => __nccwpck_require__(4766); - - /***/ - }, - /***/ 3589: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; +/*! + * ignore + */ - /*! - * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId - * @constructor NodeMongoDbObjectId - * @see ObjectId - */ +module.exports = new WeakMap(); - const ObjectId = __nccwpck_require__(5517).ObjectId; +/***/ }), - /*! - * ignore - */ +/***/ 1296: +/***/ ((module) => { - module.exports = exports = ObjectId; +"use strict"; - /***/ - }, - /***/ 2798: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const MongooseError = __nccwpck_require__(5953); - const get = __nccwpck_require__(8730); - const util = __nccwpck_require__(1669); - - /** - * Casting Error constructor. - * - * @param {String} type - * @param {String} value - * @inherits MongooseError - * @api private - */ - - class CastError extends MongooseError { - constructor(type, value, path, reason, schemaType) { - // If no args, assume we'll `init()` later. - if (arguments.length > 0) { - const stringValue = getStringValue(value); - const valueType = getValueType(value); - const messageFormat = getMessageFormat(schemaType); - const msg = formatMessage( - null, - type, - stringValue, - path, - messageFormat, - valueType - ); - super(msg); - this.init(type, value, path, reason, schemaType); - } else { - super(formatMessage()); - } - } +module.exports = function lookupLocalFields(cur, path, val) { + if (cur == null) { + return cur; + } - toJSON() { - return { - stringValue: this.stringValue, - valueType: this.valueType, - kind: this.kind, - value: this.value, - path: this.path, - reason: this.reason, - name: this.name, - message: this.message, - }; - } - /*! - * ignore - */ - init(type, value, path, reason, schemaType) { - this.stringValue = getStringValue(value); - this.messageFormat = getMessageFormat(schemaType); - this.kind = type; - this.value = value; - this.path = path; - this.reason = reason; - this.valueType = getValueType(value); - } - - /*! - * ignore - * @param {Readonly} other - */ - copy(other) { - this.messageFormat = other.messageFormat; - this.stringValue = other.stringValue; - this.kind = other.kind; - this.value = other.value; - this.path = other.path; - this.reason = other.reason; - this.message = other.message; - this.valueType = other.valueType; - } - - /*! - * ignore - */ - setModel(model) { - this.model = model; - this.message = formatMessage( - model, - this.kind, - this.stringValue, - this.path, - this.messageFormat, - this.valueType - ); - } - } + if (cur._doc != null) { + cur = cur._doc; + } - Object.defineProperty(CastError.prototype, "name", { - value: "CastError", - }); + if (arguments.length >= 3) { + if (typeof cur !== 'object') { + return void 0; + } + if (val === void 0) { + return void 0; + } + if (cur instanceof Map) { + cur.set(path, val); + } else { + cur[path] = val; + } + return val; + } - function getStringValue(value) { - let stringValue = util.inspect(value); - stringValue = stringValue.replace(/^'|'$/g, '"'); - if (!stringValue.startsWith('"')) { - stringValue = '"' + stringValue + '"'; - } - return stringValue; - } - function getValueType(value) { - if (value == null) { - return "" + value; - } + // Support populating paths under maps using `map.$*.subpath` + if (path === '$*') { + return cur instanceof Map ? + Array.from(cur.values()) : + Object.keys(cur).map(key => cur[key]); + } - const t = typeof value; - if (t !== "object") { - return t; - } - if (typeof value.constructor !== "function") { - return t; - } - return value.constructor.name; - } + if (cur instanceof Map) { + return cur.get(path); + } - function getMessageFormat(schemaType) { - const messageFormat = get(schemaType, "options.cast", null); - if (typeof messageFormat === "string") { - return messageFormat; - } - } + return cur[path]; +}; - /*! - * ignore - */ +/***/ }), - function formatMessage( - model, - kind, - stringValue, - path, - messageFormat, - valueType - ) { - if (messageFormat != null) { - let ret = messageFormat - .replace("{KIND}", kind) - .replace("{VALUE}", stringValue) - .replace("{PATH}", path); - if (model != null) { - ret = ret.replace("{MODEL}", model.modelName); - } +/***/ 3515: +/***/ ((module) => { - return ret; - } else { - const valueTypeMsg = valueType ? " (type " + valueType + ")" : ""; - let ret = - "Cast to " + - kind + - " failed for value " + - stringValue + - valueTypeMsg + - ' at path "' + - path + - '"'; - if (model != null) { - ret += ' for model "' + model.modelName + '"'; - } - return ret; - } - } +"use strict"; - /*! - * exports - */ - module.exports = CastError; +/*! + * If populating a path within a document array, make sure each + * subdoc within the array knows its subpaths are populated. + * + * ####Example: + * const doc = await Article.findOne().populate('comments.author'); + * doc.comments[0].populated('author'); // Should be set + */ - /***/ - }, +module.exports = function markArraySubdocsPopulated(doc, populated) { + if (doc._id == null || populated == null || populated.length === 0) { + return; + } - /***/ 8912: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + const id = String(doc._id); + for (const item of populated) { + if (item.isVirtual) { + continue; + } + const path = item.path; + const pieces = path.split('.'); + for (let i = 0; i < pieces.length - 1; ++i) { + const subpath = pieces.slice(0, i + 1).join('.'); + const rest = pieces.slice(i + 1).join('.'); + const val = doc.get(subpath); + if (val == null) { + continue; + } - /*! - * Module dependencies. - */ + if (val.isMongooseDocumentArray) { + for (let j = 0; j < val.length; ++j) { + val[j].populated(rest, item._docs[id] == null ? void 0 : item._docs[id][j], item); + } + break; + } + } + } +}; - const MongooseError = __nccwpck_require__(4327); +/***/ }), - class DivergentArrayError extends MongooseError { - /*! - * DivergentArrayError constructor. - * @param {Array} paths - */ - constructor(paths) { - const msg = - "For your own good, using `document.save()` to update an array " + - "which was selected using an $elemMatch projection OR " + - "populated using skip, limit, query conditions, or exclusion of " + - "the _id field when the operation results in a $pop or $set of " + - "the entire array is not supported. The following " + - "path(s) would have been modified unsafely:\n" + - " " + - paths.join("\n ") + - "\n" + - "Use Model.update() to update these arrays instead."; - // TODO write up a docs page (FAQ) and link to it - super(msg); - } - } - - Object.defineProperty(DivergentArrayError.prototype, "name", { - value: "DivergentArrayError", - }); +/***/ 76: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /*! - * exports - */ +"use strict"; - module.exports = DivergentArrayError; - /***/ - }, +const MongooseError = __nccwpck_require__(5953); +const isPathExcluded = __nccwpck_require__(1126); +const lookupLocalFields = __nccwpck_require__(1296); +const mpath = __nccwpck_require__(8586); +const util = __nccwpck_require__(1669); +const utils = __nccwpck_require__(9232); - /***/ 4327: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; - - /** - * MongooseError constructor. MongooseError is the base class for all - * Mongoose-specific errors. - * - * ####Example: - * const Model = mongoose.model('Test', new Schema({ answer: Number })); - * const doc = new Model({ answer: 'not a number' }); - * const err = doc.validateSync(); - * - * err instanceof mongoose.Error; // true - * - * @constructor Error - * @param {String} msg Error message - * @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error - */ - - const MongooseError = __nccwpck_require__(5953); - - /** - * The name of the error. The name uniquely identifies this Mongoose error. The - * possible values are: - * - * - `MongooseError`: general Mongoose error - * - `CastError`: Mongoose could not convert a value to the type defined in the schema path. May be in a `ValidationError` class' `errors` property. - * - `DisconnectedError`: This [connection](connections.html) timed out in trying to reconnect to MongoDB and will not successfully reconnect to MongoDB unless you explicitly reconnect. - * - `DivergentArrayError`: You attempted to `save()` an array that was modified after you loaded it with a `$elemMatch` or similar projection - * - `MissingSchemaError`: You tried to access a model with [`mongoose.model()`](api.html#mongoose_Mongoose-model) that was not defined - * - `DocumentNotFoundError`: The document you tried to [`save()`](api.html#document_Document-save) was not found - * - `ValidatorError`: error from an individual schema path's validator - * - `ValidationError`: error returned from [`validate()`](api.html#document_Document-validate) or [`validateSync()`](api.html#document_Document-validateSync). Contains zero or more `ValidatorError` instances in `.errors` property. - * - `MissingSchemaError`: You called `mongoose.Document()` without a schema - * - `ObjectExpectedError`: Thrown when you set a nested path to a non-object value with [strict mode set](guide.html#strict). - * - `ObjectParameterError`: Thrown when you pass a non-object value to a function which expects an object as a paramter - * - `OverwriteModelError`: Thrown when you call [`mongoose.model()`](api.html#mongoose_Mongoose-model) to re-define a model that was already defined. - * - `ParallelSaveError`: Thrown when you call [`save()`](api.html#model_Model-save) on a document when the same document instance is already saving. - * - `StrictModeError`: Thrown when you set a path that isn't the schema and [strict mode](guide.html#strict) is set to `throw`. - * - `VersionError`: Thrown when the [document is out of sync](guide.html#versionKey) - * - * @api public - * @property {String} name - * @memberOf Error - * @instance - */ - - /*! - * Module exports. - */ - - module.exports = exports = MongooseError; - - /** - * The default built-in validator error messages. - * - * @see Error.messages #error_messages_MongooseError-messages - * @api public - * @memberOf Error - * @static messages - */ - - MongooseError.messages = __nccwpck_require__(8657); - - // backward compat - MongooseError.Messages = MongooseError.messages; - - /** - * An instance of this error class will be returned when `save()` fails - * because the underlying - * document was not found. The constructor takes one parameter, the - * conditions that mongoose passed to `update()` when trying to update - * the document. - * - * @api public - * @memberOf Error - * @static DocumentNotFoundError - */ - - MongooseError.DocumentNotFoundError = __nccwpck_require__(5147); - - /** - * An instance of this error class will be returned when mongoose failed to - * cast a value. - * - * @api public - * @memberOf Error - * @static CastError - */ - - MongooseError.CastError = __nccwpck_require__(2798); - - /** - * An instance of this error class will be returned when [validation](/docs/validation.html) failed. - * The `errors` property contains an object whose keys are the paths that failed and whose values are - * instances of CastError or ValidationError. - * - * @api public - * @memberOf Error - * @static ValidationError - */ - - MongooseError.ValidationError = __nccwpck_require__(8460); - - /** - * A `ValidationError` has a hash of `errors` that contain individual - * `ValidatorError` instances. - * - * ####Example: - * - * const schema = Schema({ name: { type: String, required: true } }); - * const Model = mongoose.model('Test', schema); - * const doc = new Model({}); - * - * // Top-level error is a ValidationError, **not** a ValidatorError - * const err = doc.validateSync(); - * err instanceof mongoose.Error.ValidationError; // true - * - * // A ValidationError `err` has 0 or more ValidatorErrors keyed by the - * // path in the `err.errors` property. - * err.errors['name'] instanceof mongoose.Error.ValidatorError; - * - * err.errors['name'].kind; // 'required' - * err.errors['name'].path; // 'name' - * err.errors['name'].value; // undefined - * - * Instances of `ValidatorError` have the following properties: - * - * - `kind`: The validator's `type`, like `'required'` or `'regexp'` - * - `path`: The path that failed validation - * - `value`: The value that failed validation - * - * @api public - * @memberOf Error - * @static ValidatorError - */ - - MongooseError.ValidatorError = __nccwpck_require__(6345); - - /** - * An instance of this error class will be returned when you call `save()` after - * the document in the database was changed in a potentially unsafe way. See - * the [`versionKey` option](/docs/guide.html#versionKey) for more information. - * - * @api public - * @memberOf Error - * @static VersionError - */ - - MongooseError.VersionError = __nccwpck_require__(4305); - - /** - * An instance of this error class will be returned when you call `save()` multiple - * times on the same document in parallel. See the [FAQ](/docs/faq.html) for more - * information. - * - * @api public - * @memberOf Error - * @static ParallelSaveError - */ - - MongooseError.ParallelSaveError = __nccwpck_require__(618); - - /** - * Thrown when a model with the given name was already registered on the connection. - * See [the FAQ about `OverwriteModelError`](/docs/faq.html#overwrite-model-error). - * - * @api public - * @memberOf Error - * @static OverwriteModelError - */ - - MongooseError.OverwriteModelError = __nccwpck_require__(970); - - /** - * Thrown when you try to access a model that has not been registered yet - * - * @api public - * @memberOf Error - * @static MissingSchemaError - */ - - MongooseError.MissingSchemaError = __nccwpck_require__(2860); - - /** - * An instance of this error will be returned if you used an array projection - * and then modified the array in an unsafe way. - * - * @api public - * @memberOf Error - * @static DivergentArrayError - */ - - MongooseError.DivergentArrayError = __nccwpck_require__(8912); - - /** - * Thrown when your try to pass values to model contrtuctor that - * were not specified in schema or change immutable properties when - * `strict` mode is `"throw"` - * - * @api public - * @memberOf Error - * @static StrictModeError - */ - - MongooseError.StrictModeError = __nccwpck_require__(703); - - /***/ - }, +module.exports = function modelNamesFromRefPath(refPath, doc, populatedPath, modelSchema, queryProjection) { + if (refPath == null) { + return []; + } - /***/ 8657: /***/ (module, exports) => { - "use strict"; - - /** - * The default built-in validator error messages. These may be customized. - * - * // customize within each schema or globally like so - * const mongoose = require('mongoose'); - * mongoose.Error.messages.String.enum = "Your custom message for {PATH}."; - * - * As you might have noticed, error messages support basic templating - * - * - `{PATH}` is replaced with the invalid document path - * - `{VALUE}` is replaced with the invalid value - * - `{TYPE}` is replaced with the validator type such as "regexp", "min", or "user defined" - * - `{MIN}` is replaced with the declared min value for the Number.min validator - * - `{MAX}` is replaced with the declared max value for the Number.max validator - * - * Click the "show code" link below to see all defaults. - * - * @static messages - * @receiver MongooseError - * @api public - */ - - const msg = (module.exports = exports = {}); - - msg.DocumentNotFoundError = null; - - msg.general = {}; - msg.general.default = - "Validator failed for path `{PATH}` with value `{VALUE}`"; - msg.general.required = "Path `{PATH}` is required."; - - msg.Number = {}; - msg.Number.min = - "Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN})."; - msg.Number.max = - "Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX})."; - msg.Number.enum = - "`{VALUE}` is not a valid enum value for path `{PATH}`."; - - msg.Date = {}; - msg.Date.min = - "Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN})."; - msg.Date.max = - "Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX})."; - - msg.String = {}; - msg.String.enum = - "`{VALUE}` is not a valid enum value for path `{PATH}`."; - msg.String.match = "Path `{PATH}` is invalid ({VALUE})."; - msg.String.minlength = - "Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH})."; - msg.String.maxlength = - "Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH})."; - - /***/ - }, + if (typeof refPath === 'string' && queryProjection != null && isPathExcluded(queryProjection, refPath)) { + throw new MongooseError('refPath `' + refPath + '` must not be excluded in projection, got ' + + util.inspect(queryProjection)); + } - /***/ 2860: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + // If populated path has numerics, the end `refPath` should too. For example, + // if populating `a.0.b` instead of `a.b` and `b` has `refPath = a.c`, we + // should return `a.0.c` for the refPath. + const hasNumericProp = /(\.\d+$|\.\d+\.)/g; - /*! - * Module dependencies. - */ + if (hasNumericProp.test(populatedPath)) { + const chunks = populatedPath.split(hasNumericProp); - const MongooseError = __nccwpck_require__(4327); + if (chunks[chunks.length - 1] === '') { + throw new Error('Can\'t populate individual element in an array'); + } - class MissingSchemaError extends MongooseError { - /*! - * MissingSchema Error constructor. - * @param {String} name - */ - constructor(name) { - const msg = - "Schema hasn't been registered for model \"" + - name + - '".\n' + - "Use mongoose.model(name, schema)"; - super(msg); - } + let _refPath = ''; + let _remaining = refPath; + // 2nd, 4th, etc. will be numeric props. For example: `[ 'a', '.0.', 'b' ]` + for (let i = 0; i < chunks.length; i += 2) { + const chunk = chunks[i]; + if (_remaining.startsWith(chunk + '.')) { + _refPath += _remaining.substr(0, chunk.length) + chunks[i + 1]; + _remaining = _remaining.substr(chunk.length + 1); + } else if (i === chunks.length - 1) { + _refPath += _remaining; + _remaining = ''; + break; + } else { + throw new Error('Could not normalize ref path, chunk ' + chunk + ' not in populated path'); } + } - Object.defineProperty(MissingSchemaError.prototype, "name", { - value: "MissingSchemaError", - }); - - /*! - * exports - */ - - module.exports = MissingSchemaError; + const refValue = mpath.get(_refPath, doc, lookupLocalFields); + let modelNames = Array.isArray(refValue) ? refValue : [refValue]; + modelNames = utils.array.flatten(modelNames); + return modelNames; + } - /***/ - }, + const refValue = mpath.get(refPath, doc, lookupLocalFields); - /***/ 5953: /***/ (module) => { - "use strict"; + let modelNames; + if (modelSchema != null && modelSchema.virtuals.hasOwnProperty(refPath)) { + modelNames = [modelSchema.virtuals[refPath].applyGetters(void 0, doc)]; + } else { + modelNames = Array.isArray(refValue) ? refValue : [refValue]; + } - /*! - * ignore - */ + modelNames = utils.array.flatten(modelNames); - class MongooseError extends Error {} + return modelNames; +}; - Object.defineProperty(MongooseError.prototype, "name", { - value: "MongooseError", - }); +/***/ }), - module.exports = MongooseError; +/***/ 6962: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /***/ - }, +"use strict"; - /***/ 5147: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ +const get = __nccwpck_require__(8730); +const mpath = __nccwpck_require__(8586); +const parseProjection = __nccwpck_require__(7201); - const MongooseError = __nccwpck_require__(4327); - const util = __nccwpck_require__(1669); +/*! + * ignore + */ - class DocumentNotFoundError extends MongooseError { - /*! - * OverwriteModel Error constructor. - */ - constructor(filter, model, numAffected, result) { - let msg; - const messages = MongooseError.messages; - if (messages.DocumentNotFoundError != null) { - msg = - typeof messages.DocumentNotFoundError === "function" - ? messages.DocumentNotFoundError(filter, model) - : messages.DocumentNotFoundError; - } else { - msg = - 'No document found for query "' + - util.inspect(filter) + - '" on model "' + - model + - '"'; - } +module.exports = function removeDeselectedForeignField(foreignFields, options, docs) { + const projection = parseProjection(get(options, 'select', null), true) || + parseProjection(get(options, 'options.select', null), true); - super(msg); + if (projection == null) { + return; + } + for (const foreignField of foreignFields) { + if (!projection.hasOwnProperty('-' + foreignField)) { + continue; + } - this.result = result; - this.numAffected = numAffected; - this.filter = filter; - // Backwards compat - this.query = filter; - } + for (const val of docs) { + if (val.$__ != null) { + mpath.unset(foreignField, val._doc); + } else { + mpath.unset(foreignField, val); } + } + } +}; - Object.defineProperty(DocumentNotFoundError.prototype, "name", { - value: "DocumentNotFoundError", - }); +/***/ }), - /*! - * exports - */ +/***/ 5458: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - module.exports = DocumentNotFoundError; +"use strict"; - /***/ - }, - /***/ 2293: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ +const MongooseError = __nccwpck_require__(5953); +const util = __nccwpck_require__(1669); - const MongooseError = __nccwpck_require__(4327); +module.exports = validateRef; - class ObjectExpectedError extends MongooseError { - /** - * Strict mode error constructor - * - * @param {string} type - * @param {string} value - * @api private - */ - constructor(path, val) { - const typeDescription = Array.isArray(val) - ? "array" - : "primitive value"; - super( - "Tried to set nested object field `" + - path + - `\` to ${typeDescription} \`` + - val + - "` and strict mode is set to throw." - ); - this.path = path; - } - } +function validateRef(ref, path) { + if (typeof ref === 'string') { + return; + } - Object.defineProperty(ObjectExpectedError.prototype, "name", { - value: "ObjectExpectedError", - }); + if (typeof ref === 'function') { + return; + } - module.exports = ObjectExpectedError; + throw new MongooseError('Invalid ref at path "' + path + '". Got ' + + util.inspect(ref, { depth: 0 })); +} - /***/ - }, +/***/ }), - /***/ 3456: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ +/***/ 2312: +/***/ ((__unused_webpack_module, __unused_webpack_exports, __nccwpck_require__) => { - const MongooseError = __nccwpck_require__(4327); +"use strict"; - class ObjectParameterError extends MongooseError { - /** - * Constructor for errors that happen when a parameter that's expected to be - * an object isn't an object - * - * @param {Any} value - * @param {String} paramName - * @param {String} fnName - * @api private - */ - constructor(value, paramName, fnName) { - super( - 'Parameter "' + - paramName + - '" to ' + - fnName + - "() must be an object, got " + - value.toString() - ); - } - } - Object.defineProperty(ObjectParameterError.prototype, "name", { - value: "ObjectParameterError", - }); +const utils = __nccwpck_require__(9232); - module.exports = ObjectParameterError; +if (typeof jest !== 'undefined' && typeof window !== 'undefined') { + utils.warn('Mongoose: looks like you\'re trying to test a Mongoose app ' + + 'with Jest\'s default jsdom test environment. Please make sure you read ' + + 'Mongoose\'s docs on configuring Jest to test Node.js apps: ' + + 'http://mongoosejs.com/docs/jest.html'); +} - /***/ - }, +if (typeof jest !== 'undefined' && process.nextTick.toString().indexOf('nextTick') === -1) { + utils.warn('Mongoose: looks like you\'re trying to test a Mongoose app ' + + 'with Jest\'s mock timers enabled. Please make sure you read ' + + 'Mongoose\'s docs on configuring Jest to test Node.js apps: ' + + 'http://mongoosejs.com/docs/jest.html'); +} - /***/ 970: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +/***/ }), - /*! - * Module dependencies. - */ +/***/ 2448: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const MongooseError = __nccwpck_require__(4327); +"use strict"; - class OverwriteModelError extends MongooseError { - /*! - * OverwriteModel Error constructor. - * @param {String} name - */ - constructor(name) { - super("Cannot overwrite `" + name + "` model once compiled."); - } - } - Object.defineProperty(OverwriteModelError.prototype, "name", { - value: "OverwriteModelError", - }); +const clone = __nccwpck_require__(5092); +const MongooseError = __nccwpck_require__(4327); - /*! - * exports - */ +function processConnectionOptions(uri, options) { + const opts = options ? options : {}; + const readPreference = opts.readPreference + ? opts.readPreference + : getUriReadPreference(uri); - module.exports = OverwriteModelError; + const resolvedOpts = (readPreference && readPreference !== 'primary') + ? resolveOptsConflicts(readPreference, opts) + : opts; - /***/ - }, + return clone(resolvedOpts); +} - /***/ 618: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +function resolveOptsConflicts(pref, opts) { + // don't silently override user-provided indexing options + if (setsIndexOptions(opts) && setsSecondaryRead(pref)) { + throwReadPreferenceError(); + } - /*! - * Module dependencies. - */ + // if user has not explicitly set any auto-indexing options, + // we can silently default them all to false + else { + return defaultIndexOptsToFalse(opts); + } +} - const MongooseError = __nccwpck_require__(4327); +function setsIndexOptions(opts) { + const configIdx = opts.config && opts.config.autoIndex; + const { autoCreate, autoIndex } = opts; + return !!(configIdx || autoCreate || autoIndex); +} - class ParallelSaveError extends MongooseError { - /** - * ParallelSave Error constructor. - * - * @param {Document} doc - * @api private - */ - constructor(doc) { - const msg = - "Can't save() the same doc multiple times in parallel. Document: "; - super(msg + doc._id); - } - } +function setsSecondaryRead(prefString) { + return !!(prefString === 'secondary' || prefString === 'secondaryPreferred'); +} - Object.defineProperty(ParallelSaveError.prototype, "name", { - value: "ParallelSaveError", - }); +function getUriReadPreference(connectionString) { + const exp = /(?:&|\?)readPreference=(\w+)(?:&|$)/; + const match = exp.exec(connectionString); + return match ? match[1] : null; +} - /*! - * exports - */ +function defaultIndexOptsToFalse(opts) { + opts.config = { autoIndex: false }; + opts.autoCreate = false; + opts.autoIndex = false; + return opts; +} - module.exports = ParallelSaveError; +function throwReadPreferenceError() { + throw new MongooseError( + 'MongoDB prohibits index creation on connections that read from ' + + 'non-primary replicas. Connections that set "readPreference" to "secondary" or ' + + '"secondaryPreferred" may not opt-in to the following connection options: ' + + 'autoCreate, autoIndex' + ); +} - /***/ - }, +module.exports = processConnectionOptions; - /***/ 3897: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ +/***/ }), - const MongooseError = __nccwpck_require__(5953); +/***/ 1903: +/***/ ((module) => { - class ParallelValidateError extends MongooseError { - /** - * ParallelValidate Error constructor. - * - * @param {Document} doc - * @api private - */ - constructor(doc) { - const msg = - "Can't validate() the same doc multiple times in parallel. Document: "; - super(msg + doc._id); - } - } +"use strict"; - Object.defineProperty(ParallelValidateError.prototype, "name", { - value: "ParallelValidateError", - }); - /*! - * exports - */ +/*! + * ignore + */ - module.exports = ParallelValidateError; +module.exports = function isDefiningProjection(val) { + if (val == null) { + // `undefined` or `null` become exclusive projections + return true; + } + if (typeof val === 'object') { + // Only cases where a value does **not** define whether the whole projection + // is inclusive or exclusive are `$meta` and `$slice`. + return !('$meta' in val) && !('$slice' in val); + } + return true; +}; - /***/ - }, - /***/ 3070: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ - - const MongooseError = __nccwpck_require__(5953); - const allServersUnknown = __nccwpck_require__(8571); - const isAtlas = __nccwpck_require__(7352); - const isSSLError = __nccwpck_require__(5437); - - /*! - * ignore - */ - - const atlasMessage = - "Could not connect to any servers in your MongoDB Atlas cluster. " + - "One common reason is that you're trying to access the database from " + - "an IP that isn't whitelisted. Make sure your current IP address is on your Atlas " + - "cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/"; - - const sslMessage = - "Mongoose is connecting with SSL enabled, but the server is " + - "not accepting SSL connections. Please ensure that the MongoDB server you are " + - "connecting to is configured to accept SSL connections. Learn more: " + - "https://mongoosejs.com/docs/tutorials/ssl.html"; - - class MongooseServerSelectionError extends MongooseError { - /** - * MongooseServerSelectionError constructor - * - * @api private - */ - assimilateError(err) { - const reason = err.reason; - // Special message for a case that is likely due to IP whitelisting issues. - const isAtlasWhitelistError = - isAtlas(reason) && - allServersUnknown(reason) && - err.message.indexOf("bad auth") === -1 && - err.message.indexOf("Authentication failed") === -1; - - if (isAtlasWhitelistError) { - this.message = atlasMessage; - } else if (isSSLError(reason)) { - this.message = sslMessage; - } else { - this.message = err.message; - } - for (const key in err) { - if (key !== "name") { - this[key] = err[key]; - } - } +/***/ }), - return this; - } - } +/***/ 3522: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Object.defineProperty(MongooseServerSelectionError.prototype, "name", { - value: "MongooseServerSelectionError", - }); +"use strict"; - module.exports = MongooseServerSelectionError; - /***/ - }, +const isDefiningProjection = __nccwpck_require__(1903); - /***/ 703: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ +/*! + * ignore + */ - const MongooseError = __nccwpck_require__(4327); +module.exports = function isExclusive(projection) { + if (projection == null) { + return null; + } - class StrictModeError extends MongooseError { - /** - * Strict mode error constructor - * - * @param {String} path - * @param {String} [msg] - * @param {Boolean} [immutable] - * @inherits MongooseError - * @api private - */ - constructor(path, msg, immutable) { - msg = - msg || - "Field `" + - path + - "` is not in schema and strict " + - "mode is set to throw."; - super(msg); - this.isImmutableError = !!immutable; - this.path = path; - } + const keys = Object.keys(projection); + let ki = keys.length; + let exclude = null; + + if (ki === 1 && keys[0] === '_id') { + exclude = !projection._id; + } else { + while (ki--) { + // Does this projection explicitly define inclusion/exclusion? + // Explicitly avoid `$meta` and `$slice` + if (keys[ki] !== '_id' && isDefiningProjection(projection[keys[ki]])) { + exclude = !projection[keys[ki]]; + break; } + } + } - Object.defineProperty(StrictModeError.prototype, "name", { - value: "StrictModeError", - }); + return exclude; +}; - module.exports = StrictModeError; - /***/ - }, +/***/ }), - /***/ 8460: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module requirements - */ - - const MongooseError = __nccwpck_require__(5953); - const getConstructorName = __nccwpck_require__(7323); - const util = __nccwpck_require__(1669); - - class ValidationError extends MongooseError { - /** - * Document Validation Error - * - * @api private - * @param {Document} [instance] - * @inherits MongooseError - */ - constructor(instance) { - let _message; - if (getConstructorName(instance) === "model") { - _message = instance.constructor.modelName + " validation failed"; - } else { - _message = "Validation failed"; - } +/***/ 2951: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - super(_message); +"use strict"; - this.errors = {}; - this._message = _message; - if (instance) { - instance.errors = this.errors; - } - } +const isDefiningProjection = __nccwpck_require__(1903); - /** - * Console.log helper - */ - toString() { - return this.name + ": " + _generateMessage(this); - } +/*! + * ignore + */ - /*! - * inspect helper - */ - inspect() { - return Object.assign(new Error(this.message), this); - } +module.exports = function isInclusive(projection) { + if (projection == null) { + return false; + } - /*! - * add message - */ - addError(path, error) { - this.errors[path] = error; - this.message = this._message + ": " + _generateMessage(this); - } - } + const props = Object.keys(projection); + const numProps = props.length; + if (numProps === 0) { + return false; + } - if (util.inspect.custom) { - /*! - * Avoid Node deprecation warning DEP0079 - */ + for (let i = 0; i < numProps; ++i) { + const prop = props[i]; + // Plus paths can't define the projection (see gh-7050) + if (prop.startsWith('+')) { + continue; + } + // If field is truthy (1, true, etc.) and not an object, then this + // projection must be inclusive. If object, assume its $meta, $slice, etc. + if (isDefiningProjection(projection[prop]) && !!projection[prop]) { + return true; + } + } - ValidationError.prototype[util.inspect.custom] = - ValidationError.prototype.inspect; - } + return false; +}; - /*! - * Helper for JSON.stringify - * Ensure `name` and `message` show up in toJSON output re: gh-9847 - */ - Object.defineProperty(ValidationError.prototype, "toJSON", { - enumerable: false, - writable: false, - configurable: true, - value: function () { - return Object.assign({}, this, { - name: this.name, - message: this.message, - }); - }, - }); - Object.defineProperty(ValidationError.prototype, "name", { - value: "ValidationError", - }); +/***/ }), - /*! - * ignore - */ +/***/ 1126: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function _generateMessage(err) { - const keys = Object.keys(err.errors || {}); - const len = keys.length; - const msgs = []; - let key; +"use strict"; - for (let i = 0; i < len; ++i) { - key = keys[i]; - if (err === err.errors[key]) { - continue; - } - msgs.push(key + ": " + err.errors[key].message); - } - return msgs.join(", "); - } +const isDefiningProjection = __nccwpck_require__(1903); + +/*! + * Determines if `path` is excluded by `projection` + * + * @param {Object} projection + * @param {string} path + * @return {Boolean} + */ - /*! - * Module exports - */ +module.exports = function isPathExcluded(projection, path) { + if (path === '_id') { + return projection._id === 0; + } - module.exports = ValidationError; + const paths = Object.keys(projection); + let type = null; - /***/ - }, + for (const _path of paths) { + if (isDefiningProjection(projection[_path])) { + type = projection[path] === 1 ? 'inclusive' : 'exclusive'; + break; + } + } - /***/ 6345: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ + if (type === 'inclusive') { + return projection[path] !== 1; + } + if (type === 'exclusive') { + return projection[path] === 0; + } + return false; +}; - const MongooseError = __nccwpck_require__(4327); - class ValidatorError extends MongooseError { - /** - * Schema validator error - * - * @param {Object} properties - * @api private - */ - constructor(properties) { - let msg = properties.message; - if (!msg) { - msg = MongooseError.messages.general.default; - } +/***/ }), - const message = formatMessage(msg, properties); - super(message); +/***/ 2000: +/***/ ((module) => { - properties = Object.assign({}, properties, { message: message }); - this.properties = properties; - this.kind = properties.type; - this.path = properties.path; - this.value = properties.value; - this.reason = properties.reason; - } +"use strict"; - /*! - * toString helper - * TODO remove? This defaults to `${this.name}: ${this.message}` - */ - toString() { - return this.message; - } - /*! - * Ensure `name` and `message` show up in toJSON output re: gh-9296 - */ +/*! + * ignore + */ - toJSON() { - return Object.assign( - { name: this.name, message: this.message }, - this - ); +module.exports = function isPathSelectedInclusive(fields, path) { + const chunks = path.split('.'); + let cur = ''; + let j; + let keys; + let numKeys; + for (let i = 0; i < chunks.length; ++i) { + cur += cur.length ? '.' : '' + chunks[i]; + if (fields[cur]) { + keys = Object.keys(fields); + numKeys = keys.length; + for (j = 0; j < numKeys; ++j) { + if (keys[i].indexOf(cur + '.') === 0 && keys[i].indexOf(path) !== 0) { + continue; } } + return true; + } + } - Object.defineProperty(ValidatorError.prototype, "name", { - value: "ValidatorError", - }); + return false; +}; - /*! - * The object used to define this validator. Not enumerable to hide - * it from `require('util').inspect()` output re: gh-3925 - */ - Object.defineProperty(ValidatorError.prototype, "properties", { - enumerable: false, - writable: true, - value: null, - }); +/***/ }), - // Exposed for testing - ValidatorError.prototype.formatMessage = formatMessage; +/***/ 8578: +/***/ ((module) => { - /*! - * Formats error messages - */ +"use strict"; - function formatMessage(msg, properties) { - if (typeof msg === "function") { - return msg(properties); - } - const propertyNames = Object.keys(properties); - for (const propertyName of propertyNames) { - if (propertyName === "message") { - continue; - } - msg = msg.replace( - "{" + propertyName.toUpperCase() + "}", - properties[propertyName] - ); - } +/*! + * Determines if `path2` is a subpath of or equal to `path1` + * + * @param {string} path1 + * @param {string} path2 + * @return {Boolean} + */ - return msg; - } +module.exports = function isSubpath(path1, path2) { + return path1 === path2 || path2.startsWith(path1 + '.'); +}; - /*! - * exports - */ - module.exports = ValidatorError; +/***/ }), - /***/ - }, +/***/ 7201: +/***/ ((module) => { - /***/ 4305: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +"use strict"; - /*! - * Module dependencies. - */ - const MongooseError = __nccwpck_require__(4327); +/** + * Convert a string or array into a projection object, retaining all + * `-` and `+` paths. + */ - class VersionError extends MongooseError { - /** - * Version Error constructor. - * - * @param {Document} doc - * @param {Number} currentVersion - * @param {Array} modifiedPaths - * @api private - */ - constructor(doc, currentVersion, modifiedPaths) { - const modifiedPathsStr = modifiedPaths.join(", "); - super( - 'No matching document found for id "' + - doc._id + - '" version ' + - currentVersion + - ' modifiedPaths "' + - modifiedPathsStr + - '"' - ); - this.version = currentVersion; - this.modifiedPaths = modifiedPaths; - } - } +module.exports = function parseProjection(v, retainMinusPaths) { + const type = typeof v; - Object.defineProperty(VersionError.prototype, "name", { - value: "VersionError", - }); + if (type === 'string') { + v = v.split(/\s+/); + } + if (!Array.isArray(v) && Object.prototype.toString.call(v) !== '[object Arguments]') { + return v; + } - /*! - * exports - */ + const len = v.length; + const ret = {}; + for (let i = 0; i < len; ++i) { + let field = v[i]; + if (!field) { + continue; + } + const include = '-' == field[0] ? 0 : 1; + if (!retainMinusPaths && include === 0) { + field = field.substring(1); + } + ret[field] = include; + } - module.exports = VersionError; + return ret; +}; - /***/ - }, +/***/ }), - /***/ 6819: /***/ (module) => { - "use strict"; +/***/ 4046: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - module.exports = function stringifyFunctionOperators(pipeline) { - if (!Array.isArray(pipeline)) { - return; - } +"use strict"; - for (const stage of pipeline) { - if (stage == null) { - continue; - } - const canHaveAccumulator = - stage.$group || stage.$bucket || stage.$bucketAuto; - if (canHaveAccumulator != null) { - for (const key of Object.keys(canHaveAccumulator)) { - handleAccumulator(canHaveAccumulator[key]); - } - } +const PromiseProvider = __nccwpck_require__(5176); +const immediate = __nccwpck_require__(4830); - const stageType = Object.keys(stage)[0]; - if (stageType && typeof stage[stageType] === "object") { - const stageOptions = stage[stageType]; - for (const key of Object.keys(stageOptions)) { - if ( - stageOptions[key] != null && - stageOptions[key].$function != null && - typeof stageOptions[key].$function.body === "function" - ) { - stageOptions[key].$function.body = - stageOptions[key].$function.body.toString(); - } - } - } +const emittedSymbol = Symbol('mongoose:emitted'); - if (stage.$facet != null) { - for (const key of Object.keys(stage.$facet)) { - stringifyFunctionOperators(stage.$facet[key]); - } - } +module.exports = function promiseOrCallback(callback, fn, ee, Promise) { + if (typeof callback === 'function') { + return fn(function(error) { + if (error != null) { + if (ee != null && ee.listeners != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) { + error[emittedSymbol] = true; + ee.emit('error', error); } - }; - - function handleAccumulator(operator) { - if (operator == null || operator.$accumulator == null) { - return; + try { + callback(error); + } catch (error) { + return immediate(() => { + throw error; + }); } + return; + } + callback.apply(this, arguments); + }); + } - for (const key of ["init", "accumulate", "merge", "finalize"]) { - if (typeof operator.$accumulator[key] === "function") { - operator.$accumulator[key] = String(operator.$accumulator[key]); - } + Promise = Promise || PromiseProvider.get(); + + return new Promise((resolve, reject) => { + fn(function(error, res) { + if (error != null) { + if (ee != null && ee.listeners != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) { + error[emittedSymbol] = true; + ee.emit('error', error); } + return reject(error); + } + if (arguments.length > 2) { + return resolve(Array.prototype.slice.call(arguments, 1)); } + resolve(res); + }); + }); +}; - /***/ - }, - /***/ 8906: /***/ (module) => { - "use strict"; +/***/ }), - module.exports = arrayDepth; +/***/ 7428: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function arrayDepth(arr) { - if (!Array.isArray(arr)) { - return { min: 0, max: 0, containsNonArrayItem: true }; - } - if (arr.length === 0) { - return { min: 1, max: 1, containsNonArrayItem: false }; - } - if (arr.length === 1 && !Array.isArray(arr[0])) { - return { min: 1, max: 1, containsNonArrayItem: false }; - } +"use strict"; - const res = arrayDepth(arr[0]); - for (let i = 1; i < arr.length; ++i) { - const _res = arrayDepth(arr[i]); - if (_res.min < res.min) { - res.min = _res.min; - } - if (_res.max > res.max) { - res.max = _res.max; - } - res.containsNonArrayItem = - res.containsNonArrayItem || _res.containsNonArrayItem; - } +const utils = __nccwpck_require__(9232); - res.min = res.min + 1; - res.max = res.max + 1; +module.exports = function applyGlobalMaxTimeMS(options, model) { + if (utils.hasUserDefinedProperty(options, 'maxTimeMS')) { + return; + } - return res; - } + if (utils.hasUserDefinedProperty(model.db.options, 'maxTimeMS')) { + options.maxTimeMS = model.db.options.maxTimeMS; + } else if (utils.hasUserDefinedProperty(model.base.options, 'maxTimeMS')) { + options.maxTimeMS = model.base.options.maxTimeMS; + } +}; - /***/ - }, +/***/ }), - /***/ 5092: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const cloneRegExp = __nccwpck_require__(8292); - const Decimal = __nccwpck_require__(8319); - const ObjectId = __nccwpck_require__(2706); - const specialProperties = __nccwpck_require__(6786); - const isMongooseObject = __nccwpck_require__(7104); - const getFunctionName = __nccwpck_require__(6621); - const isBsonType = __nccwpck_require__(1238); - const isObject = __nccwpck_require__(273); - const symbols = __nccwpck_require__(3240); - const utils = __nccwpck_require__(9232); - - /*! - * Object clone with Mongoose natives support. - * - * If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible. - * - * Functions are never cloned. - * - * @param {Object} obj the object to clone - * @param {Object} options - * @param {Boolean} isArrayChild true if cloning immediately underneath an array. Special case for minimize. - * @return {Object} the cloned object - * @api private - */ - - function clone(obj, options, isArrayChild) { - if (obj == null) { - return obj; - } - - if (Array.isArray(obj)) { - return cloneArray(obj, options); - } - - if (isMongooseObject(obj)) { - // Single nested subdocs should apply getters later in `applyGetters()` - // when calling `toObject()`. See gh-7442, gh-8295 - if ( - options && - options._skipSingleNestedGetters && - obj.$isSingleNested - ) { - options = Object.assign({}, options, { getters: false }); - } +/***/ 7378: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (utils.isPOJO(obj) && obj.$__ != null && obj._doc != null) { - return obj._doc; - } +"use strict"; - if (options && options.json && typeof obj.toJSON === "function") { - return obj.toJSON(options); - } - return obj.toObject(options); - } - if (obj.constructor) { - switch (getFunctionName(obj.constructor)) { - case "Object": - return cloneObject(obj, options, isArrayChild); - case "Date": - return new obj.constructor(+obj); - case "RegExp": - return cloneRegExp(obj); - default: - // ignore - break; - } - } +/*! + * ignore + */ - if (obj instanceof ObjectId) { - return new ObjectId(obj.id); - } +module.exports = applyQueryMiddleware; - if (isBsonType(obj, "Decimal128")) { - if (options && options.flattenDecimals) { - return obj.toJSON(); - } - return Decimal.fromString(obj.toString()); - } +const validOps = __nccwpck_require__(2786); - if (!obj.constructor && isObject(obj)) { - // object created with Object.create(null) - return cloneObject(obj, options, isArrayChild); - } +/*! + * ignore + */ - if (obj[symbols.schemaTypeSymbol]) { - return obj.clone(); - } +applyQueryMiddleware.middlewareFunctions = validOps.concat([ + 'validate' +]); - // If we're cloning this object to go into a MongoDB command, - // and there's a `toBSON()` function, assume this object will be - // stored as a primitive in MongoDB and doesn't need to be cloned. - if (options && options.bson && typeof obj.toBSON === "function") { - return obj; - } +/*! + * Apply query middleware + * + * @param {Query} query constructor + * @param {Model} model + */ - if (obj.valueOf != null) { - return obj.valueOf(); - } +function applyQueryMiddleware(Query, model) { + const kareemOptions = { + useErrorHandlers: true, + numCallbackParams: 1, + nullResultByDefault: true + }; - return cloneObject(obj, options, isArrayChild); - } - module.exports = clone; + const middleware = model.hooks.filter(hook => { + const contexts = _getContexts(hook); + if (hook.name === 'updateOne') { + return contexts.query == null || !!contexts.query; + } + if (hook.name === 'deleteOne') { + return !!contexts.query || Object.keys(contexts).length === 0; + } + if (hook.name === 'validate' || hook.name === 'remove') { + return !!contexts.query; + } + if (hook.query != null || hook.document != null) { + return !!hook.query; + } + return true; + }); + + // `update()` thunk has a different name because `_update` was already taken + Query.prototype._execUpdate = middleware.createWrapper('update', + Query.prototype._execUpdate, null, kareemOptions); + // `distinct()` thunk has a different name because `_distinct` was already taken + Query.prototype.__distinct = middleware.createWrapper('distinct', + Query.prototype.__distinct, null, kareemOptions); + + // `validate()` doesn't have a thunk because it doesn't execute a query. + Query.prototype.validate = middleware.createWrapper('validate', + Query.prototype.validate, null, kareemOptions); + + applyQueryMiddleware.middlewareFunctions. + filter(v => v !== 'update' && v !== 'distinct' && v !== 'validate'). + forEach(fn => { + Query.prototype[`_${fn}`] = middleware.createWrapper(fn, + Query.prototype[`_${fn}`], null, kareemOptions); + }); +} + +function _getContexts(hook) { + const ret = {}; + if (hook.hasOwnProperty('query')) { + ret.query = hook.query; + } + if (hook.hasOwnProperty('document')) { + ret.document = hook.document; + } + return ret; +} - /*! - * ignore - */ +/***/ }), - function cloneObject(obj, options, isArrayChild) { - const minimize = options && options.minimize; - const ret = {}; - let hasKeys; +/***/ 8045: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (const k of Object.keys(obj)) { - if (specialProperties.has(k)) { - continue; - } +"use strict"; - // Don't pass `isArrayChild` down - const val = clone(obj[k], options); - if (!minimize || typeof val !== "undefined") { - if (minimize === false && typeof val === "undefined") { - delete ret[k]; - } else { - hasKeys || (hasKeys = true); - ret[k] = val; - } - } - } +const isOperator = __nccwpck_require__(3342); - return minimize && !isArrayChild ? hasKeys && ret : ret; - } +module.exports = function castFilterPath(query, schematype, val) { + const ctx = query; + const any$conditionals = Object.keys(val).some(isOperator); - function cloneArray(arr, options) { - const ret = []; + if (!any$conditionals) { + return schematype.castForQueryWrapper({ + val: val, + context: ctx + }); + } - for (const item of arr) { - ret.push(clone(item, options, true)); - } + const ks = Object.keys(val); - return ret; - } + let k = ks.length; - /***/ - }, + while (k--) { + const $cond = ks[k]; + const nested = val[$cond]; - /***/ 3719: /***/ ( - __unused_webpack_module, - exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const Binary = __nccwpck_require__(2324).get().Binary; - const Decimal128 = __nccwpck_require__(8319); - const ObjectId = __nccwpck_require__(2706); - const isMongooseObject = __nccwpck_require__(7104); - - exports.x = flatten; - exports.M = modifiedPaths; - - /*! - * ignore - */ - - function flatten(update, path, options, schema) { - let keys; - if (update && isMongooseObject(update) && !Buffer.isBuffer(update)) { - keys = Object.keys( - update.toObject({ transform: false, virtuals: false }) - ); + if ($cond === '$not') { + if (nested && schematype && !schematype.caster) { + const _keys = Object.keys(nested); + if (_keys.length && isOperator(_keys[0])) { + for (const key of Object.keys(nested)) { + nested[key] = schematype.castForQueryWrapper({ + $conditional: key, + val: nested[key], + context: ctx + }); + } } else { - keys = Object.keys(update || {}); + val[$cond] = schematype.castForQueryWrapper({ + $conditional: $cond, + val: nested, + context: ctx + }); } + continue; + } + // cast(schematype.caster ? schematype.caster.schema : schema, nested, options, context); + } else { + val[$cond] = schematype.castForQueryWrapper({ + $conditional: $cond, + val: nested, + context: ctx + }); + } + } - const numKeys = keys.length; - const result = {}; - path = path ? path + "." : ""; + return val; +}; - for (let i = 0; i < numKeys; ++i) { - const key = keys[i]; - const val = update[key]; - result[path + key] = val; +/***/ }), - // Avoid going into mixed paths if schema is specified - const keySchema = schema && schema.path && schema.path(path + key); - const isNested = schema && schema.nested && schema.nested[path + key]; - if (keySchema && keySchema.instance === "Mixed") continue; +/***/ 3303: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (shouldFlatten(val)) { - if (options && options.skipArrays && Array.isArray(val)) { - continue; - } - const flat = flatten(val, path + key, options, schema); - for (const k in flat) { - result[k] = flat[k]; - } - if (Array.isArray(val)) { - result[path + key] = val; - } - } +"use strict"; - if (isNested) { - const paths = Object.keys(schema.paths); - for (const p of paths) { - if (p.startsWith(path + key + ".") && !result.hasOwnProperty(p)) { - result[p] = void 0; - } - } - } - } - return result; +const CastError = __nccwpck_require__(2798); +const MongooseError = __nccwpck_require__(5953); +const StrictModeError = __nccwpck_require__(5328); +const ValidationError = __nccwpck_require__(8460); +const castNumber = __nccwpck_require__(1582); +const cast = __nccwpck_require__(9179); +const getConstructorName = __nccwpck_require__(7323); +const getEmbeddedDiscriminatorPath = __nccwpck_require__(5087); +const handleImmutable = __nccwpck_require__(8176); +const moveImmutableProperties = __nccwpck_require__(4632); +const schemaMixedSymbol = __nccwpck_require__(1205).schemaMixedSymbol; +const setDottedPath = __nccwpck_require__(1707); +const utils = __nccwpck_require__(9232); + +/*! + * Casts an update op based on the given schema + * + * @param {Schema} schema + * @param {Object} obj + * @param {Object} options + * @param {Boolean} [options.overwrite] defaults to false + * @param {Boolean|String} [options.strict] defaults to true + * @param {Query} context passed to setters + * @return {Boolean} true iff the update is non-empty + */ +module.exports = function castUpdate(schema, obj, options, context, filter) { + if (obj == null) { + return undefined; + } + options = options || {}; + // Update pipeline + if (Array.isArray(obj)) { + const len = obj.length; + for (let i = 0; i < len; ++i) { + const ops = Object.keys(obj[i]); + for (const op of ops) { + obj[i][op] = castPipelineOperator(op, obj[i][op]); + } + } + return obj; + } + if (schema.options.strict === 'throw' && obj.hasOwnProperty(schema.options.discriminatorKey)) { + throw new StrictModeError(schema.options.discriminatorKey); + } else if (context._mongooseOptions != null && !context._mongooseOptions.overwriteDiscriminatorKey) { + delete obj[schema.options.discriminatorKey]; + } + if (options.upsert) { + moveImmutableProperties(schema, obj, context); + } + + const ops = Object.keys(obj); + let i = ops.length; + const ret = {}; + let val; + let hasDollarKey = false; + const overwrite = options.overwrite; + + filter = filter || {}; + while (i--) { + const op = ops[i]; + // if overwrite is set, don't do any of the special $set stuff + if (op[0] !== '$' && !overwrite) { + // fix up $set sugar + if (!ret.$set) { + if (obj.$set) { + ret.$set = obj.$set; + } else { + ret.$set = {}; + } } + ret.$set[op] = obj[op]; + ops.splice(i, 1); + if (!~ops.indexOf('$set')) ops.push('$set'); + } else if (op === '$set') { + if (!ret.$set) { + ret[op] = obj[op]; + } + } else { + ret[op] = obj[op]; + } + } + // cast each value + i = ops.length; + while (i--) { + const op = ops[i]; + val = ret[op]; + hasDollarKey = hasDollarKey || op.startsWith('$'); + + if (val && + typeof val === 'object' && + !Buffer.isBuffer(val) && + (!overwrite || hasDollarKey)) { + walkUpdatePath(schema, val, op, options, context, filter); + } else if (overwrite && ret && typeof ret === 'object') { + walkUpdatePath(schema, ret, '$set', options, context, filter); + } else { + const msg = 'Invalid atomic update value for ' + op + '. ' + + 'Expected an object, received ' + typeof val; + throw new Error(msg); + } - /*! - * ignore - */ + if (op.startsWith('$') && utils.isEmptyObject(val)) { + delete ret[op]; + } + } - function modifiedPaths(update, path, result) { - const keys = Object.keys(update || {}); - const numKeys = keys.length; - result = result || {}; - path = path ? path + "." : ""; + if (Object.keys(ret).length === 0 && + options.upsert && + Object.keys(filter).length > 0) { + // Trick the driver into allowing empty upserts to work around + // https://github.com/mongodb/node-mongodb-native/pull/2490 + return { $setOnInsert: filter }; + } + return ret; +}; - for (let i = 0; i < numKeys; ++i) { - const key = keys[i]; - let val = update[key]; +/*! + * ignore + */ - result[path + key] = true; - if (isMongooseObject(val) && !Buffer.isBuffer(val)) { - val = val.toObject({ transform: false, virtuals: false }); - } - if (shouldFlatten(val)) { - modifiedPaths(val, path + key, result); - } - } +function castPipelineOperator(op, val) { + if (op === '$unset') { + if (typeof val !== 'string' && (!Array.isArray(val) || val.find(v => typeof v !== 'string'))) { + throw new MongooseError('Invalid $unset in pipeline, must be ' + + ' a string or an array of strings'); + } + return val; + } + if (op === '$project') { + if (val == null || typeof val !== 'object') { + throw new MongooseError('Invalid $project in pipeline, must be an object'); + } + return val; + } + if (op === '$addFields' || op === '$set') { + if (val == null || typeof val !== 'object') { + throw new MongooseError('Invalid ' + op + ' in pipeline, must be an object'); + } + return val; + } else if (op === '$replaceRoot' || op === '$replaceWith') { + if (val == null || typeof val !== 'object') { + throw new MongooseError('Invalid ' + op + ' in pipeline, must be an object'); + } + return val; + } - return result; + throw new MongooseError('Invalid update pipeline operator: "' + op + '"'); +} + +/*! + * Walk each path of obj and cast its values + * according to its schema. + * + * @param {Schema} schema + * @param {Object} obj - part of a query + * @param {String} op - the atomic operator ($pull, $set, etc) + * @param {Object} options + * @param {Boolean|String} [options.strict] + * @param {Query} context + * @param {String} pref - path prefix (internal only) + * @return {Bool} true if this path has keys to update + * @api private + */ + +function walkUpdatePath(schema, obj, op, options, context, filter, pref) { + const strict = options.strict; + const prefix = pref ? pref + '.' : ''; + const keys = Object.keys(obj); + let i = keys.length; + let hasKeys = false; + let schematype; + let key; + let val; + + let aggregatedError = null; + + while (i--) { + key = keys[i]; + val = obj[key]; + + // `$pull` is special because we need to cast the RHS as a query, not as + // an update. + if (op === '$pull') { + schematype = schema._getSchema(prefix + key); + if (schematype != null && schematype.schema != null) { + obj[key] = cast(schematype.schema, obj[key], options, context); + hasKeys = true; + continue; } + } - /*! - * ignore - */ - - function shouldFlatten(val) { - return ( - val && - typeof val === "object" && - !(val instanceof Date) && - !(val instanceof ObjectId) && - (!Array.isArray(val) || val.length > 0) && - !(val instanceof Buffer) && - !(val instanceof Decimal128) && - !(val instanceof Binary) - ); + if (getConstructorName(val) === 'Object') { + // watch for embedded doc schemas + schematype = schema._getSchema(prefix + key); + + if (schematype == null) { + const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, prefix + key, options); + if (_res.schematype != null) { + schematype = _res.schematype; + } } - /***/ - }, + if (op !== '$setOnInsert' && + handleImmutable(schematype, strict, obj, key, prefix + key, context)) { + continue; + } - /***/ 9893: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const immediate = __nccwpck_require__(4830); - const promiseOrCallback = __nccwpck_require__(4046); - - /** - * Execute `fn` for every document in the cursor. If `fn` returns a promise, - * will wait for the promise to resolve before iterating on to the next one. - * Returns a promise that resolves when done. - * - * @param {Function} next the thunk to call to get the next document - * @param {Function} fn - * @param {Object} options - * @param {Function} [callback] executed when all docs have been processed - * @return {Promise} - * @api public - * @method eachAsync - */ - - module.exports = function eachAsync(next, fn, options, callback) { - const parallel = options.parallel || 1; - const batchSize = options.batchSize; - const enqueue = asyncQueue(); - - return promiseOrCallback(callback, (cb) => { - if (batchSize != null) { - if (typeof batchSize !== "number") { - throw new TypeError("batchSize must be a number"); - } - if (batchSize < 1) { - throw new TypeError("batchSize must be at least 1"); - } - if (batchSize !== Math.floor(batchSize)) { - throw new TypeError("batchSize must be a positive integer"); - } + if (schematype && schematype.caster && op in castOps) { + // embedded doc schema + if ('$each' in val) { + hasKeys = true; + try { + obj[key] = { + $each: castUpdateVal(schematype, val.$each, op, key, context, prefix + key) + }; + } catch (error) { + aggregatedError = _handleCastError(error, context, key, aggregatedError); } - iterate(cb); - }); - - function iterate(finalCallback) { - let drained = false; - let handleResultsInProgress = 0; - let currentDocumentIndex = 0; - let documentsBatch = []; + if (val.$slice != null) { + obj[key].$slice = val.$slice | 0; + } - let error = null; - for (let i = 0; i < parallel; ++i) { - enqueue(fetch); + if (val.$sort) { + obj[key].$sort = val.$sort; } - function fetch(done) { - if (drained || error) { - return done(); + if (val.$position != null) { + obj[key].$position = castNumber(val.$position); + } + } else { + if (schematype != null && schematype.$isSingleNested) { + const _strict = strict == null ? schematype.schema.options.strict : strict; + try { + obj[key] = schematype.castForQuery(val, context, { strict: _strict }); + } catch (error) { + aggregatedError = _handleCastError(error, context, key, aggregatedError); } + } else { + try { + obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key); + } catch (error) { + aggregatedError = _handleCastError(error, context, key, aggregatedError); + } + } - next(function (err, doc) { - if (drained || error != null) { - return done(); - } - if (err != null) { - error = err; - finalCallback(err); - return done(); - } - if (doc == null) { - drained = true; - if (handleResultsInProgress <= 0) { - finalCallback(null); - } else if (batchSize != null && documentsBatch.length) { - handleNextResult( - documentsBatch, - currentDocumentIndex++, - handleNextResultCallBack - ); - } - return done(); - } + if (obj[key] === void 0) { + delete obj[key]; + continue; + } - ++handleResultsInProgress; + hasKeys = true; + } + } else if ((op === '$currentDate') || (op in castOps && schematype)) { + // $currentDate can take an object + try { + obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key); + } catch (error) { + aggregatedError = _handleCastError(error, context, key, aggregatedError); + } - // Kick off the subsequent `next()` before handling the result, but - // make sure we know that we still have a result to handle re: #8422 - immediate(() => done()); + if (obj[key] === void 0) { + delete obj[key]; + continue; + } - if (batchSize != null) { - documentsBatch.push(doc); - } + hasKeys = true; + } else { + const pathToCheck = (prefix + key); + const v = schema._getPathType(pathToCheck); + let _strict = strict; + if (v && v.schema && _strict == null) { + _strict = v.schema.options.strict; + } - // If the current documents size is less than the provided patch size don't process the documents yet - if (batchSize != null && documentsBatch.length !== batchSize) { - setTimeout(() => enqueue(fetch), 0); - return; - } + if (v.pathType === 'undefined') { + if (_strict === 'throw') { + throw new StrictModeError(pathToCheck); + } else if (_strict) { + delete obj[key]; + continue; + } + } - const docsToProcess = batchSize != null ? documentsBatch : doc; + // gh-2314 + // we should be able to set a schema-less field + // to an empty object literal + hasKeys |= walkUpdatePath(schema, val, op, options, context, filter, prefix + key) || + (utils.isObject(val) && Object.keys(val).length === 0); + } + } else { + const checkPath = (key === '$each' || key === '$or' || key === '$and' || key === '$in') ? + pref : prefix + key; + schematype = schema._getSchema(checkPath); - function handleNextResultCallBack(err) { - if (batchSize != null) { - handleResultsInProgress -= documentsBatch.length; - documentsBatch = []; - } else { - --handleResultsInProgress; - } - if (err != null) { - error = err; - return finalCallback(err); - } - if (drained && handleResultsInProgress <= 0) { - return finalCallback(null); - } + // You can use `$setOnInsert` with immutable keys + if (op !== '$setOnInsert' && + handleImmutable(schematype, strict, obj, key, prefix + key, context)) { + continue; + } - setTimeout(() => enqueue(fetch), 0); - } + let pathDetails = schema._getPathType(checkPath); - handleNextResult( - docsToProcess, - currentDocumentIndex++, - handleNextResultCallBack - ); - }); - } + // If no schema type, check for embedded discriminators because the + // filter or update may imply an embedded discriminator type. See #8378 + if (schematype == null) { + const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, checkPath, options); + if (_res.schematype != null) { + schematype = _res.schematype; + pathDetails = _res.type; } + } - function handleNextResult(doc, i, callback) { - const promise = fn(doc, i); - if (promise && typeof promise.then === "function") { - promise.then( - function () { - callback(null); - }, - function (error) { - callback( - error || - new Error("`eachAsync()` promise rejected without error") - ); - } - ); + let isStrict = strict; + if (pathDetails && pathDetails.schema && strict == null) { + isStrict = pathDetails.schema.options.strict; + } + + const skip = isStrict && + !schematype && + !/real|nested/.test(pathDetails.pathType); + + if (skip) { + // Even if strict is `throw`, avoid throwing an error because of + // virtuals because of #6731 + if (isStrict === 'throw' && schema.virtuals[checkPath] == null) { + throw new StrictModeError(prefix + key); + } else { + delete obj[key]; + } + } else { + // gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking + // improving this. + if (op === '$rename') { + hasKeys = true; + continue; + } + + try { + if (prefix.length === 0 || key.indexOf('.') === -1) { + obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key); } else { - callback(null); + // Setting a nested dotted path that's in the schema. We don't allow paths with '.' in + // a schema, so replace the dotted path with a nested object to avoid ending up with + // dotted properties in the updated object. See (gh-10200) + setDottedPath(obj, key, castUpdateVal(schematype, val, op, key, context, prefix + key)); + delete obj[key]; } + } catch (error) { + aggregatedError = _handleCastError(error, context, key, aggregatedError); } - }; - // `next()` can only execute one at a time, so make sure we always execute - // `next()` in series, while still allowing multiple `fn()` instances to run - // in parallel. - function asyncQueue() { - const _queue = []; - let inProgress = null; - let id = 0; - - return function enqueue(fn) { - if (_queue.length === 0 && inProgress == null) { - inProgress = id++; - return fn(_step); + if (Array.isArray(obj[key]) && (op === '$addToSet' || op === '$push') && key !== '$each') { + if (schematype && schematype.caster && !schematype.caster.$isMongooseArray) { + obj[key] = { $each: obj[key] }; } - _queue.push(fn); - }; + } - function _step() { - inProgress = null; - if (_queue.length > 0) { - inProgress = id++; - const fn = _queue.shift(); - fn(_step); - } + if (obj[key] === void 0) { + delete obj[key]; + continue; } - } - /***/ - }, + hasKeys = true; + } + } + } - /***/ 9295: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + if (aggregatedError != null) { + throw aggregatedError; + } - const ObjectId = __nccwpck_require__(2706); + return hasKeys; +} - module.exports = function areDiscriminatorValuesEqual(a, b) { - if (typeof a === "string" && typeof b === "string") { - return a === b; - } - if (typeof a === "number" && typeof b === "number") { - return a === b; - } - if (a instanceof ObjectId && b instanceof ObjectId) { - return a.toString() === b.toString(); - } - return false; - }; +/*! + * ignore + */ - /***/ - }, +function _handleCastError(error, query, key, aggregatedError) { + if (typeof query !== 'object' || !query.options.multipleCastError) { + throw error; + } + aggregatedError = aggregatedError || new ValidationError(); + aggregatedError.addError(key, error); + return aggregatedError; +} + +/*! + * These operators should be cast to numbers instead + * of their path schema type. + */ - /***/ 1762: /***/ (module) => { - "use strict"; - - module.exports = function checkEmbeddedDiscriminatorKeyProjection( - userProjection, - path, - schema, - selected, - addedPaths - ) { - const userProjectedInPath = Object.keys(userProjection).reduce( - (cur, key) => cur || key.startsWith(path + "."), - false - ); - const _discriminatorKey = path + "." + schema.options.discriminatorKey; - if ( - !userProjectedInPath && - addedPaths.length === 1 && - addedPaths[0] === _discriminatorKey - ) { - selected.splice(selected.indexOf(_discriminatorKey), 1); - } - }; +const numberOps = { + $pop: 1, + $inc: 1 +}; - /***/ - }, +/*! + * These ops require no casting because the RHS doesn't do anything. + */ - /***/ 1449: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +const noCastOps = { + $unset: 1 +}; - const getDiscriminatorByValue = __nccwpck_require__(8689); +/*! + * These operators require casting docs + * to real Documents for Update operations. + */ - /*! - * Find the correct constructor, taking into account discriminators - */ +const castOps = { + $push: 1, + $addToSet: 1, + $set: 1, + $setOnInsert: 1 +}; - module.exports = function getConstructor(Constructor, value) { - const discriminatorKey = Constructor.schema.options.discriminatorKey; - if ( - value != null && - Constructor.discriminators && - value[discriminatorKey] != null - ) { - if (Constructor.discriminators[value[discriminatorKey]]) { - Constructor = Constructor.discriminators[value[discriminatorKey]]; - } else { - const constructorByValue = getDiscriminatorByValue( - Constructor.discriminators, - value[discriminatorKey] - ); - if (constructorByValue) { - Constructor = constructorByValue; - } - } - } +/*! + * ignore + */ - return Constructor; - }; +const overwriteOps = { + $set: 1, + $setOnInsert: 1 +}; - /***/ - }, +/*! + * Casts `val` according to `schema` and atomic `op`. + * + * @param {SchemaType} schema + * @param {Object} val + * @param {String} op - the atomic operator ($pull, $set, etc) + * @param {String} $conditional + * @param {Query} context + * @api private + */ - /***/ 8689: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const areDiscriminatorValuesEqual = __nccwpck_require__(9295); - - /*! - * returns discriminator by discriminatorMapping.value - * - * @param {Model} model - * @param {string} value - */ - - module.exports = function getDiscriminatorByValue(discriminators, value) { - if (discriminators == null) { - return null; - } - for (const name of Object.keys(discriminators)) { - const it = discriminators[name]; - if ( - it.schema && - it.schema.discriminatorMapping && - areDiscriminatorValuesEqual( - it.schema.discriminatorMapping.value, - value - ) - ) { - return it; - } - } - return null; - }; +function castUpdateVal(schema, val, op, $conditional, context, path) { + if (!schema) { + // non-existing schema path + if (op in numberOps) { + try { + return castNumber(val); + } catch (err) { + throw new CastError('number', val, path); + } + } + return val; + } - /***/ - }, + const cond = schema.caster && op in castOps && + (utils.isObject(val) || Array.isArray(val)); + if (cond && !overwriteOps[op]) { + // Cast values for ops that add data to MongoDB. + // Ensures embedded documents get ObjectIds etc. + let schemaArrayDepth = 0; + let cur = schema; + while (cur.$isMongooseArray) { + ++schemaArrayDepth; + cur = cur.caster; + } + let arrayDepth = 0; + let _val = val; + while (Array.isArray(_val)) { + ++arrayDepth; + _val = _val[0]; + } - /***/ 6250: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + const additionalNesting = schemaArrayDepth - arrayDepth; + while (arrayDepth < schemaArrayDepth) { + val = [val]; + ++arrayDepth; + } - const areDiscriminatorValuesEqual = __nccwpck_require__(9295); + let tmp = schema.applySetters(Array.isArray(val) ? val : [val], context); - /*! - * returns discriminator by discriminatorMapping.value - * - * @param {Schema} schema - * @param {string} value - */ + for (let i = 0; i < additionalNesting; ++i) { + tmp = tmp[0]; + } + return tmp; + } - module.exports = function getSchemaDiscriminatorByValue(schema, value) { - if (schema == null || schema.discriminators == null) { - return null; - } - for (const key of Object.keys(schema.discriminators)) { - const discriminatorSchema = schema.discriminators[key]; - if (discriminatorSchema.discriminatorMapping == null) { - continue; - } - if ( - areDiscriminatorValuesEqual( - discriminatorSchema.discriminatorMapping.value, - value - ) - ) { - return discriminatorSchema; - } - } - return null; - }; + if (op in noCastOps) { + return val; + } + if (op in numberOps) { + // Null and undefined not allowed for $pop, $inc + if (val == null) { + throw new CastError('number', val, schema.path); + } + if (op === '$inc') { + // Support `$inc` with long, int32, etc. (gh-4283) + return schema.castForQueryWrapper({ + val: val, + context: context + }); + } + try { + return castNumber(val); + } catch (error) { + throw new CastError('number', val, schema.path); + } + } + if (op === '$currentDate') { + if (typeof val === 'object') { + return { $type: val.$type }; + } + return Boolean(val); + } - /***/ - }, + if (/^\$/.test($conditional)) { + return schema.castForQueryWrapper({ + $conditional: $conditional, + val: val, + context: context + }); + } - /***/ 7958: /***/ (module) => { - "use strict"; + if (overwriteOps[op]) { + return schema.castForQueryWrapper({ + val: val, + context: context, + $skipQueryCastForUpdate: val != null && schema.$isMongooseArray && schema.$fullPath != null && !schema.$fullPath.match(/\d+$/), + $applySetters: schema[schemaMixedSymbol] != null + }); + } - /*! - * ignore - */ + return schema.castForQueryWrapper({ val: val, context: context }); +} - module.exports = function cleanModifiedSubpaths(doc, path, options) { - options = options || {}; - const skipDocArrays = options.skipDocArrays; - let deleted = 0; - if (!doc) { - return deleted; - } - for (const modifiedPath of Object.keys( - doc.$__.activePaths.states.modify - )) { - if (skipDocArrays) { - const schemaType = doc.$__schema.path(modifiedPath); - if (schemaType && schemaType.$isMongooseDocumentArray) { - continue; - } - } - if (modifiedPath.startsWith(path + ".")) { - delete doc.$__.activePaths.states.modify[modifiedPath]; - ++deleted; - } - } - return deleted; - }; +/***/ }), - /***/ - }, +/***/ 2941: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /***/ 2096: /***/ ( - __unused_webpack_module, - exports, - __nccwpck_require__ - ) => { - "use strict"; - - const documentSchemaSymbol = - __nccwpck_require__(3240).documentSchemaSymbol; - const get = __nccwpck_require__(8730); - const internalToObjectOptions = - __nccwpck_require__(5684) /* .internalToObjectOptions */.h; - const utils = __nccwpck_require__(9232); - - let Document; - const getSymbol = __nccwpck_require__(3240).getSymbol; - const scopeSymbol = __nccwpck_require__(3240).scopeSymbol; - - /*! - * exports - */ - - exports.M = compile; - exports.c = defineKey; - - /*! - * Compiles schemas. - */ - - function compile(tree, proto, prefix, options) { - Document = Document || __nccwpck_require__(6717); - const keys = Object.keys(tree); - const len = keys.length; - let limb; - let key; +"use strict"; - for (let i = 0; i < len; ++i) { - key = keys[i]; - limb = tree[key]; - const hasSubprops = - utils.isPOJO(limb) && - Object.keys(limb).length && - (!limb[options.typeKey] || - (options.typeKey === "type" && limb.type.type)); - const subprops = hasSubprops ? limb : null; +const helpers = __nccwpck_require__(5299); +const immediate = __nccwpck_require__(4830); - defineKey(key, subprops, proto, prefix, keys, options); - } - } +module.exports = completeMany; - /*! - * Defines the accessor named prop on the incoming prototype. - */ +/*! + * Given a model and an array of docs, hydrates all the docs to be instances + * of the model. Used to initialize docs returned from the db from `find()` + * + * @param {Model} model + * @param {Array} docs + * @param {Object} fields the projection used, including `select` from schemas + * @param {Object} userProvidedFields the user-specified projection + * @param {Object} opts + * @param {Array} [opts.populated] + * @param {ClientSession} [opts.session] + * @param {Function} callback + */ - function defineKey(prop, subprops, prototype, prefix, keys, options) { - Document = Document || __nccwpck_require__(6717); - const path = (prefix ? prefix + "." : "") + prop; - prefix = prefix || ""; +function completeMany(model, docs, fields, userProvidedFields, opts, callback) { + const arr = []; + let count = docs.length; + const len = count; + let error = null; - if (subprops) { - Object.defineProperty(prototype, prop, { - enumerable: true, - configurable: true, - get: function () { - const _this = this; - if (!this.$__.getters) { - this.$__.getters = {}; - } + function init(_error) { + if (_error != null) { + error = error || _error; + } + if (error != null) { + --count || immediate(() => callback(error)); + return; + } + --count || immediate(() => callback(error, arr)); + } - if (!this.$__.getters[path]) { - const nested = Object.create( - Document.prototype, - getOwnPropertyDescriptors(this) - ); + for (let i = 0; i < len; ++i) { + arr[i] = helpers.createModel(model, docs[i], fields, userProvidedFields); + try { + arr[i].$init(docs[i], opts, init); + } catch (error) { + init(error); + } - // save scope for nested getters/setters - if (!prefix) { - nested.$__[scopeSymbol] = this; - } - nested.$__.nestedPath = path; + if (opts.session != null) { + arr[i].$session(opts.session); + } + } +} - Object.defineProperty(nested, "schema", { - enumerable: false, - configurable: true, - writable: false, - value: prototype.schema, - }); - Object.defineProperty(nested, "$__schema", { - enumerable: false, - configurable: true, - writable: false, - value: prototype.schema, - }); +/***/ }), - Object.defineProperty(nested, documentSchemaSymbol, { - enumerable: false, - configurable: true, - writable: false, - value: prototype.schema, - }); +/***/ 5087: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Object.defineProperty(nested, "toObject", { - enumerable: false, - configurable: true, - writable: false, - value: function () { - return utils.clone( - _this.get(path, null, { - virtuals: get( - this, - "schema.options.toObject.virtuals", - null - ), - }) - ); - }, - }); +"use strict"; - Object.defineProperty(nested, "$__get", { - enumerable: false, - configurable: true, - writable: false, - value: function () { - return _this.get(path, null, { - virtuals: get( - this, - "schema.options.toObject.virtuals", - null - ), - }); - }, - }); - Object.defineProperty(nested, "toJSON", { - enumerable: false, - configurable: true, - writable: false, - value: function () { - return _this.get(path, null, { - virtuals: get( - _this, - "schema.options.toJSON.virtuals", - null - ), - }); - }, - }); +const cleanPositionalOperators = __nccwpck_require__(1119); +const get = __nccwpck_require__(8730); +const getDiscriminatorByValue = __nccwpck_require__(8689); +const updatedPathsByArrayFilter = __nccwpck_require__(6507); - Object.defineProperty(nested, "$__isNested", { - enumerable: false, - configurable: true, - writable: false, - value: true, - }); +/*! + * Like `schema.path()`, except with a document, because impossible to + * determine path type without knowing the embedded discriminator key. + */ - const _isEmptyOptions = Object.freeze({ - minimize: true, - virtuals: false, - getters: false, - transform: false, - }); - Object.defineProperty(nested, "$isEmpty", { - enumerable: false, - configurable: true, - writable: false, - value: function () { - return ( - Object.keys(this.get(path, null, _isEmptyOptions) || {}) - .length === 0 - ); - }, - }); +module.exports = function getEmbeddedDiscriminatorPath(schema, update, filter, path, options) { + const parts = path.split('.'); + let schematype = null; + let type = 'adhocOrUndefined'; + + filter = filter || {}; + update = update || {}; + const arrayFilters = options != null && Array.isArray(options.arrayFilters) ? + options.arrayFilters : []; + const updatedPathsByFilter = updatedPathsByArrayFilter(update); + + for (let i = 0; i < parts.length; ++i) { + const subpath = cleanPositionalOperators(parts.slice(0, i + 1).join('.')); + schematype = schema.path(subpath); + if (schematype == null) { + continue; + } - Object.defineProperty(nested, "$__parent", { - enumerable: false, - configurable: true, - writable: false, - value: this, - }); + type = schema.pathType(subpath); + if ((schematype.$isSingleNested || schematype.$isMongooseDocumentArrayElement) && + schematype.schema.discriminators != null) { + const key = get(schematype, 'schema.options.discriminatorKey'); + const discriminatorValuePath = subpath + '.' + key; + const discriminatorFilterPath = + discriminatorValuePath.replace(/\.\d+\./, '.'); + let discriminatorKey = null; - compile(subprops, nested, path, options); - this.$__.getters[path] = nested; - } + if (discriminatorValuePath in filter) { + discriminatorKey = filter[discriminatorValuePath]; + } + if (discriminatorFilterPath in filter) { + discriminatorKey = filter[discriminatorFilterPath]; + } - return this.$__.getters[path]; - }, - set: function (v) { - if (v != null && v.$__isNested) { - // Convert top-level to POJO, but leave subdocs hydrated so `$set` - // can handle them. See gh-9293. - v = v.$__get(); - } else if (v instanceof Document && !v.$__isNested) { - v = v.toObject(internalToObjectOptions); - } - const doc = this.$__[scopeSymbol] || this; - doc.$set(path, v); - }, - }); - } else { - Object.defineProperty(prototype, prop, { - enumerable: true, - configurable: true, - get: function () { - return this[getSymbol].call(this.$__[scopeSymbol] || this, path); - }, - set: function (v) { - this.$set.call(this.$__[scopeSymbol] || this, path, v); - }, - }); - } + const wrapperPath = subpath.replace(/\.\d+$/, ''); + if (schematype.$isMongooseDocumentArrayElement && + get(filter[wrapperPath], '$elemMatch.' + key) != null) { + discriminatorKey = filter[wrapperPath].$elemMatch[key]; } - // gets descriptors for all properties of `object` - // makes all properties non-enumerable to match previous behavior to #2211 - function getOwnPropertyDescriptors(object) { - const result = {}; + if (discriminatorValuePath in update) { + discriminatorKey = update[discriminatorValuePath]; + } - Object.getOwnPropertyNames(object).forEach(function (key) { - const skip = - [ - "isNew", - "$__", - "errors", - "_doc", - "$locals", - "$op", - "__parentArray", - "__index", - "$isDocumentArrayElement", - ].indexOf(key) === -1; - if (skip) { - return; + for (const filterKey of Object.keys(updatedPathsByFilter)) { + const schemaKey = updatedPathsByFilter[filterKey] + '.' + key; + const arrayFilterKey = filterKey + '.' + key; + if (schemaKey === discriminatorFilterPath) { + const filter = arrayFilters.find(filter => filter.hasOwnProperty(arrayFilterKey)); + if (filter != null) { + discriminatorKey = filter[arrayFilterKey]; } + } + } - result[key] = Object.getOwnPropertyDescriptor(object, key); - result[key].enumerable = false; - }); + if (discriminatorKey == null) { + continue; + } - return result; + const discriminatorSchema = getDiscriminatorByValue(schematype.caster.discriminators, discriminatorKey).schema; + + const rest = parts.slice(i + 1).join('.'); + schematype = discriminatorSchema.path(rest); + if (schematype != null) { + type = discriminatorSchema._getPathType(rest); + break; } + } + } - /***/ - }, + return { type: type, schematype: schematype }; +}; - /***/ 509: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const get = __nccwpck_require__(8730); - - /*! - * Like `schema.path()`, except with a document, because impossible to - * determine path type without knowing the embedded discriminator key. - */ - - module.exports = function getEmbeddedDiscriminatorPath( - doc, - path, - options - ) { - options = options || {}; - const typeOnly = options.typeOnly; - const parts = path.split("."); - let schema = null; - let type = "adhocOrUndefined"; - - for (let i = 0; i < parts.length; ++i) { - const subpath = parts.slice(0, i + 1).join("."); - schema = doc.schema.path(subpath); - if (schema == null) { - type = "adhocOrUndefined"; - continue; - } - if (schema.instance === "Mixed") { - return typeOnly ? "real" : schema; - } - type = doc.schema.pathType(subpath); - if ( - (schema.$isSingleNested || - schema.$isMongooseDocumentArrayElement) && - schema.schema.discriminators != null - ) { - const discriminators = schema.schema.discriminators; - const discriminatorKey = doc.get( - subpath + "." + get(schema, "schema.options.discriminatorKey") - ); - if ( - discriminatorKey == null || - discriminators[discriminatorKey] == null - ) { - continue; - } - const rest = parts.slice(i + 1).join("."); - return getEmbeddedDiscriminatorPath( - doc.get(subpath), - rest, - options - ); - } - } - // Are we getting the whole schema or just the type, 'real', 'nested', etc. - return typeOnly ? type : schema; - }; +/***/ }), - /***/ - }, +/***/ 8176: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /***/ 5232: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +"use strict"; - const utils = __nccwpck_require__(9232); - /** - * Using spread operator on a Mongoose document gives you a - * POJO that has a tendency to cause infinite recursion. So - * we use this function on `set()` to prevent that. - */ +const StrictModeError = __nccwpck_require__(5328); - module.exports = function handleSpreadDoc(v) { - if (utils.isPOJO(v) && v.$__ != null && v._doc != null) { - return v._doc; - } +module.exports = function handleImmutable(schematype, strict, obj, key, fullPath, ctx) { + if (schematype == null || !schematype.options || !schematype.options.immutable) { + return false; + } + let immutable = schematype.options.immutable; - return v; - }; + if (typeof immutable === 'function') { + immutable = immutable.call(ctx, ctx); + } + if (!immutable) { + return false; + } - /***/ - }, + if (strict === false) { + return false; + } + if (strict === 'throw') { + throw new StrictModeError(null, + `Field ${fullPath} is immutable and strict = 'throw'`); + } - /***/ 9965: /***/ (module) => { - "use strict"; + delete obj[key]; + return true; +}; - module.exports = function each(arr, cb, done) { - if (arr.length === 0) { - return done(); - } - let remaining = arr.length; - let err = null; - for (const v of arr) { - cb(v, function (_err) { - if (err != null) { - return; - } - if (_err != null) { - err = _err; - return done(err); - } +/***/ }), - if (--remaining <= 0) { - return done(); - } - }); - } - }; +/***/ 8309: +/***/ ((module) => { - /***/ - }, +"use strict"; - /***/ 8730: /***/ (module) => { - "use strict"; - /*! - * Simplified lodash.get to work around the annoying null quirk. See: - * https://github.com/lodash/lodash/issues/3659 - */ +/*! + * ignore + */ - module.exports = function get(obj, path, def) { - let parts; - let isPathArray = false; - if (typeof path === "string") { - if (path.indexOf(".") === -1) { - const _v = getProperty(obj, path); - if (_v == null) { - return def; - } - return _v; - } +module.exports = function(obj) { + if (obj == null || typeof obj !== 'object') { + return false; + } + const keys = Object.keys(obj); + const len = keys.length; + for (let i = 0; i < len; ++i) { + if (keys[i].startsWith('$')) { + return true; + } + } + return false; +}; - parts = path.split("."); - } else { - isPathArray = true; - parts = path; - if (parts.length === 1) { - const _v = getProperty(obj, parts[0]); - if (_v == null) { - return def; - } - return _v; - } - } - let rest = path; - let cur = obj; - for (const part of parts) { - if (cur == null) { - return def; - } +/***/ }), - // `lib/cast.js` depends on being able to get dotted paths in updates, - // like `{ $set: { 'a.b': 42 } }` - if (!isPathArray && cur[rest] != null) { - return cur[rest]; - } +/***/ 3342: +/***/ ((module) => { - cur = getProperty(cur, part); +"use strict"; - if (!isPathArray) { - rest = rest.substr(part.length + 1); - } - } - return cur == null ? def : cur; - }; +const specialKeys = new Set([ + '$ref', + '$id', + '$db' +]); - function getProperty(obj, prop) { - if (obj == null) { - return obj; - } - if (obj instanceof Map) { - return obj.get(prop); - } - return obj[prop]; - } +module.exports = function isOperator(path) { + return path.startsWith('$') && !specialKeys.has(path); +}; - /***/ - }, +/***/ }), - /***/ 7323: /***/ (module) => { - "use strict"; +/***/ 3824: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /*! - * If `val` is an object, returns constructor name, if possible. Otherwise returns undefined. - */ +"use strict"; - module.exports = function getConstructorName(val) { - if (val == null) { - return void 0; - } - if (typeof val.constructor !== "function") { - return void 0; - } - return val.constructor.name; - }; - /***/ - }, +const hasDollarKeys = __nccwpck_require__(8309); +const { trustedSymbol } = __nccwpck_require__(7776); - /***/ 3039: /***/ (module) => { - "use strict"; +module.exports = function sanitizeFilter(filter) { + if (filter == null || typeof filter !== 'object') { + return filter; + } + if (Array.isArray(filter)) { + for (const subfilter of filter) { + sanitizeFilter(subfilter); + } + return filter; + } - function getDefaultBulkwriteResult() { - return { - result: { - ok: 1, - writeErrors: [], - writeConcernErrors: [], - insertedIds: [], - nInserted: 0, - nUpserted: 0, - nMatched: 0, - nModified: 0, - nRemoved: 0, - upserted: [], - }, - insertedCount: 0, - matchedCount: 0, - modifiedCount: 0, - deletedCount: 0, - upsertedCount: 0, - upsertedIds: {}, - insertedIds: {}, - n: 0, - }; + const filterKeys = Object.keys(filter); + for (const key of filterKeys) { + const value = filter[key]; + if (value != null && value[trustedSymbol]) { + continue; + } + if (key === '$and' || key === '$or') { + sanitizeFilter(value); + continue; + } + + if (hasDollarKeys(value)) { + const keys = Object.keys(value); + if (keys.length === 1 && keys[0] === '$eq') { + continue; } + filter[key] = { $eq: filter[key] }; + } + } - module.exports = getDefaultBulkwriteResult; + return filter; +}; - /***/ - }, +/***/ }), - /***/ 6621: /***/ (module) => { - "use strict"; +/***/ 8276: +/***/ ((module) => { - module.exports = function (fn) { - if (fn.name) { - return fn.name; - } - return (fn - .toString() - .trim() - .match(/^function\s*([^\s(]+)/) || [])[1]; - }; +"use strict"; - /***/ - }, - /***/ 4830: /***/ (module) => { - "use strict"; - /*! - * Centralize this so we can more easily work around issues with people - * stubbing out `process.nextTick()` in tests using sinon: - * https://github.com/sinonjs/lolex#automatically-incrementing-mocked-time - * See gh-6074 - */ +module.exports = function sanitizeProjection(projection) { + if (projection == null) { + return; + } - const nextTick = process.nextTick.bind(process); + const keys = Object.keys(projection); + for (let i = 0; i < keys.length; ++i) { + if (typeof projection[keys[i]] === 'string') { + projection[keys[i]] = 1; + } + } +}; - module.exports = function immediate(cb) { - return nextTick(cb); - }; +/***/ }), - /***/ - }, +/***/ 1907: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /***/ 7720: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const get = __nccwpck_require__(8730); - - module.exports = function isDefaultIdIndex(index) { - if (Array.isArray(index)) { - // Mongoose syntax - const keys = Object.keys(index[0]); - return ( - keys.length === 1 && keys[0] === "_id" && index[0]._id !== "hashed" - ); - } +"use strict"; - if (typeof index !== "object") { - return false; - } - const key = get(index, "key", {}); - return Object.keys(key).length === 1 && key.hasOwnProperty("_id"); - }; +const isExclusive = __nccwpck_require__(3522); +const isInclusive = __nccwpck_require__(2951); - /***/ - }, +/*! + * ignore + */ - /***/ 4749: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const get = __nccwpck_require__(8730); - const utils = __nccwpck_require__(9232); - - /** - * Given a Mongoose index definition (key + options objects) and a MongoDB server - * index definition, determine if the two indexes are equal. - * - * @param {Object} key the Mongoose index spec - * @param {Object} options the Mongoose index definition's options - * @param {Object} dbIndex the index in MongoDB as returned by `listIndexes()` - * @api private - */ - - module.exports = function isIndexEqual(key, options, dbIndex) { - // Special case: text indexes have a special format in the db. For example, - // `{ name: 'text' }` becomes: - // { - // v: 2, - // key: { _fts: 'text', _ftsx: 1 }, - // name: 'name_text', - // ns: 'test.tests', - // background: true, - // weights: { name: 1 }, - // default_language: 'english', - // language_override: 'language', - // textIndexVersion: 3 - // } - if (dbIndex.textIndexVersion != null) { - const weights = dbIndex.weights; - if (Object.keys(weights).length !== Object.keys(key).length) { - return false; - } - for (const prop of Object.keys(weights)) { - if (!(prop in key)) { - return false; - } - const weight = weights[prop]; - if ( - weight !== get(options, "weights." + prop) && - !(weight === 1 && get(options, "weights." + prop) == null) - ) { - return false; - } - } +module.exports = function selectPopulatedFields(fields, userProvidedFields, populateOptions) { + if (populateOptions == null) { + return; + } - if (options["default_language"] !== dbIndex["default_language"]) { - return ( - dbIndex["default_language"] === "english" && - options["default_language"] == null - ); - } + const paths = Object.keys(populateOptions); + userProvidedFields = userProvidedFields || {}; + if (isInclusive(fields)) { + for (const path of paths) { + if (!isPathInFields(userProvidedFields, path)) { + fields[path] = 1; + } else if (userProvidedFields[path] === 0) { + delete fields[path]; + } + } + } else if (isExclusive(fields)) { + for (const path of paths) { + if (userProvidedFields[path] == null) { + delete fields[path]; + } + } + } +}; + +/*! + * ignore + */ + +function isPathInFields(userProvidedFields, path) { + const pieces = path.split('.'); + const len = pieces.length; + let cur = pieces[0]; + for (let i = 1; i < len; ++i) { + if (userProvidedFields[cur] != null || userProvidedFields[cur + '.$'] != null) { + return true; + } + cur += '.' + pieces[i]; + } + return userProvidedFields[cur] != null || userProvidedFields[cur + '.$'] != null; +} - return true; - } - const optionKeys = [ - "unique", - "partialFilterExpression", - "sparse", - "expireAfterSeconds", - "collation", - ]; - for (const key of optionKeys) { - if (!(key in options) && !(key in dbIndex)) { - continue; - } - if (key === "collation") { - if (options[key] == null || dbIndex[key] == null) { - return options[key] == null && dbIndex[key] == null; - } - const definedKeys = Object.keys(options.collation); - const schemaCollation = options.collation; - const dbCollation = dbIndex.collation; - for (const opt of definedKeys) { - if (get(schemaCollation, opt) !== get(dbCollation, opt)) { - return false; - } - } - } else if (!utils.deepEqual(options[key], dbIndex[key])) { - return false; - } - } +/***/ }), - const schemaIndexKeys = Object.keys(key); - const dbIndexKeys = Object.keys(dbIndex.key); - if (schemaIndexKeys.length !== dbIndexKeys.length) { - return false; - } - for (let i = 0; i < schemaIndexKeys.length; ++i) { - if (schemaIndexKeys[i] !== dbIndexKeys[i]) { - return false; - } - if ( - !utils.deepEqual( - key[schemaIndexKeys[i]], - dbIndex.key[dbIndexKeys[i]] - ) - ) { - return false; - } - } +/***/ 7776: +/***/ ((__unused_webpack_module, exports) => { - return true; - }; +"use strict"; - /***/ - }, - /***/ 1238: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +const trustedSymbol = Symbol('mongoose#trustedSymbol'); - const get = __nccwpck_require__(8730); +exports.trustedSymbol = trustedSymbol; - /*! - * Get the bson type, if it exists - */ +exports.trusted = function trusted(obj) { + if (obj == null || typeof obj !== 'object') { + return obj; + } + obj[trustedSymbol] = true; + return obj; +}; + +/***/ }), + +/***/ 2786: +/***/ ((module) => { + +"use strict"; + + +module.exports = Object.freeze([ + // Read + 'count', + 'countDocuments', + 'distinct', + 'estimatedDocumentCount', + 'find', + 'findOne', + // Update + 'findOneAndReplace', + 'findOneAndUpdate', + 'replaceOne', + 'update', + 'updateMany', + 'updateOne', + // Delete + 'deleteMany', + 'deleteOne', + 'findOneAndDelete', + 'findOneAndRemove', + 'remove' +]); + +/***/ }), + +/***/ 2006: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const MongooseError = __nccwpck_require__(5953); + +/*! + * A query thunk is the function responsible for sending the query to MongoDB, + * like `Query#_findOne()` or `Query#_execUpdate()`. The `Query#exec()` function + * calls a thunk. The term "thunk" here is the traditional Node.js definition: + * a function that takes exactly 1 parameter, a callback. + * + * This function defines common behavior for all query thunks. + */ - function isBsonType(obj, typename) { - return get(obj, "_bsontype", void 0) === typename; +module.exports = function wrapThunk(fn) { + return function _wrappedThunk(cb) { + if (this._executionStack != null) { + let str = this.toString(); + if (str.length > 60) { + str = str.slice(0, 60) + '...'; } + const err = new MongooseError('Query was already executed: ' + str); + err.originalStack = this._executionStack.stack; + return cb(err); + } + this._executionStack = new Error(); - module.exports = isBsonType; + fn.call(this, cb); + }; +}; - /***/ - }, +/***/ }), - /***/ 7104: /***/ (module) => { - "use strict"; +/***/ 9115: +/***/ ((module) => { - /*! - * Returns if `v` is a mongoose object that has a `toObject()` method we can use. - * - * This is for compatibility with libs like Date.js which do foolish things to Natives. - * - * @param {any} v - * @api private - */ +"use strict"; - module.exports = function (v) { - if (v == null) { - return false; - } - return ( - v.$__ != null || // Document - v.isMongooseArray || // Array or Document Array - v.isMongooseBuffer || // Buffer - v.$isMongooseMap - ); // Map - }; +module.exports = function addAutoId(schema) { + const _obj = { _id: { auto: true } }; + _obj._id[schema.options.typeKey] = 'ObjectId'; + schema.add(_obj); +}; - /***/ - }, +/***/ }), - /***/ 273: /***/ (module) => { - "use strict"; +/***/ 6990: +/***/ ((module) => { - /*! - * Determines if `arg` is an object. - * - * @param {Object|Array|String|Function|RegExp|any} arg - * @api private - * @return {Boolean} - */ +"use strict"; - module.exports = function (arg) { - if (Buffer.isBuffer(arg)) { - return true; - } - return Object.prototype.toString.call(arg) === "[object Object]"; - }; - /***/ - }, +module.exports = function applyPlugins(schema, plugins, options, cacheKey) { + if (schema[cacheKey]) { + return; + } + schema[cacheKey] = true; + + if (!options || !options.skipTopLevel) { + for (const plugin of plugins) { + schema.plugin(plugin[0], plugin[1]); + } + } - /***/ 224: /***/ (module) => { - "use strict"; + options = Object.assign({}, options); + delete options.skipTopLevel; - function isPromise(val) { - return ( - !!val && - (typeof val === "object" || typeof val === "function") && - typeof val.then === "function" - ); + if (options.applyPluginsToChildSchemas !== false) { + for (const path of Object.keys(schema.paths)) { + const type = schema.paths[path]; + if (type.schema != null) { + applyPlugins(type.schema, plugins, options, cacheKey); + + // Recompile schema because plugins may have changed it, see gh-7572 + type.caster.prototype.$__setSchema(type.schema); } + } + } - module.exports = isPromise; + const discriminators = schema.discriminators; + if (discriminators == null) { + return; + } - /***/ - }, + const applyPluginsToDiscriminators = options.applyPluginsToDiscriminators; - /***/ 5373: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const symbols = __nccwpck_require__(1205); - const promiseOrCallback = __nccwpck_require__(4046); - - /*! - * ignore - */ - - module.exports = applyHooks; - - /*! - * ignore - */ - - applyHooks.middlewareFunctions = [ - "deleteOne", - "save", - "validate", - "remove", - "updateOne", - "init", - ]; + const keys = Object.keys(discriminators); + for (const discriminatorKey of keys) { + const discriminatorSchema = discriminators[discriminatorKey]; - /*! - * Register hooks for this model - * - * @param {Model} model - * @param {Schema} schema - */ + applyPlugins(discriminatorSchema, plugins, + { skipTopLevel: !applyPluginsToDiscriminators }, cacheKey); + } +}; - function applyHooks(model, schema, options) { - options = options || {}; +/***/ }), - const kareemOptions = { - useErrorHandlers: true, - numCallbackParams: 1, - nullResultByDefault: true, - contextParameter: true, - }; - const objToDecorate = options.decorateDoc ? model : model.prototype; - - model.$appliedHooks = true; - for (const key of Object.keys(schema.paths)) { - const type = schema.paths[key]; - let childModel = null; - if (type.$isSingleNested) { - childModel = type.caster; - } else if (type.$isMongooseDocumentArray) { - childModel = type.Constructor; - } else { - continue; - } +/***/ 5661: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (childModel.$appliedHooks) { - continue; - } +"use strict"; - applyHooks(childModel, type.schema, options); - if (childModel.discriminators != null) { - const keys = Object.keys(childModel.discriminators); - for (const key of keys) { - applyHooks( - childModel.discriminators[key], - childModel.discriminators[key].schema, - options - ); - } - } - } - // Built-in hooks rely on hooking internal functions in order to support - // promises and make it so that `doc.save.toString()` provides meaningful - // information. +const get = __nccwpck_require__(8730); - const middleware = schema.s.hooks - .filter((hook) => { - if (hook.name === "updateOne" || hook.name === "deleteOne") { - return !!hook["document"]; - } - if (hook.name === "remove" || hook.name === "init") { - return hook["document"] == null || !!hook["document"]; - } - if (hook.query != null || hook.document != null) { - return hook.document !== false; - } - return true; - }) - .filter((hook) => { - // If user has overwritten the method, don't apply built-in middleware - if (schema.methods[hook.name]) { - return !hook.fn[symbols.builtInMiddleware]; - } +module.exports = function applyWriteConcern(schema, options) { + const writeConcern = get(schema, 'options.writeConcern', {}); + if (Object.keys(writeConcern).length != 0) { + options.writeConcern = {}; + if (!('w' in options) && writeConcern.w != null) { + options.writeConcern.w = writeConcern.w; + } + if (!('j' in options) && writeConcern.j != null) { + options.writeConcern.j = writeConcern.j; + } + if (!('wtimeout' in options) && writeConcern.wtimeout != null) { + options.writeConcern.wtimeout = writeConcern.wtimeout; + } + } + else { + if (!('w' in options) && writeConcern.w != null) { + options.w = writeConcern.w; + } + if (!('j' in options) && writeConcern.j != null) { + options.j = writeConcern.j; + } + if (!('wtimeout' in options) && writeConcern.wtimeout != null) { + options.wtimeout = writeConcern.wtimeout; + } + } +}; - return true; - }); - model._middleware = middleware; +/***/ }), - objToDecorate.$__originalValidate = - objToDecorate.$__originalValidate || objToDecorate.$__validate; +/***/ 1119: +/***/ ((module) => { - for (const method of ["save", "validate", "remove", "deleteOne"]) { - const toWrap = - method === "validate" ? "$__originalValidate" : `$__${method}`; - const wrapped = middleware.createWrapper( - method, - objToDecorate[toWrap], - null, - kareemOptions - ); - objToDecorate[`$__${method}`] = wrapped; - } - objToDecorate.$__init = middleware.createWrapperSync( - "init", - objToDecorate.$__init, - null, - kareemOptions - ); +"use strict"; - // Support hooks for custom methods - const customMethods = Object.keys(schema.methods); - const customMethodOptions = Object.assign({}, kareemOptions, { - // Only use `checkForPromise` for custom methods, because mongoose - // query thunks are not as consistent as I would like about returning - // a nullish value rather than the query. If a query thunk returns - // a query, `checkForPromise` causes infinite recursion - checkForPromise: true, - }); - for (const method of customMethods) { - if (!middleware.hasHooks(method)) { - // Don't wrap if there are no hooks for the custom method to avoid - // surprises. Also, `createWrapper()` enforces consistent async, - // so wrapping a sync method would break it. - continue; - } - const originalMethod = objToDecorate[method]; - objToDecorate[method] = function () { - const args = Array.prototype.slice.call(arguments); - const cb = args.slice(-1).pop(); - const argsWithoutCallback = - typeof cb === "function" ? args.slice(0, args.length - 1) : args; - return promiseOrCallback( - cb, - (callback) => { - return this[`$__${method}`].apply( - this, - argsWithoutCallback.concat([callback]) - ); - }, - model.events - ); - }; - objToDecorate[`$__${method}`] = middleware.createWrapper( - method, - originalMethod, - null, - customMethodOptions - ); - } - } - /***/ - }, +/** + * For consistency's sake, we replace positional operator `$` and array filters + * `$[]` and `$[foo]` with `0` when looking up schema paths. + */ - /***/ 3543: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const get = __nccwpck_require__(8730); - - /*! - * Register methods for this model - * - * @param {Model} model - * @param {Schema} schema - */ - - module.exports = function applyMethods(model, schema) { - function apply(method, schema) { - Object.defineProperty(model.prototype, method, { - get: function () { - const h = {}; - for (const k in schema.methods[method]) { - h[k] = schema.methods[method][k].bind(this); - } - return h; - }, - configurable: true, - }); - } - for (const method of Object.keys(schema.methods)) { - const fn = schema.methods[method]; - if (schema.tree.hasOwnProperty(method)) { - throw new Error( - "You have a method and a property in your schema both " + - 'named "' + - method + - '"' - ); - } - if ( - schema.reserved[method] && - !get(schema, `methodOptions.${method}.suppressWarning`, false) - ) { - console.warn( - `mongoose: the method name "${method}" is used by mongoose ` + - "internally, overwriting it may cause bugs. If you're sure you know " + - "what you're doing, you can suppress this error by using " + - `\`schema.method('${method}', fn, { suppressWarning: true })\`.` - ); - } - if (typeof fn === "function") { - model.prototype[method] = fn; - } else { - apply(method, schema); - } - } +module.exports = function cleanPositionalOperators(path) { + return path. + replace(/\.\$(\[[^\]]*\])?(?=\.)/g, '.0'). + replace(/\.\$(\[[^\]]*\])?$/g, '.0'); +}; - // Recursively call `applyMethods()` on child schemas - model.$appliedMethods = true; - for (const key of Object.keys(schema.paths)) { - const type = schema.paths[key]; - if (type.$isSingleNested && !type.caster.$appliedMethods) { - applyMethods(type.caster, type.schema); - } - if ( - type.$isMongooseDocumentArray && - !type.Constructor.$appliedMethods - ) { - applyMethods(type.Constructor, type.schema); - } - } - }; +/***/ }), - /***/ - }, +/***/ 8373: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /***/ 3739: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +"use strict"; - const middlewareFunctions = __nccwpck_require__(7378).middlewareFunctions; - const promiseOrCallback = __nccwpck_require__(4046); - module.exports = function applyStaticHooks(model, hooks, statics) { - const kareemOptions = { - useErrorHandlers: true, - numCallbackParams: 1, - }; +const get = __nccwpck_require__(8730); +const helperIsObject = __nccwpck_require__(273); - hooks = hooks.filter((hook) => { - // If the custom static overwrites an existing query middleware, don't apply - // middleware to it by default. This avoids a potential backwards breaking - // change with plugins like `mongoose-delete` that use statics to overwrite - // built-in Mongoose functions. - if (middlewareFunctions.indexOf(hook.name) !== -1) { - return !!hook.model; - } - return hook.model !== false; - }); +/*! + * Gather all indexes defined in the schema, including single nested, + * document arrays, and embedded discriminators. + */ - model.$__insertMany = hooks.createWrapper( - "insertMany", - model.$__insertMany, - model, - kareemOptions - ); +module.exports = function getIndexes(schema) { + let indexes = []; + const schemaStack = new WeakMap(); + const indexTypes = schema.constructor.indexTypes; + const indexByName = new Map(); - for (const key of Object.keys(statics)) { - if (hooks.hasHooks(key)) { - const original = model[key]; - - model[key] = function () { - const numArgs = arguments.length; - const lastArg = numArgs > 0 ? arguments[numArgs - 1] : null; - const cb = typeof lastArg === "function" ? lastArg : null; - const args = Array.prototype.slice.call( - arguments, - 0, - cb == null ? numArgs : numArgs - 1 - ); - // Special case: can't use `Kareem#wrap()` because it doesn't currently - // support wrapped functions that return a promise. - return promiseOrCallback( - cb, - (callback) => { - hooks.execPre(key, model, args, function (err) { - if (err != null) { - return callback(err); - } + collectIndexes(schema); + return indexes; - let postCalled = 0; - const ret = original.apply(model, args.concat(post)); - if (ret != null && typeof ret.then === "function") { - ret.then( - (res) => post(null, res), - (err) => post(err) - ); - } + function collectIndexes(schema, prefix, baseSchema) { + // Ignore infinitely nested schemas, if we've already seen this schema + // along this path there must be a cycle + if (schemaStack.has(schema)) { + return; + } + schemaStack.set(schema, true); - function post(error, res) { - if (postCalled++ > 0) { - return; - } + prefix = prefix || ''; + const keys = Object.keys(schema.paths); - if (error != null) { - return callback(error); - } + for (const key of keys) { + const path = schema.paths[key]; + if (baseSchema != null && baseSchema.paths[key]) { + // If looking at an embedded discriminator schema, don't look at paths + // that the + continue; + } - hooks.execPost(key, model, [res], function (error) { - if (error != null) { - return callback(error); - } - callback(null, res); - }); - } - }); - }, - model.events - ); - }; + if (path.$isMongooseDocumentArray || path.$isSingleNested) { + if (get(path, 'options.excludeIndexes') !== true && + get(path, 'schemaOptions.excludeIndexes') !== true && + get(path, 'schema.options.excludeIndexes') !== true) { + collectIndexes(path.schema, prefix + key + '.'); + } + + if (path.schema.discriminators != null) { + const discriminators = path.schema.discriminators; + const discriminatorKeys = Object.keys(discriminators); + for (const discriminatorKey of discriminatorKeys) { + collectIndexes(discriminators[discriminatorKey], + prefix + key + '.', path.schema); } } - }; - /***/ - }, + // Retained to minimize risk of backwards breaking changes due to + // gh-6113 + if (path.$isMongooseDocumentArray) { + continue; + } + } - /***/ 5220: /***/ (module) => { - "use strict"; + const index = path._index || (path.caster && path.caster._index); - /*! - * Register statics for this model - * @param {Model} model - * @param {Schema} schema - */ - module.exports = function applyStatics(model, schema) { - for (const i in schema.statics) { - model[i] = schema.statics[i]; - } - }; + if (index !== false && index !== null && index !== undefined) { + const field = {}; + const isObject = helperIsObject(index); + const options = isObject ? index : {}; + const type = typeof index === 'string' ? index : + isObject ? index.type : + false; - /***/ - }, + if (type && indexTypes.indexOf(type) !== -1) { + field[prefix + key] = type; + } else if (options.text) { + field[prefix + key] = 'text'; + delete options.text; + } else { + const isDescendingIndex = Number(index) === -1; + field[prefix + key] = isDescendingIndex ? -1 : 1; + } - /***/ 4531: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const getDiscriminatorByValue = __nccwpck_require__(8689); - const applyTimestampsToChildren = __nccwpck_require__(1975); - const applyTimestampsToUpdate = __nccwpck_require__(1162); - const cast = __nccwpck_require__(8874); - const castUpdate = __nccwpck_require__(3303); - const setDefaultsOnInsert = __nccwpck_require__(5937); - - /*! - * Given a model and a bulkWrite op, return a thunk that handles casting and - * validating the individual op. - */ - - module.exports = function castBulkWrite(originalModel, op, options) { - const now = originalModel.base.now(); - - if (op["insertOne"]) { - return (callback) => { - const model = decideModelByObject( - originalModel, - op["insertOne"]["document"] - ); + delete options.type; + if (!('background' in options)) { + options.background = true; + } + if (schema.options.autoIndex != null) { + options._autoIndex = schema.options.autoIndex; + } - const doc = new model(op["insertOne"]["document"]); - if (model.schema.options.timestamps) { - doc.initializeTimestamps(); - } - if (options.session != null) { - doc.$session(options.session); - } - op["insertOne"]["document"] = doc; - op["insertOne"]["document"].validate( - { __noPromise: true }, - function (error) { - if (error) { - return callback(error, null); - } - callback(null); - } - ); - }; - } else if (op["updateOne"]) { - return (callback) => { - try { - if (!op["updateOne"]["filter"]) { - throw new Error("Must provide a filter object."); - } - if (!op["updateOne"]["update"]) { - throw new Error("Must provide an update object."); - } + const indexName = options && options.name; + if (typeof indexName === 'string') { + if (indexByName.has(indexName)) { + Object.assign(indexByName.get(indexName), field); + } else { + indexes.push([field, options]); + indexByName.set(indexName, field); + } + } else { + indexes.push([field, options]); + indexByName.set(indexName, field); + } + } + } - const model = decideModelByObject( - originalModel, - op["updateOne"]["filter"] - ); - const schema = model.schema; - const strict = - options.strict != null - ? options.strict - : model.schema.options.strict; - - _addDiscriminatorToObject(schema, op["updateOne"]["filter"]); - - if ( - model.schema.$timestamps != null && - op["updateOne"].timestamps !== false - ) { - const createdAt = model.schema.$timestamps.createdAt; - const updatedAt = model.schema.$timestamps.updatedAt; - applyTimestampsToUpdate( - now, - createdAt, - updatedAt, - op["updateOne"]["update"], - {} - ); - } + schemaStack.delete(schema); - applyTimestampsToChildren( - now, - op["updateOne"]["update"], - model.schema - ); + if (prefix) { + fixSubIndexPaths(schema, prefix); + } else { + schema._indexes.forEach(function(index) { + if (!('background' in index[1])) { + index[1].background = true; + } + }); + indexes = indexes.concat(schema._indexes); + } + } - if (op["updateOne"].setDefaultsOnInsert) { - setDefaultsOnInsert( - op["updateOne"]["filter"], - model.schema, - op["updateOne"]["update"], - { - setDefaultsOnInsert: true, - upsert: op["updateOne"].upsert, - } - ); - } + /*! + * Checks for indexes added to subdocs using Schema.index(). + * These indexes need their paths prefixed properly. + * + * schema._indexes = [ [indexObj, options], [indexObj, options] ..] + */ - op["updateOne"]["filter"] = cast( - model.schema, - op["updateOne"]["filter"], - { - strict: strict, - upsert: op["updateOne"].upsert, - } - ); + function fixSubIndexPaths(schema, prefix) { + const subindexes = schema._indexes; + const len = subindexes.length; + for (let i = 0; i < len; ++i) { + const indexObj = subindexes[i][0]; + const indexOptions = subindexes[i][1]; + const keys = Object.keys(indexObj); + const klen = keys.length; + const newindex = {}; - op["updateOne"]["update"] = castUpdate( - model.schema, - op["updateOne"]["update"], - { - strict: strict, - overwrite: false, - upsert: op["updateOne"].upsert, - }, - model, - op["updateOne"]["filter"] - ); - } catch (error) { - return callback(error, null); - } + // use forward iteration, order matters + for (let j = 0; j < klen; ++j) { + const key = keys[j]; + newindex[prefix + key] = indexObj[key]; + } - callback(null); - }; - } else if (op["updateMany"]) { - return (callback) => { - try { - if (!op["updateMany"]["filter"]) { - throw new Error("Must provide a filter object."); - } - if (!op["updateMany"]["update"]) { - throw new Error("Must provide an update object."); - } + const newIndexOptions = Object.assign({}, indexOptions); + if (indexOptions != null && indexOptions.partialFilterExpression != null) { + newIndexOptions.partialFilterExpression = {}; + const partialFilterExpression = indexOptions.partialFilterExpression; + for (const key of Object.keys(partialFilterExpression)) { + newIndexOptions.partialFilterExpression[prefix + key] = + partialFilterExpression[key]; + } + } - const model = decideModelByObject( - originalModel, - op["updateMany"]["filter"] - ); - const schema = model.schema; - const strict = - options.strict != null - ? options.strict - : model.schema.options.strict; - - if (op["updateMany"].setDefaultsOnInsert) { - setDefaultsOnInsert( - op["updateMany"]["filter"], - model.schema, - op["updateMany"]["update"], - { - setDefaultsOnInsert: true, - upsert: op["updateMany"].upsert, - } - ); - } + indexes.push([newindex, newIndexOptions]); + } + } +}; - if ( - model.schema.$timestamps != null && - op["updateMany"].timestamps !== false - ) { - const createdAt = model.schema.$timestamps.createdAt; - const updatedAt = model.schema.$timestamps.updatedAt; - applyTimestampsToUpdate( - now, - createdAt, - updatedAt, - op["updateMany"]["update"], - {} - ); - } - applyTimestampsToChildren( - now, - op["updateMany"]["update"], - model.schema - ); +/***/ }), - _addDiscriminatorToObject(schema, op["updateMany"]["filter"]); +/***/ 6000: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - op["updateMany"]["filter"] = cast( - model.schema, - op["updateMany"]["filter"], - { - strict: strict, - upsert: op["updateMany"].upsert, - } - ); +"use strict"; - op["updateMany"]["update"] = castUpdate( - model.schema, - op["updateMany"]["update"], - { - strict: strict, - overwrite: false, - upsert: op["updateMany"].upsert, - }, - model, - op["updateMany"]["filter"] - ); - } catch (error) { - return callback(error, null); - } - callback(null); - }; - } else if (op["replaceOne"]) { - return (callback) => { - const model = decideModelByObject( - originalModel, - op["replaceOne"]["filter"] - ); - const schema = model.schema; - const strict = - options.strict != null - ? options.strict - : model.schema.options.strict; +const get = __nccwpck_require__(8730); - _addDiscriminatorToObject(schema, op["replaceOne"]["filter"]); - try { - op["replaceOne"]["filter"] = cast( - model.schema, - op["replaceOne"]["filter"], - { - strict: strict, - upsert: op["replaceOne"].upsert, - } - ); - } catch (error) { - return callback(error, null); - } +module.exports = function getKeysInSchemaOrder(schema, val, path) { + const schemaKeys = path != null ? Object.keys(get(schema.tree, path, {})) : Object.keys(schema.tree); + const valKeys = new Set(Object.keys(val)); - // set `skipId`, otherwise we get "_id field cannot be changed" - const doc = new model( - op["replaceOne"]["replacement"], - strict, - true - ); - if (model.schema.options.timestamps) { - doc.initializeTimestamps(); - } - if (options.session != null) { - doc.$session(options.session); - } - op["replaceOne"]["replacement"] = doc; + let keys; + if (valKeys.size > 1) { + keys = new Set(); + for (const key of schemaKeys) { + if (valKeys.has(key)) { + keys.add(key); + } + } + for (const key of valKeys) { + if (!keys.has(key)) { + keys.add(key); + } + } + keys = Array.from(keys); + } else { + keys = Array.from(valKeys); + } - op["replaceOne"]["replacement"].validate( - { __noPromise: true }, - function (error) { - if (error) { - return callback(error, null); - } - op["replaceOne"]["replacement"] = - op["replaceOne"]["replacement"].toBSON(); - callback(null); - } - ); - }; - } else if (op["deleteOne"]) { - return (callback) => { - const model = decideModelByObject( - originalModel, - op["deleteOne"]["filter"] - ); - const schema = model.schema; + return keys; +}; - _addDiscriminatorToObject(schema, op["deleteOne"]["filter"]); +/***/ }), - try { - op["deleteOne"]["filter"] = cast( - model.schema, - op["deleteOne"]["filter"] - ); - } catch (error) { - return callback(error, null); - } +/***/ 7453: +/***/ ((module) => { - callback(null); - }; - } else if (op["deleteMany"]) { - return (callback) => { - const model = decideModelByObject( - originalModel, - op["deleteMany"]["filter"] - ); - const schema = model.schema; +"use strict"; - _addDiscriminatorToObject(schema, op["deleteMany"]["filter"]); - try { - op["deleteMany"]["filter"] = cast( - model.schema, - op["deleteMany"]["filter"] - ); - } catch (error) { - return callback(error, null); - } +/*! + * Behaves like `Schema#path()`, except for it also digs into arrays without + * needing to put `.0.`, so `getPath(schema, 'docArr.elProp')` works. + */ - callback(null); - }; - } else { - return (callback) => { - callback(new Error("Invalid op passed to `bulkWrite()`"), null); - }; - } - }; +module.exports = function getPath(schema, path) { + let schematype = schema.path(path); + if (schematype != null) { + return schematype; + } - function _addDiscriminatorToObject(schema, obj) { - if (schema == null) { - return; - } - if ( - schema.discriminatorMapping && - !schema.discriminatorMapping.isRoot - ) { - obj[schema.discriminatorMapping.key] = - schema.discriminatorMapping.value; - } - } + const pieces = path.split('.'); + let cur = ''; + let isArray = false; - /*! - * gets discriminator model if discriminator key is present in object - */ + for (const piece of pieces) { + if (/^\d+$/.test(piece) && isArray) { + continue; + } + cur = cur.length === 0 ? piece : cur + '.' + piece; - function decideModelByObject(model, object) { - const discriminatorKey = model.schema.options.discriminatorKey; - if (object != null && object.hasOwnProperty(discriminatorKey)) { - model = - getDiscriminatorByValue( - model.discriminators, - object[discriminatorKey] - ) || model; - } - return model; + schematype = schema.path(cur); + if (schematype != null && schematype.schema) { + schema = schematype.schema; + cur = ''; + if (schematype.$isMongooseDocumentArray) { + isArray = true; } + } + } - /***/ - }, + return schematype; +}; - /***/ 1462: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Mixed = __nccwpck_require__(7495); - const defineKey = __nccwpck_require__(2096) /* .defineKey */.c; - const get = __nccwpck_require__(8730); - const utils = __nccwpck_require__(9232); - - const CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = { - toJSON: true, - toObject: true, - _id: true, - id: true, - }; +/***/ }), - /*! - * ignore - */ +/***/ 8965: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - module.exports = function discriminator( - model, - name, - schema, - tiedValue, - applyPlugins - ) { - if (!(schema && schema.instanceOfSchema)) { - throw new Error("You must pass a valid discriminator Schema"); - } +"use strict"; - if ( - model.schema.discriminatorMapping && - !model.schema.discriminatorMapping.isRoot - ) { - throw new Error( - 'Discriminator "' + - name + - '" can only be a discriminator of the root model' - ); - } - if (applyPlugins) { - const applyPluginsToDiscriminators = get( - model.base, - "options.applyPluginsToDiscriminators", - false - ); - // Even if `applyPluginsToDiscriminators` isn't set, we should still apply - // global plugins to schemas embedded in the discriminator schema (gh-7370) - model.base._applyPlugins(schema, { - skipTopLevel: !applyPluginsToDiscriminators, - }); - } +const addAutoId = __nccwpck_require__(9115); + +module.exports = function handleIdOption(schema, options) { + if (options == null || options._id == null) { + return schema; + } - const key = model.schema.options.discriminatorKey; + schema = schema.clone(); + if (!options._id) { + schema.remove('_id'); + schema.options._id = false; + } else if (!schema.paths['_id']) { + addAutoId(schema); + schema.options._id = true; + } - const existingPath = model.schema.path(key); - if (existingPath != null) { - if (!utils.hasUserDefinedProperty(existingPath.options, "select")) { - existingPath.options.select = true; - } - existingPath.options.$skipDiscriminatorCheck = true; - } else { - const baseSchemaAddition = {}; - baseSchemaAddition[key] = { - default: void 0, - select: true, - $skipDiscriminatorCheck: true, - }; - baseSchemaAddition[key][model.schema.options.typeKey] = String; - model.schema.add(baseSchemaAddition); - defineKey( - key, - null, - model.prototype, - null, - [key], - model.schema.options - ); - } + return schema; +}; - if ( - schema.path(key) && - schema.path(key).options.$skipDiscriminatorCheck !== true - ) { - throw new Error( - 'Discriminator "' + - name + - '" cannot have field with name "' + - key + - '"' - ); - } +/***/ }), - let value = name; - if ( - (typeof tiedValue === "string" && tiedValue.length) || - tiedValue != null - ) { - value = tiedValue; - } - - function merge(schema, baseSchema) { - // Retain original schema before merging base schema - schema._baseSchema = baseSchema; - if ( - baseSchema.paths._id && - baseSchema.paths._id.options && - !baseSchema.paths._id.options.auto - ) { - schema.remove("_id"); - } +/***/ 2850: +/***/ ((module) => { - // Find conflicting paths: if something is a path in the base schema - // and a nested path in the child schema, overwrite the base schema path. - // See gh-6076 - const baseSchemaPaths = Object.keys(baseSchema.paths); - const conflictingPaths = []; +"use strict"; - for (const path of baseSchemaPaths) { - if (schema.nested[path]) { - conflictingPaths.push(path); - continue; - } - if (path.indexOf(".") === -1) { - continue; - } - const sp = path.split(".").slice(0, -1); - let cur = ""; - for (const piece of sp) { - cur += (cur.length ? "." : "") + piece; - if ( - schema.paths[cur] instanceof Mixed || - schema.singleNestedPaths[cur] instanceof Mixed - ) { - conflictingPaths.push(path); - } - } - } +module.exports = handleTimestampOption; - utils.merge(schema, baseSchema, { - isDiscriminatorSchemaMerge: true, - omit: { discriminators: true, base: true }, - omitNested: conflictingPaths.reduce((cur, path) => { - cur["tree." + path] = true; - return cur; - }, {}), - }); +/*! + * ignore + */ - // Clean up conflicting paths _after_ merging re: gh-6076 - for (const conflictingPath of conflictingPaths) { - delete schema.paths[conflictingPath]; - } +function handleTimestampOption(arg, prop) { + if (arg == null) { + return null; + } - // Rebuild schema models because schemas may have been merged re: #7884 - schema.childSchemas.forEach((obj) => { - obj.model.prototype.$__setSchema(obj.schema); - }); + if (typeof arg === 'boolean') { + return prop; + } + if (typeof arg[prop] === 'boolean') { + return arg[prop] ? prop : null; + } + if (!(prop in arg)) { + return prop; + } + return arg[prop]; +} - const obj = {}; - obj[key] = { - default: value, - select: true, - set: function (newName) { - if ( - newName === value || - (Array.isArray(value) && utils.deepEqual(newName, value)) - ) { - return value; - } - throw new Error("Can't set discriminator key \"" + key + '"'); - }, - $skipDiscriminatorCheck: true, - }; - obj[key][schema.options.typeKey] = existingPath - ? existingPath.options[schema.options.typeKey] - : String; - schema.add(obj); +/***/ }), - schema.discriminatorMapping = { - key: key, - value: value, - isRoot: false, - }; +/***/ 895: +/***/ ((module) => { - if (baseSchema.options.collection) { - schema.options.collection = baseSchema.options.collection; - } +"use strict"; - const toJSON = schema.options.toJSON; - const toObject = schema.options.toObject; - const _id = schema.options._id; - const id = schema.options.id; - - const keys = Object.keys(schema.options); - schema.options.discriminatorKey = baseSchema.options.discriminatorKey; - - for (const _key of keys) { - if (!CUSTOMIZABLE_DISCRIMINATOR_OPTIONS[_key]) { - // Special case: compiling a model sets `pluralization = true` by default. Avoid throwing an error - // for that case. See gh-9238 - if ( - _key === "pluralization" && - schema.options[_key] == true && - baseSchema.options[_key] == null - ) { - continue; - } - if ( - !utils.deepEqual(schema.options[_key], baseSchema.options[_key]) - ) { - throw new Error( - "Can't customize discriminator option " + - _key + - " (can only modify " + - Object.keys(CUSTOMIZABLE_DISCRIMINATOR_OPTIONS).join(", ") + - ")" - ); - } - } - } - schema.options = utils.clone(baseSchema.options); - if (toJSON) schema.options.toJSON = toJSON; - if (toObject) schema.options.toObject = toObject; - if (typeof _id !== "undefined") { - schema.options._id = _id; - } - schema.options.id = id; - schema.s.hooks = model.schema.s.hooks.merge(schema.s.hooks); +/*! + * ignore + */ - schema.plugins = Array.prototype.slice.call(baseSchema.plugins); - schema.callQueue = baseSchema.callQueue.concat(schema.callQueue); - delete schema._requiredpaths; // reset just in case Schema#requiredPaths() was called on either schema - } +module.exports = function addIdGetter(schema) { + // ensure the documents receive an id getter unless disabled + const autoIdGetter = !schema.paths['id'] && + schema.paths['_id'] && + schema.options.id; + if (!autoIdGetter) { + return schema; + } - // merges base schema into new discriminator schema and sets new type field. - merge(schema, model.schema); + schema.virtual('id').get(idGetter); - if (!model.discriminators) { - model.discriminators = {}; - } + return schema; +}; - if (!model.schema.discriminatorMapping) { - model.schema.discriminatorMapping = { - key: key, - value: null, - isRoot: true, - }; - } - if (!model.schema.discriminators) { - model.schema.discriminators = {}; - } +/*! + * Returns this documents _id cast to a string. + */ - model.schema.discriminators[name] = schema; +function idGetter() { + if (this._id != null) { + return String(this._id); + } - if (model.discriminators[name]) { - throw new Error( - 'Discriminator with name "' + name + '" already exists' - ); - } + return null; +} - return schema; - }; - /***/ - }, +/***/ }), - /***/ 7716: /***/ (module) => { - "use strict"; +/***/ 2830: +/***/ ((module) => { - module.exports = parallelLimit; +"use strict"; - /*! - * ignore - */ - function parallelLimit(fns, limit, callback) { - let numInProgress = 0; - let numFinished = 0; - let error = null; +module.exports = function merge(s1, s2, skipConflictingPaths) { + const paths = Object.keys(s2.tree); + const pathsToAdd = {}; + for (const key of paths) { + if (skipConflictingPaths && (s1.paths[key] || s1.nested[key] || s1.singleNestedPaths[key])) { + continue; + } + pathsToAdd[key] = s2.tree[key]; + } + s1.add(pathsToAdd); - if (limit <= 0) { - throw new Error("Limit must be positive"); - } + s1.callQueue = s1.callQueue.concat(s2.callQueue); + s1.method(s2.methods); + s1.static(s2.statics); - if (fns.length === 0) { - return callback(null, []); - } + for (const query in s2.query) { + s1.query[query] = s2.query[query]; + } - for (let i = 0; i < fns.length && i < limit; ++i) { - _start(); - } + for (const virtual in s2.virtuals) { + s1.virtuals[virtual] = s2.virtuals[virtual].clone(); + } - function _start() { - fns[numFinished + numInProgress](_done(numFinished + numInProgress)); - ++numInProgress; - } + s1.s.hooks.merge(s2.s.hooks, false); +}; - const results = []; - function _done(index) { - return (err, res) => { - --numInProgress; - ++numFinished; +/***/ }), - if (error != null) { - return; - } - if (err != null) { - error = err; - return callback(error); - } +/***/ 773: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - results[index] = res; +"use strict"; - if (numFinished === fns.length) { - return callback(null, results); - } else if (numFinished + numInProgress < fns.length) { - _start(); - } - }; - } - } - /***/ - }, +const StrictModeError = __nccwpck_require__(5328); - /***/ 8123: /***/ (module) => { - "use strict"; +/*! + * ignore + */ - module.exports = function parentPaths(path) { - const pieces = path.split("."); - let cur = ""; - const ret = []; - for (let i = 0; i < pieces.length; ++i) { - cur += (cur.length > 0 ? "." : "") + pieces[i]; - ret.push(cur); - } +module.exports = function(schematype) { + if (schematype.$immutable) { + schematype.$immutableSetter = createImmutableSetter(schematype.path, + schematype.options.immutable); + schematype.set(schematype.$immutableSetter); + } else if (schematype.$immutableSetter) { + schematype.setters = schematype.setters. + filter(fn => fn !== schematype.$immutableSetter); + delete schematype.$immutableSetter; + } +}; - return ret; - }; +function createImmutableSetter(path, immutable) { + return function immutableSetter(v) { + if (this == null || this.$__ == null) { + return v; + } + if (this.isNew) { + return v; + } - /***/ - }, + const _immutable = typeof immutable === 'function' ? + immutable.call(this, this) : + immutable; + if (!_immutable) { + return v; + } - /***/ 9152: /***/ (module) => { - "use strict"; + const _value = this.$__.priorDoc != null ? + this.$__.priorDoc.$__getValue(path) : + this.$__getValue(path); + if (this.$__.strictMode === 'throw' && v !== _value) { + throw new StrictModeError(path, 'Path `' + path + '` is immutable ' + + 'and strict mode is set to throw.', true); + } - module.exports = function setDottedPath(obj, path, val) { - const parts = path.split("."); - let cur = obj; - for (const part of parts.slice(0, -1)) { - if (cur[part] == null) { - cur[part] = {}; - } + return _value; + }; +} - cur = cur[part]; - } - const last = parts[parts.length - 1]; - cur[last] = val; - }; +/***/ }), - /***/ - }, +/***/ 5937: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /***/ 694: /***/ (module) => { - "use strict"; +"use strict"; - module.exports = function SkipPopulateValue(val) { - if (!(this instanceof SkipPopulateValue)) { - return new SkipPopulateValue(val); - } +const modifiedPaths = __nccwpck_require__(3719)/* .modifiedPaths */ .M; +const get = __nccwpck_require__(8730); - this.val = val; - return this; - }; +/** + * Applies defaults to update and findOneAndUpdate operations. + * + * @param {Object} filter + * @param {Schema} schema + * @param {Object} castedDoc + * @param {Object} options + * @method setDefaultsOnInsert + * @api private + */ - /***/ - }, +module.exports = function(filter, schema, castedDoc, options) { + options = options || {}; - /***/ 8490: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const leanPopulateMap = __nccwpck_require__(914); - const modelSymbol = __nccwpck_require__(3240).modelSymbol; - const utils = __nccwpck_require__(9232); - - module.exports = assignRawDocsToIdStructure; - - /*! - * Assign `vals` returned by mongo query to the `rawIds` - * structure returned from utils.getVals() honoring - * query sort order if specified by user. - * - * This can be optimized. - * - * Rules: - * - * if the value of the path is not an array, use findOne rules, else find. - * for findOne the results are assigned directly to doc path (including null results). - * for find, if user specified sort order, results are assigned directly - * else documents are put back in original order of array if found in results - * - * @param {Array} rawIds - * @param {Array} vals - * @param {Boolean} sort - * @api private - */ - - function assignRawDocsToIdStructure( - rawIds, - resultDocs, - resultOrder, - options, - recursed - ) { - // honor user specified sort order - const newOrder = []; - const sorting = options.sort && rawIds.length > 1; - const nullIfNotFound = options.$nullIfNotFound; - let doc; - let sid; - let id; - - for (let i = 0; i < rawIds.length; ++i) { - id = rawIds[i]; - - if (Array.isArray(id)) { - // handle [ [id0, id2], [id3] ] - assignRawDocsToIdStructure( - id, - resultDocs, - resultOrder, - options, - true - ); - newOrder.push(id); - continue; - } + const shouldSetDefaultsOnInsert = + options.setDefaultsOnInsert != null ? + options.setDefaultsOnInsert : + schema.base.options.setDefaultsOnInsert; - if (id === null && !sorting) { - // keep nulls for findOne unless sorting, which always - // removes them (backward compat) - newOrder.push(id); - continue; - } + if (!options.upsert || shouldSetDefaultsOnInsert === false) { + return castedDoc; + } - sid = String(id); + const keys = Object.keys(castedDoc || {}); + const updatedKeys = {}; + const updatedValues = {}; + const numKeys = keys.length; + const modified = {}; - doc = resultDocs[sid]; - // If user wants separate copies of same doc, use this option - if (options.clone && doc != null) { - if (options.lean) { - const _model = leanPopulateMap.get(doc); - doc = utils.clone(doc); - leanPopulateMap.set(doc, _model); - } else { - doc = doc.constructor.hydrate(doc._doc); - } - } + let hasDollarUpdate = false; - if (recursed) { - if (doc) { - if (sorting) { - const _resultOrder = resultOrder[sid]; - if ( - Array.isArray(_resultOrder) && - Array.isArray(doc) && - _resultOrder.length === doc.length - ) { - newOrder.push(doc); - } else { - newOrder[_resultOrder] = doc; - } - } else { - newOrder.push(doc); - } - } else if (id != null && id[modelSymbol] != null) { - newOrder.push(id); - } else { - newOrder.push( - options.retainNullValues || nullIfNotFound ? null : id - ); - } - } else { - // apply findOne behavior - if document in results, assign, else assign null - newOrder[i] = doc || null; - } - } + for (let i = 0; i < numKeys; ++i) { + if (keys[i].startsWith('$')) { + modifiedPaths(castedDoc[keys[i]], '', modified); + hasDollarUpdate = true; + } + } - rawIds.length = 0; - if (newOrder.length) { - // reassign the documents based on corrected order + if (!hasDollarUpdate) { + modifiedPaths(castedDoc, '', modified); + } - // forEach skips over sparse entries in arrays so we - // can safely use this to our advantage dealing with sorted - // result sets too. - newOrder.forEach(function (doc, i) { - rawIds[i] = doc; - }); + const paths = Object.keys(filter); + const numPaths = paths.length; + for (let i = 0; i < numPaths; ++i) { + const path = paths[i]; + const condition = filter[path]; + if (condition && typeof condition === 'object') { + const conditionKeys = Object.keys(condition); + const numConditionKeys = conditionKeys.length; + let hasDollarKey = false; + for (let j = 0; j < numConditionKeys; ++j) { + if (conditionKeys[j].startsWith('$')) { + hasDollarKey = true; + break; } } + if (hasDollarKey) { + continue; + } + } + updatedKeys[path] = true; + modified[path] = true; + } - /***/ - }, - - /***/ 6414: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const SkipPopulateValue = __nccwpck_require__(694); - const assignRawDocsToIdStructure = __nccwpck_require__(8490); - const get = __nccwpck_require__(8730); - const getVirtual = __nccwpck_require__(6371); - const leanPopulateMap = __nccwpck_require__(914); - const lookupLocalFields = __nccwpck_require__(1296); - const mpath = __nccwpck_require__(8586); - const sift = __nccwpck_require__(2865).default; - const utils = __nccwpck_require__(9232); - - module.exports = function assignVals(o) { - // Options that aren't explicitly listed in `populateOptions` - const userOptions = Object.assign( - {}, - get(o, "allOptions.options.options"), - get(o, "allOptions.options") - ); - // `o.options` contains options explicitly listed in `populateOptions`, like - // `match` and `limit`. - const populateOptions = Object.assign({}, o.options, userOptions, { - justOne: o.justOne, - }); - populateOptions.$nullIfNotFound = o.isVirtual; - const populatedModel = o.populatedModel; - - const originalIds = [].concat(o.rawIds); - - // replace the original ids in our intermediate _ids structure - // with the documents found by query - o.allIds = [].concat(o.allIds); - assignRawDocsToIdStructure( - o.rawIds, - o.rawDocs, - o.rawOrder, - populateOptions - ); + if (options && options.overwrite && !hasDollarUpdate) { + // Defaults will be set later, since we're overwriting we'll cast + // the whole update to a document + return castedDoc; + } - // now update the original documents being populated using the - // result structure that contains real documents. - const docs = o.docs; - const rawIds = o.rawIds; - const options = o.options; - const count = o.count && o.isVirtual; - let i; - - function setValue(val) { - if (count) { - return val; - } - if (val instanceof SkipPopulateValue) { - return val.val; - } + schema.eachPath(function(path, schemaType) { + // Skip single nested paths if underneath a map + if (schemaType.path === '_id' && schemaType.options.auto) { + return; + } + const def = schemaType.getDefault(null, true); + if (!isModified(modified, path) && typeof def !== 'undefined') { + castedDoc = castedDoc || {}; + castedDoc.$setOnInsert = castedDoc.$setOnInsert || {}; + if (get(castedDoc, path) == null) { + castedDoc.$setOnInsert[path] = def; + } + updatedValues[path] = def; + } + }); - const _allIds = o.allIds[i]; - - if (o.justOne === true && Array.isArray(val)) { - // Might be an embedded discriminator (re: gh-9244) with multiple models, so make sure to pick the right - // model before assigning. - const ret = []; - for (const doc of val) { - const _docPopulatedModel = leanPopulateMap.get(doc); - if ( - _docPopulatedModel == null || - _docPopulatedModel === populatedModel - ) { - ret.push(doc); - } - } - // Since we don't want to have to create a new mongoosearray, make sure to - // modify the array in place - while (val.length > ret.length) { - Array.prototype.pop.apply(val, []); - } - for (let i = 0; i < ret.length; ++i) { - val[i] = ret[i]; - } + return castedDoc; +}; - return valueFilter(val[0], options, populateOptions, _allIds); - } else if (o.justOne === false && !Array.isArray(val)) { - return valueFilter([val], options, populateOptions, _allIds); - } - return valueFilter(val, options, populateOptions, _allIds); - } +function isModified(modified, path) { + if (modified[path]) { + return true; + } + const sp = path.split('.'); + let cur = sp[0]; + for (let i = 1; i < sp.length; ++i) { + if (modified[cur]) { + return true; + } + cur += '.' + sp[i]; + } + return false; +} - for (i = 0; i < docs.length; ++i) { - const _path = o.path.endsWith(".$*") ? o.path.slice(0, -3) : o.path; - const existingVal = mpath.get(_path, docs[i], lookupLocalFields); - if ( - existingVal == null && - !getVirtual(o.originalModel.schema, _path) - ) { - continue; - } - let valueToSet; - if (count) { - valueToSet = numDocs(rawIds[i]); - } else if (Array.isArray(o.match)) { - valueToSet = Array.isArray(rawIds[i]) - ? rawIds[i].filter(sift(o.match[i])) - : [rawIds[i]].filter(sift(o.match[i]))[0]; - } else { - valueToSet = rawIds[i]; - } +/***/ }), - // If we're populating a map, the existing value will be an object, so - // we need to transform again - const originalSchema = o.originalModel.schema; - const isDoc = get(docs[i], "$__", null) != null; - let isMap = isDoc - ? existingVal instanceof Map - : utils.isPOJO(existingVal); - // If we pass the first check, also make sure the local field's schematype - // is map (re: gh-6460) - isMap = - isMap && get(originalSchema._getSchema(_path), "$isSchemaMap"); - if (!o.isVirtual && isMap) { - const _keys = - existingVal instanceof Map - ? Array.from(existingVal.keys()) - : Object.keys(existingVal); - valueToSet = valueToSet.reduce((cur, v, i) => { - cur.set(_keys[i], v); - return cur; - }, new Map()); - } +/***/ 6786: +/***/ ((module) => { - if (isDoc && Array.isArray(valueToSet)) { - for (const val of valueToSet) { - if (val != null && val.$__ != null) { - val.$__.parent = docs[i]; - } - } - } else if (isDoc && valueToSet != null && valueToSet.$__ != null) { - valueToSet.$__.parent = docs[i]; - } +"use strict"; - if (o.isVirtual && isDoc) { - docs[i].populated( - _path, - o.justOne ? originalIds[0] : originalIds, - o.allOptions - ); - // If virtual populate and doc is already init-ed, need to walk through - // the actual doc to set rather than setting `_doc` directly - mpath.set(_path, valueToSet, docs[i], setValue); - continue; - } - const parts = _path.split("."); - let cur = docs[i]; - const curPath = parts[0]; - for (let j = 0; j < parts.length - 1; ++j) { - // If we get to an array with a dotted path, like `arr.foo`, don't set - // `foo` on the array. - if (Array.isArray(cur) && !utils.isArrayIndex(parts[j])) { - break; - } +module.exports = new Set(['__proto__', 'constructor', 'prototype']); - if (parts[j] === "$*") { - break; - } +/***/ }), - if (cur[parts[j]] == null) { - // If nothing to set, avoid creating an unnecessary array. Otherwise - // we'll end up with a single doc in the array with only defaults. - // See gh-8342, gh-8455 - const schematype = originalSchema._getSchema(curPath); - if ( - valueToSet == null && - schematype != null && - schematype.$isMongooseArray - ) { - break; - } - cur[parts[j]] = {}; - } - cur = cur[parts[j]]; - // If the property in MongoDB is a primitive, we won't be able to populate - // the nested path, so skip it. See gh-7545 - if (typeof cur !== "object") { - break; - } - } - if (docs[i].$__) { - docs[i].populated(_path, o.allIds[i], o.allOptions); - } +/***/ 3240: +/***/ ((__unused_webpack_module, exports) => { - // If lean, need to check that each individual virtual respects - // `justOne`, because you may have a populated virtual with `justOne` - // underneath an array. See gh-6867 - mpath.set( - _path, - valueToSet, - docs[i], - lookupLocalFields, - setValue, - false - ); - } - }; +"use strict"; - function numDocs(v) { - if (Array.isArray(v)) { - // If setting underneath an array of populated subdocs, we may have an - // array of arrays. See gh-7573 - if (v.some((el) => Array.isArray(el))) { - return v.map((el) => numDocs(el)); - } - return v.length; - } - return v == null ? 0 : 1; - } - - /*! - * 1) Apply backwards compatible find/findOne behavior to sub documents - * - * find logic: - * a) filter out non-documents - * b) remove _id from sub docs when user specified - * - * findOne - * a) if no doc found, set to null - * b) remove _id from sub docs when user specified - * - * 2) Remove _ids when specified by users query. - * - * background: - * _ids are left in the query even when user excludes them so - * that population mapping can occur. - */ - - function valueFilter(val, assignmentOpts, populateOptions, allIds) { - const userSpecifiedTransform = - typeof populateOptions.transform === "function"; - const transform = userSpecifiedTransform - ? populateOptions.transform - : noop; - if (Array.isArray(val)) { - // find logic - const ret = []; - const numValues = val.length; - for (let i = 0; i < numValues; ++i) { - let subdoc = val[i]; - const _allIds = Array.isArray(allIds) ? allIds[i] : allIds; - if ( - !isPopulatedObject(subdoc) && - (!populateOptions.retainNullValues || subdoc != null) && - !userSpecifiedTransform - ) { - continue; - } else if (userSpecifiedTransform) { - subdoc = transform( - isPopulatedObject(subdoc) ? subdoc : null, - _allIds - ); - } - maybeRemoveId(subdoc, assignmentOpts); - ret.push(subdoc); - if ( - assignmentOpts.originalLimit && - ret.length >= assignmentOpts.originalLimit - ) { - break; - } - } - // Since we don't want to have to create a new mongoosearray, make sure to - // modify the array in place - while (val.length > ret.length) { - Array.prototype.pop.apply(val, []); - } - for (let i = 0; i < ret.length; ++i) { - val[i] = ret[i]; - } - return val; - } +exports.arrayAtomicsBackupSymbol = Symbol('mongoose#Array#atomicsBackup'); +exports.arrayAtomicsSymbol = Symbol('mongoose#Array#_atomics'); +exports.arrayParentSymbol = Symbol('mongoose#Array#_parent'); +exports.arrayPathSymbol = Symbol('mongoose#Array#_path'); +exports.arraySchemaSymbol = Symbol('mongoose#Array#_schema'); +exports.documentArrayParent = Symbol('mongoose:documentArrayParent'); +exports.documentIsSelected = Symbol('mongoose#Document#isSelected'); +exports.documentIsModified = Symbol('mongoose#Document#isModified'); +exports.documentModifiedPaths = Symbol('mongoose#Document#modifiedPaths'); +exports.documentSchemaSymbol = Symbol('mongoose#Document#schema'); +exports.getSymbol = Symbol('mongoose#Document#get'); +exports.modelSymbol = Symbol('mongoose#Model'); +exports.objectIdSymbol = Symbol('mongoose#ObjectId'); +exports.populateModelSymbol = Symbol('mongoose.PopulateOptions#Model'); +exports.schemaTypeSymbol = Symbol('mongoose#schemaType'); +exports.sessionNewDocuments = Symbol('mongoose:ClientSession#newDocuments'); +exports.scopeSymbol = Symbol('mongoose#Document#scope'); +exports.validatorErrorSymbol = Symbol('mongoose:validatorError'); - // findOne - if (isPopulatedObject(val) || utils.isPOJO(val)) { - maybeRemoveId(val, assignmentOpts); - return transform(val, allIds); - } - if (val instanceof Map) { - return val; - } +/***/ }), - if (populateOptions.justOne === false) { - return []; - } +/***/ 82: +/***/ ((__unused_webpack_module, exports) => { - return val == null ? transform(val, allIds) : transform(null, allIds); - } +"use strict"; - /*! - * Remove _id from `subdoc` if user specified "lean" query option - */ - function maybeRemoveId(subdoc, assignmentOpts) { - if (subdoc != null && assignmentOpts.excludeId) { - if (typeof subdoc.$__setValue === "function") { - delete subdoc._doc._id; - } else { - delete subdoc._id; - } - } - } +exports.i = setTimeout; - /*! - * Determine if `obj` is something we can set a populated path to. Can be a - * document, a lean document, or an array/map that contains docs. - */ +/***/ }), - function isPopulatedObject(obj) { - if (obj == null) { - return false; - } +/***/ 3151: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return ( - Array.isArray(obj) || - obj.$isMongooseMap || - obj.$__ != null || - leanPopulateMap.has(obj) - ); - } +"use strict"; - function noop(v) { - return v; - } - /***/ - }, +const applyTimestampsToChildren = __nccwpck_require__(1975); +const applyTimestampsToUpdate = __nccwpck_require__(1162); +const get = __nccwpck_require__(8730); +const handleTimestampOption = __nccwpck_require__(2850); +const symbols = __nccwpck_require__(1205); - /***/ 5138: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const SkipPopulateValue = __nccwpck_require__(694); - const parentPaths = __nccwpck_require__(8123); - - module.exports = function createPopulateQueryFilter( - ids, - _match, - _foreignField, - model, - skipInvalidIds - ) { - const match = _formatMatch(_match); - - if (_foreignField.size === 1) { - const foreignField = Array.from(_foreignField)[0]; - const foreignSchemaType = model.schema.path(foreignField); - if (foreignField !== "_id" || !match["_id"]) { - ids = _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds); - match[foreignField] = { $in: ids }; - } +module.exports = function setupTimestamps(schema, timestamps) { + const childHasTimestamp = schema.childSchemas.find(withTimestamp); + function withTimestamp(s) { + const ts = s.schema.options.timestamps; + return !!ts; + } - const _parentPaths = parentPaths(foreignField); - for (let i = 0; i < _parentPaths.length - 1; ++i) { - const cur = _parentPaths[i]; - if (match[cur] != null && match[cur].$elemMatch != null) { - match[cur].$elemMatch[foreignField.slice(cur.length + 1)] = { - $in: ids, - }; - delete match[foreignField]; - break; - } - } - } else { - const $or = []; - if (Array.isArray(match.$or)) { - match.$and = [{ $or: match.$or }, { $or: $or }]; - delete match.$or; - } else { - match.$or = $or; - } - for (const foreignField of _foreignField) { - if (foreignField !== "_id" || !match["_id"]) { - const foreignSchemaType = model.schema.path(foreignField); - ids = _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds); - $or.push({ [foreignField]: { $in: ids } }); - } - } - } + if (!timestamps && !childHasTimestamp) { + return; + } - return match; - }; + const createdAt = handleTimestampOption(timestamps, 'createdAt'); + const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); + const currentTime = timestamps != null && timestamps.hasOwnProperty('currentTime') ? + timestamps.currentTime : + null; + const schemaAdditions = {}; - /*! - * Optionally filter out invalid ids that don't conform to foreign field's schema - * to avoid cast errors (gh-7706) - */ + schema.$timestamps = { createdAt: createdAt, updatedAt: updatedAt }; - function _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds) { - ids = ids.filter((v) => !(v instanceof SkipPopulateValue)); - if (!skipInvalidIds) { - return ids; - } - return ids.filter((id) => { - try { - foreignSchemaType.cast(id); - return true; - } catch (err) { - return false; - } - }); - } + if (updatedAt && !schema.paths[updatedAt]) { + schemaAdditions[updatedAt] = Date; + } - /*! - * Format `mod.match` given that it may be an array that we need to $or if - * the client has multiple docs with match functions - */ + if (createdAt && !schema.paths[createdAt]) { + schemaAdditions[createdAt] = { [schema.options.typeKey || 'type']: Date, immutable: true }; + } + schema.add(schemaAdditions); - function _formatMatch(match) { - if (Array.isArray(match)) { - if (match.length > 1) { - return { $or: [].concat(match.map((m) => Object.assign({}, m))) }; - } - return Object.assign({}, match[0]); - } - return Object.assign({}, match); - } + schema.pre('save', function(next) { + const timestampOption = get(this, '$__.saveOptions.timestamps'); + if (timestampOption === false) { + return next(); + } - /***/ - }, + const skipUpdatedAt = timestampOption != null && timestampOption.updatedAt === false; + const skipCreatedAt = timestampOption != null && timestampOption.createdAt === false; - /***/ 1684: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const MongooseError = __nccwpck_require__(4327); - const SkipPopulateValue = __nccwpck_require__(694); - const get = __nccwpck_require__(8730); - const getDiscriminatorByValue = __nccwpck_require__(8689); - const isPathExcluded = __nccwpck_require__(1126); - const getConstructorName = __nccwpck_require__(7323); - const getSchemaTypes = __nccwpck_require__(7604); - const getVirtual = __nccwpck_require__(6371); - const lookupLocalFields = __nccwpck_require__(1296); - const mpath = __nccwpck_require__(8586); - const normalizeRefPath = __nccwpck_require__(3360); - const util = __nccwpck_require__(1669); - const utils = __nccwpck_require__(9232); - - const modelSymbol = __nccwpck_require__(3240).modelSymbol; - const populateModelSymbol = __nccwpck_require__(3240).populateModelSymbol; - const schemaMixedSymbol = __nccwpck_require__(1205).schemaMixedSymbol; - - module.exports = function getModelsMapForPopulate(model, docs, options) { - let i; - let doc; - const len = docs.length; - const available = {}; - const map = []; - const modelNameFromQuery = - (options.model && options.model.modelName) || options.model; - let schema; - let refPath; - let Model; - let currentOptions; - let modelNames; - let modelName; - - const originalModel = options.model; - let isVirtual = false; - const modelSchema = model.schema; - - let allSchemaTypes = getSchemaTypes(modelSchema, null, options.path); - allSchemaTypes = Array.isArray(allSchemaTypes) - ? allSchemaTypes - : [allSchemaTypes].filter((v) => v != null); - const _firstWithRefPath = allSchemaTypes.find( - (schematype) => get(schematype, "options.refPath", null) != null - ); + const defaultTimestamp = currentTime != null ? + currentTime() : + this.ownerDocument().constructor.base.now(); + const auto_id = this._id && this._id.auto; - for (i = 0; i < len; i++) { - doc = docs[i]; - let justOne = null; - schema = getSchemaTypes(modelSchema, doc, options.path); - // Special case: populating a path that's a DocumentArray unless - // there's an explicit `ref` or `refPath` re: gh-8946 - if ( - schema != null && - schema.$isMongooseDocumentArray && - schema.options.ref == null && - schema.options.refPath == null - ) { - continue; - } - // Populating a nested path should always be a no-op re: #9073. - // People shouldn't do this, but apparently they do. - if ( - options._localModel != null && - options._localModel.schema.nested[options.path] - ) { - continue; - } - const isUnderneathDocArray = schema && schema.$isUnderneathDocArray; - if (isUnderneathDocArray && get(options, "options.sort") != null) { - return new MongooseError( - "Cannot populate with `sort` on path " + - options.path + - " because it is a subproperty of a document array" - ); - } + if (!skipCreatedAt && this.isNew && createdAt && !this.$__getValue(createdAt) && this.$__isSelected(createdAt)) { + this.$set(createdAt, auto_id ? this._id.getTimestamp() : defaultTimestamp); + } - modelNames = null; - let isRefPath = !!_firstWithRefPath; - let normalizedRefPath = _firstWithRefPath - ? get(_firstWithRefPath, "options.refPath", null) - : null; - let schemaOptions = null; - - if (Array.isArray(schema)) { - const schemasArray = schema; - for (const _schema of schemasArray) { - let _modelNames; - let res; - try { - res = _getModelNames(doc, _schema); - _modelNames = res.modelNames; - isRefPath = isRefPath || res.isRefPath; - normalizedRefPath = - normalizeRefPath(normalizedRefPath, doc, options.path) || - res.refPath; - justOne = res.justOne; - } catch (error) { - return error; - } + if (!skipUpdatedAt && updatedAt && (this.isNew || this.$isModified())) { + let ts = defaultTimestamp; + if (this.isNew) { + if (createdAt != null) { + ts = this.$__getValue(createdAt); + } else if (auto_id) { + ts = this._id.getTimestamp(); + } + } + this.$set(updatedAt, ts); + } - if (isRefPath && !res.isRefPath) { - continue; - } - if (!_modelNames) { - continue; - } - modelNames = modelNames || []; - for (const modelName of _modelNames) { - if (modelNames.indexOf(modelName) === -1) { - modelNames.push(modelName); - } - } - } - } else { - try { - const res = _getModelNames(doc, schema); - modelNames = res.modelNames; - isRefPath = res.isRefPath; - normalizedRefPath = res.refPath; - justOne = res.justOne; - schemaOptions = get(schema, "options.populate", null); - } catch (error) { - return error; - } + next(); + }); - if (!modelNames) { - continue; - } - } + schema.methods.initializeTimestamps = function() { + const ts = currentTime != null ? + currentTime() : + this.constructor.base.now(); + if (createdAt && !this.get(createdAt)) { + this.$set(createdAt, ts); + } + if (updatedAt && !this.get(updatedAt)) { + this.$set(updatedAt, ts); + } + return this; + }; - const _virtualRes = getVirtual(model.schema, options.path); - const virtual = _virtualRes == null ? null : _virtualRes.virtual; - - let localField; - let count = false; - if (virtual && virtual.options) { - const virtualPrefix = _virtualRes.nestedSchemaPath - ? _virtualRes.nestedSchemaPath + "." - : ""; - if (typeof virtual.options.localField === "function") { - localField = - virtualPrefix + virtual.options.localField.call(doc, doc); - } else if (Array.isArray(virtual.options.localField)) { - localField = virtual.options.localField.map( - (field) => virtualPrefix + field - ); - } else { - localField = virtualPrefix + virtual.options.localField; - } - count = virtual.options.count; + _setTimestampsOnUpdate[symbols.builtInMiddleware] = true; + + const opts = { query: true, model: false }; + schema.pre('findOneAndReplace', opts, _setTimestampsOnUpdate); + schema.pre('findOneAndUpdate', opts, _setTimestampsOnUpdate); + schema.pre('replaceOne', opts, _setTimestampsOnUpdate); + schema.pre('update', opts, _setTimestampsOnUpdate); + schema.pre('updateOne', opts, _setTimestampsOnUpdate); + schema.pre('updateMany', opts, _setTimestampsOnUpdate); + + function _setTimestampsOnUpdate(next) { + const now = currentTime != null ? + currentTime() : + this.model.base.now(); + // Replacing with null update should still trigger timestamps + if (this.op === 'findOneAndReplace' && this.getUpdate() == null) { + this.setUpdate({}); + } + applyTimestampsToUpdate(now, createdAt, updatedAt, this.getUpdate(), + this.options, this.schema); + applyTimestampsToChildren(now, this.getUpdate(), this.model.schema); + next(); + } +}; - if ( - virtual.options.skip != null && - !options.hasOwnProperty("skip") - ) { - options.skip = virtual.options.skip; - } - if ( - virtual.options.limit != null && - !options.hasOwnProperty("limit") - ) { - options.limit = virtual.options.limit; - } - if ( - virtual.options.perDocumentLimit != null && - !options.hasOwnProperty("perDocumentLimit") - ) { - options.perDocumentLimit = virtual.options.perDocumentLimit; - } - } else { - localField = options.path; - } - let foreignField = - virtual && virtual.options ? virtual.options.foreignField : "_id"; - - // `justOne = null` means we don't know from the schema whether the end - // result should be an array or a single doc. This can result from - // populating a POJO using `Model.populate()` - if ("justOne" in options && options.justOne !== void 0) { - justOne = options.justOne; - } else if (virtual && virtual.options && virtual.options.refPath) { - const normalizedRefPath = normalizeRefPath( - virtual.options.refPath, - doc, - options.path - ); - justOne = !!virtual.options.justOne; - isVirtual = true; - const refValue = utils.getValue(normalizedRefPath, doc); - modelNames = Array.isArray(refValue) ? refValue : [refValue]; - } else if (virtual && virtual.options && virtual.options.ref) { - let normalizedRef; - if (typeof virtual.options.ref === "function") { - normalizedRef = virtual.options.ref.call(doc, doc); - } else { - normalizedRef = virtual.options.ref; - } - justOne = !!virtual.options.justOne; - isVirtual = true; - if (!modelNames) { - modelNames = [].concat(normalizedRef); - } - } else if (schema && !schema[schemaMixedSymbol]) { - // Skip Mixed types because we explicitly don't do casting on those. - if (options.path.endsWith("." + schema.path)) { - justOne = Array.isArray(schema) - ? schema.every((schema) => !schema.$isMongooseArray) - : !schema.$isMongooseArray; - } - } +/***/ }), - if (!modelNames) { - continue; - } +/***/ 8571: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (virtual && (!localField || !foreignField)) { - return new MongooseError( - "If you are populating a virtual, you must set the " + - "localField and foreignField options" - ); - } +"use strict"; - options.isVirtual = isVirtual; - options.virtual = virtual; - if (typeof localField === "function") { - localField = localField.call(doc, doc); - } - if (typeof foreignField === "function") { - foreignField = foreignField.call(doc); - } - let match = - get(options, "match", null) || - get(currentOptions, "match", null) || - get(options, "virtual.options.match", null) || - get(options, "virtual.options.options.match", null); +const getConstructorName = __nccwpck_require__(7323); - let hasMatchFunction = typeof match === "function"; - if (hasMatchFunction) { - match = match.call(doc, doc); - } +module.exports = function allServersUnknown(topologyDescription) { + if (getConstructorName(topologyDescription) !== 'TopologyDescription') { + return false; + } - if ( - Array.isArray(localField) && - Array.isArray(foreignField) && - localField.length === foreignField.length - ) { - match = Object.assign({}, match); - for (let i = 1; i < localField.length; ++i) { - match[foreignField[i]] = convertTo_id( - mpath.get(localField[i], doc, lookupLocalFields), - schema - ); - hasMatchFunction = true; - } + const servers = Array.from(topologyDescription.servers.values()); + return servers.length > 0 && servers.every(server => server.type === 'Unknown'); +}; - localField = localField[0]; - foreignField = foreignField[0]; - } +/***/ }), - const localFieldPathType = modelSchema._getPathType(localField); - const localFieldPath = - localFieldPathType === "real" - ? modelSchema.path(localField) - : localFieldPathType.schema; - const localFieldGetters = - localFieldPath && localFieldPath.getters - ? localFieldPath.getters - : []; - let ret; +/***/ 7352: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const _populateOptions = get(options, "options", {}); - - const getters = - "getters" in _populateOptions - ? _populateOptions.getters - : options.isVirtual && get(virtual, "options.getters", false); - if (localFieldGetters.length > 0 && getters) { - const hydratedDoc = doc.$__ != null ? doc : model.hydrate(doc); - const localFieldValue = mpath.get( - localField, - doc, - lookupLocalFields - ); - if (Array.isArray(localFieldValue)) { - const localFieldHydratedValue = mpath.get( - localField.split(".").slice(0, -1), - hydratedDoc, - lookupLocalFields - ); - ret = localFieldValue.map( - (localFieldArrVal, localFieldArrIndex) => - localFieldPath.applyGetters( - localFieldArrVal, - localFieldHydratedValue[localFieldArrIndex] - ) - ); - } else { - ret = localFieldPath.applyGetters(localFieldValue, hydratedDoc); - } - } else { - ret = convertTo_id( - mpath.get(localField, doc, lookupLocalFields), - schema - ); - } +"use strict"; - const id = String(utils.getValue(foreignField, doc)); - options._docs[id] = Array.isArray(ret) ? ret.slice() : ret; - - // Re: gh-8452. Embedded discriminators may not have `refPath`, so clear - // out embedded discriminator docs that don't have a `refPath` on the - // populated path. - if (isRefPath && normalizedRefPath != null) { - const pieces = normalizedRefPath.split("."); - let cur = ""; - for (let j = 0; j < pieces.length; ++j) { - const piece = pieces[j]; - cur = cur + (cur.length === 0 ? "" : ".") + piece; - const schematype = modelSchema.path(cur); - if ( - schematype != null && - schematype.$isMongooseArray && - schematype.caster.discriminators != null && - Object.keys(schematype.caster.discriminators).length > 0 - ) { - const subdocs = utils.getValue(cur, doc); - const remnant = options.path.substr(cur.length + 1); - const discriminatorKey = - schematype.caster.schema.options.discriminatorKey; - modelNames = []; - for (const subdoc of subdocs) { - const discriminatorName = utils.getValue( - discriminatorKey, - subdoc - ); - const discriminator = - schematype.caster.discriminators[discriminatorName]; - const discriminatorSchema = - discriminator && discriminator.schema; - if (discriminatorSchema == null) { - continue; - } - const _path = discriminatorSchema.path(remnant); - if (_path == null || _path.options.refPath == null) { - const docValue = utils.getValue( - localField.substr(cur.length + 1), - subdoc - ); - ret = ret.map((v) => - v === docValue ? SkipPopulateValue(v) : v - ); - continue; - } - const modelName = utils.getValue( - pieces.slice(j + 1).join("."), - subdoc - ); - modelNames.push(modelName); - } - } - } - } - let k = modelNames.length; - while (k--) { - modelName = modelNames[k]; - if (modelName == null) { - continue; - } +const getConstructorName = __nccwpck_require__(7323); - // `PopulateOptions#connection`: if the model is passed as a string, the - // connection matters because different connections have different models. - const connection = - options.connection != null ? options.connection : model.db; +module.exports = function isAtlas(topologyDescription) { + if (getConstructorName(topologyDescription) !== 'TopologyDescription') { + return false; + } - try { - Model = - originalModel && originalModel[modelSymbol] - ? originalModel - : modelName[modelSymbol] - ? modelName - : connection.model(modelName); - } catch (error) { - // If `ret` is undefined, we'll add an empty entry to modelsMap. We shouldn't - // execute a query, but it is necessary to make sure `justOne` gets handled - // correctly for setting an empty array (see gh-8455) - if (ret !== undefined) { - return error; - } - } + const hostnames = Array.from(topologyDescription.servers.keys()); + return hostnames.length > 0 && + hostnames.every(host => host.endsWith('.mongodb.net:27017')); +}; - let ids = ret; - const flat = Array.isArray(ret) ? utils.array.flatten(ret) : []; +/***/ }), - if ( - isRefPath && - Array.isArray(ret) && - flat.length === modelNames.length - ) { - ids = flat.filter((val, i) => modelNames[i] === modelName); - } +/***/ 5437: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ( - !available[modelName] || - currentOptions.perDocumentLimit != null || - get(currentOptions, "options.perDocumentLimit") != null - ) { - currentOptions = { - model: Model, - }; +"use strict"; - if (isVirtual && get(virtual, "options.options")) { - currentOptions.options = utils.clone(virtual.options.options); - } else if (schemaOptions != null) { - currentOptions.options = Object.assign({}, schemaOptions); - } - utils.merge(currentOptions, options); - - // Used internally for checking what model was used to populate this - // path. - options[populateModelSymbol] = Model; - - available[modelName] = { - model: Model, - options: currentOptions, - match: hasMatchFunction ? [match] : match, - docs: [doc], - ids: [ids], - allIds: [ret], - localField: new Set([localField]), - foreignField: new Set([foreignField]), - justOne: justOne, - isVirtual: isVirtual, - virtual: virtual, - count: count, - [populateModelSymbol]: Model, - }; - map.push(available[modelName]); - } else { - available[modelName].localField.add(localField); - available[modelName].foreignField.add(foreignField); - available[modelName].docs.push(doc); - available[modelName].ids.push(ids); - available[modelName].allIds.push(ret); - if (hasMatchFunction) { - available[modelName].match.push(match); - } - } - } - } - return map; - function _getModelNames(doc, schema) { - let modelNames; - let discriminatorKey; - let isRefPath = false; - let justOne = null; +const getConstructorName = __nccwpck_require__(7323); - if (schema && schema.caster) { - schema = schema.caster; - } - if (schema && schema.$isSchemaMap) { - schema = schema.$__schemaType; - } +const nonSSLMessage = 'Client network socket disconnected before secure TLS ' + + 'connection was established'; - if (!schema && model.discriminators) { - discriminatorKey = model.schema.discriminatorMapping.key; - } +module.exports = function isSSLError(topologyDescription) { + if (getConstructorName(topologyDescription) !== 'TopologyDescription') { + return false; + } - refPath = schema && schema.options && schema.options.refPath; + const descriptions = Array.from(topologyDescription.servers.values()); + return descriptions.length > 0 && + descriptions.every(descr => descr.error && descr.error.message.indexOf(nonSSLMessage) !== -1); +}; - const normalizedRefPath = normalizeRefPath( - refPath, - doc, - options.path - ); +/***/ }), - if (modelNameFromQuery) { - modelNames = [modelNameFromQuery]; // query options - } else if (normalizedRefPath) { - if ( - options._queryProjection != null && - isPathExcluded(options._queryProjection, normalizedRefPath) - ) { - throw new MongooseError( - "refPath `" + - normalizedRefPath + - "` must not be excluded in projection, got " + - util.inspect(options._queryProjection) - ); - } +/***/ 1975: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ( - modelSchema.virtuals.hasOwnProperty(normalizedRefPath) && - doc.$__ == null - ) { - modelNames = [ - modelSchema.virtuals[normalizedRefPath].applyGetters( - void 0, - doc - ), - ]; - } else { - modelNames = utils.getValue(normalizedRefPath, doc); - } +"use strict"; - if (Array.isArray(modelNames)) { - modelNames = utils.array.flatten(modelNames); - } - isRefPath = true; - } else { - let modelForCurrentDoc = model; - let schemaForCurrentDoc; - let discriminatorValue; - - if ( - !schema && - discriminatorKey && - (discriminatorValue = utils.getValue(discriminatorKey, doc)) - ) { - // `modelNameForFind` is the discriminator value, so we might need - // find the discriminated model name - const discriminatorModel = - getDiscriminatorByValue( - model.discriminators, - discriminatorValue - ) || model; - if (discriminatorModel != null) { - modelForCurrentDoc = discriminatorModel; - } else { - try { - modelForCurrentDoc = model.db.model(discriminatorValue); - } catch (error) { - return error; - } - } +const cleanPositionalOperators = __nccwpck_require__(1119); +const handleTimestampOption = __nccwpck_require__(2850); - schemaForCurrentDoc = modelForCurrentDoc.schema._getSchema( - options.path - ); +module.exports = applyTimestampsToChildren; - if (schemaForCurrentDoc && schemaForCurrentDoc.caster) { - schemaForCurrentDoc = schemaForCurrentDoc.caster; - } - } else { - schemaForCurrentDoc = schema; - } - const _virtualRes = getVirtual( - modelForCurrentDoc.schema, - options.path - ); - const virtual = _virtualRes == null ? null : _virtualRes.virtual; +/*! + * ignore + */ - if (schemaForCurrentDoc != null) { - justOne = - !schemaForCurrentDoc.$isMongooseArray && - !schemaForCurrentDoc._arrayPath; - } +function applyTimestampsToChildren(now, update, schema) { + if (update == null) { + return; + } - let ref; - let refPath; + const keys = Object.keys(update); + const hasDollarKey = keys.some(key => key.startsWith('$')); - if ((ref = get(schemaForCurrentDoc, "options.ref")) != null) { - ref = handleRefFunction(ref, doc); - modelNames = [ref]; - } else if ((ref = get(virtual, "options.ref")) != null) { - ref = handleRefFunction(ref, doc); + if (hasDollarKey) { + if (update.$push) { + _applyTimestampToUpdateOperator(update.$push); + } + if (update.$addToSet) { + _applyTimestampToUpdateOperator(update.$addToSet); + } + if (update.$set != null) { + const keys = Object.keys(update.$set); + for (const key of keys) { + applyTimestampsToUpdateKey(schema, key, update.$set, now); + } + } + if (update.$setOnInsert != null) { + const keys = Object.keys(update.$setOnInsert); + for (const key of keys) { + applyTimestampsToUpdateKey(schema, key, update.$setOnInsert, now); + } + } + } - // When referencing nested arrays, the ref should be an Array - // of modelNames. - if (Array.isArray(ref)) { - modelNames = ref; - } else { - modelNames = [ref]; - } + const updateKeys = Object.keys(update).filter(key => !key.startsWith('$')); + for (const key of updateKeys) { + applyTimestampsToUpdateKey(schema, key, update, now); + } - isVirtual = true; - } else if ( - (refPath = get(schemaForCurrentDoc, "options.refPath")) != null - ) { - isRefPath = true; - refPath = normalizeRefPath(refPath, doc, options.path); - modelNames = utils.getValue(refPath, doc); - if (Array.isArray(modelNames)) { - modelNames = utils.array.flatten(modelNames); - } - } else { - // We may have a discriminator, in which case we don't want to - // populate using the base model by default - modelNames = discriminatorKey ? null : [model.modelName]; + function _applyTimestampToUpdateOperator(op) { + for (const key of Object.keys(op)) { + const $path = schema.path(key.replace(/\.\$\./i, '.').replace(/.\$$/, '')); + if (op[key] && + $path && + $path.$isMongooseDocumentArray && + $path.schema.options.timestamps) { + const timestamps = $path.schema.options.timestamps; + const createdAt = handleTimestampOption(timestamps, 'createdAt'); + const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); + if (op[key].$each) { + op[key].$each.forEach(function(subdoc) { + if (updatedAt != null) { + subdoc[updatedAt] = now; + } + if (createdAt != null) { + subdoc[createdAt] = now; } + }); + } else { + if (updatedAt != null) { + op[key][updatedAt] = now; } - - if (!modelNames) { - return { - modelNames: modelNames, - isRefPath: isRefPath, - refPath: normalizedRefPath, - justOne: justOne, - }; + if (createdAt != null) { + op[key][createdAt] = now; } + } + } + } + } +} - if (!Array.isArray(modelNames)) { - modelNames = [modelNames]; - } +function applyTimestampsToDocumentArray(arr, schematype, now) { + const timestamps = schematype.schema.options.timestamps; - return { - modelNames: modelNames, - isRefPath: isRefPath, - refPath: normalizedRefPath, - justOne: justOne, - }; - } - }; + if (!timestamps) { + return; + } - /*! - * ignore - */ + const len = arr.length; - function handleRefFunction(ref, doc) { - if (typeof ref === "function" && !ref[modelSymbol]) { - return ref.call(doc, doc); - } - return ref; - } + const createdAt = handleTimestampOption(timestamps, 'createdAt'); + const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); + for (let i = 0; i < len; ++i) { + if (updatedAt != null) { + arr[i][updatedAt] = now; + } + if (createdAt != null) { + arr[i][createdAt] = now; + } - /*! - * Retrieve the _id of `val` if a Document or Array of Documents. - * - * @param {Array|Document|Any} val - * @return {Array|Document|Any} - */ + applyTimestampsToChildren(now, arr[i], schematype.schema); + } +} - function convertTo_id(val, schema) { - if (val != null && val.$__ != null) { - return val._id; - } - if ( - val != null && - val._id != null && - (schema == null || !schema.$isSchemaMap) - ) { - return val._id; - } +function applyTimestampsToSingleNested(subdoc, schematype, now) { + const timestamps = schematype.schema.options.timestamps; + if (!timestamps) { + return; + } - if (Array.isArray(val)) { - for (let i = 0; i < val.length; ++i) { - if (val[i] != null && val[i].$__ != null) { - val[i] = val[i]._id; - } - } - if (val.isMongooseArray && val.$schema()) { - return val.$schema()._castForPopulate(val, val.$parent()); - } + const createdAt = handleTimestampOption(timestamps, 'createdAt'); + const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); + if (updatedAt != null) { + subdoc[updatedAt] = now; + } + if (createdAt != null) { + subdoc[createdAt] = now; + } - return [].concat(val); - } + applyTimestampsToChildren(now, subdoc, schematype.schema); +} - // `populate('map')` may be an object if populating on a doc that hasn't - // been hydrated yet - if ( - getConstructorName(val) === "Object" && - // The intent here is we should only flatten the object if we expect - // to get a Map in the end. Avoid doing this for mixed types. - (schema == null || schema[schemaMixedSymbol] == null) - ) { - const ret = []; - for (const key of Object.keys(val)) { - ret.push(val[key]); - } - return ret; - } - // If doc has already been hydrated, e.g. `doc.populate('map').execPopulate()` - // then `val` will already be a map - if (val instanceof Map) { - return Array.from(val.values()); +function applyTimestampsToUpdateKey(schema, key, update, now) { + // Replace positional operator `$` and array filters `$[]` and `$[.*]` + const keyToSearch = cleanPositionalOperators(key); + const path = schema.path(keyToSearch); + if (!path) { + return; + } + + const parentSchemaTypes = []; + const pieces = keyToSearch.split('.'); + for (let i = pieces.length - 1; i > 0; --i) { + const s = schema.path(pieces.slice(0, i).join('.')); + if (s != null && + (s.$isMongooseDocumentArray || s.$isSingleNested)) { + parentSchemaTypes.push({ parentPath: key.split('.').slice(0, i).join('.'), parentSchemaType: s }); + } + } + + if (Array.isArray(update[key]) && path.$isMongooseDocumentArray) { + applyTimestampsToDocumentArray(update[key], path, now); + } else if (update[key] && path.$isSingleNested) { + applyTimestampsToSingleNested(update[key], path, now); + } else if (parentSchemaTypes.length > 0) { + for (const item of parentSchemaTypes) { + const parentPath = item.parentPath; + const parentSchemaType = item.parentSchemaType; + const timestamps = parentSchemaType.schema.options.timestamps; + const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); + + if (!timestamps || updatedAt == null) { + continue; + } + + if (parentSchemaType.$isSingleNested) { + // Single nested is easy + update[parentPath + '.' + updatedAt] = now; + } else if (parentSchemaType.$isMongooseDocumentArray) { + let childPath = key.substr(parentPath.length + 1); + + if (/^\d+$/.test(childPath)) { + update[parentPath + '.' + childPath][updatedAt] = now; + continue; } - return val; + const firstDot = childPath.indexOf('.'); + childPath = firstDot !== -1 ? childPath.substr(0, firstDot) : childPath; + + update[parentPath + '.' + childPath + '.' + updatedAt] = now; } + } + } else if (path.schema != null && path.schema != schema && update[key]) { + const timestamps = path.schema.options.timestamps; + const createdAt = handleTimestampOption(timestamps, 'createdAt'); + const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); - /***/ - }, + if (!timestamps) { + return; + } - /***/ 7604: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * ignore - */ - - const Mixed = __nccwpck_require__(7495); - const get = __nccwpck_require__(8730); - const leanPopulateMap = __nccwpck_require__(914); - const mpath = __nccwpck_require__(8586); - - const populateModelSymbol = __nccwpck_require__(3240).populateModelSymbol; - - /*! - * @param {Schema} schema - * @param {Object} doc POJO - * @param {string} path - */ - - module.exports = function getSchemaTypes(schema, doc, path) { - const pathschema = schema.path(path); - const topLevelDoc = doc; - if (pathschema) { - return pathschema; - } - - function search(parts, schema, subdoc, nestedPath) { - let p = parts.length + 1; - let foundschema; - let trypath; - - while (p--) { - trypath = parts.slice(0, p).join("."); - foundschema = schema.path(trypath); - if (foundschema == null) { - continue; - } + if (updatedAt != null) { + update[key][updatedAt] = now; + } + if (createdAt != null) { + update[key][createdAt] = now; + } + } +} - if (foundschema.caster) { - // array of Mixed? - if (foundschema.caster instanceof Mixed) { - return foundschema.caster; - } +/***/ }), - let schemas = null; - if ( - foundschema.schema != null && - foundschema.schema.discriminators != null - ) { - const discriminators = foundschema.schema.discriminators; - const discriminatorKeyPath = - trypath + "." + foundschema.schema.options.discriminatorKey; - const keys = subdoc - ? mpath.get(discriminatorKeyPath, subdoc) || [] - : []; - schemas = Object.keys(discriminators).reduce(function ( - cur, - discriminator - ) { - const tiedValue = - discriminators[discriminator].discriminatorMapping.value; - if ( - doc == null || - keys.indexOf(discriminator) !== -1 || - keys.indexOf(tiedValue) !== -1 - ) { - cur.push(discriminators[discriminator]); - } - return cur; - }, - []); - } +/***/ 1162: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Now that we found the array, we need to check if there - // are remaining document paths to look up for casting. - // Also we need to handle array.$.path since schema.path - // doesn't work for that. - // If there is no foundschema.schema we are dealing with - // a path like array.$ - if (p !== parts.length && foundschema.schema) { - let ret; - if (parts[p] === "$") { - if (p + 1 === parts.length) { - // comments.$ - return foundschema; - } - // comments.$.comments.$.title - ret = search( - parts.slice(p + 1), - schema, - subdoc ? mpath.get(trypath, subdoc) : null, - nestedPath.concat(parts.slice(0, p)) - ); - if (ret) { - ret.$isUnderneathDocArray = - ret.$isUnderneathDocArray || - !foundschema.schema.$isSingleNested; - } - return ret; - } +"use strict"; - if (schemas != null && schemas.length > 0) { - ret = []; - for (const schema of schemas) { - const _ret = search( - parts.slice(p), - schema, - subdoc ? mpath.get(trypath, subdoc) : null, - nestedPath.concat(parts.slice(0, p)) - ); - if (_ret != null) { - _ret.$isUnderneathDocArray = - _ret.$isUnderneathDocArray || - !foundschema.schema.$isSingleNested; - if (_ret.$isUnderneathDocArray) { - ret.$isUnderneathDocArray = true; - } - ret.push(_ret); - } - } - return ret; - } else { - ret = search( - parts.slice(p), - foundschema.schema, - subdoc ? mpath.get(trypath, subdoc) : null, - nestedPath.concat(parts.slice(0, p)) - ); - - if (ret) { - ret.$isUnderneathDocArray = - ret.$isUnderneathDocArray || - !foundschema.schema.$isSingleNested; - } - return ret; - } - } else if ( - p !== parts.length && - foundschema.$isMongooseArray && - foundschema.casterConstructor.$isMongooseArray - ) { - // Nested arrays. Drill down to the bottom of the nested array. - let type = foundschema; - while ( - type.$isMongooseArray && - !type.$isMongooseDocumentArray - ) { - type = type.casterConstructor; - } - const ret = search( - parts.slice(p), - type.schema, - null, - nestedPath.concat(parts.slice(0, p)) - ); - if (ret != null) { - return ret; - } +/*! + * ignore + */ - if (type.schema.discriminators) { - const discriminatorPaths = []; - for (const discriminatorName of Object.keys( - type.schema.discriminators - )) { - const _schema = - type.schema.discriminators[discriminatorName] || - type.schema; - const ret = search( - parts.slice(p), - _schema, - null, - nestedPath.concat(parts.slice(0, p)) - ); - if (ret != null) { - discriminatorPaths.push(ret); - } - } - if (discriminatorPaths.length > 0) { - return discriminatorPaths; - } - } - } - } +const get = __nccwpck_require__(8730); - const fullPath = nestedPath.concat([trypath]).join("."); - if ( - topLevelDoc != null && - topLevelDoc.$__ && - topLevelDoc.populated(fullPath) && - p < parts.length - ) { - const model = - doc.$__.populated[fullPath].options[populateModelSymbol]; - if (model != null) { - const ret = search( - parts.slice(p), - model.schema, - subdoc ? mpath.get(trypath, subdoc) : null, - nestedPath.concat(parts.slice(0, p)) - ); +module.exports = applyTimestampsToUpdate; - if (ret) { - ret.$isUnderneathDocArray = - ret.$isUnderneathDocArray || !model.schema.$isSingleNested; - } - return ret; - } - } +/*! + * ignore + */ - const _val = get(topLevelDoc, trypath); - if (_val != null) { - const model = - Array.isArray(_val) && _val.length > 0 - ? leanPopulateMap.get(_val[0]) - : leanPopulateMap.get(_val); - // Populated using lean, `leanPopulateMap` value is the foreign model - const schema = model != null ? model.schema : null; - if (schema != null) { - const ret = search( - parts.slice(p), - schema, - subdoc ? mpath.get(trypath, subdoc) : null, - nestedPath.concat(parts.slice(0, p)) - ); +function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, options) { + const updates = currentUpdate; + let _updates = updates; + const overwrite = get(options, 'overwrite', false); + const timestamps = get(options, 'timestamps', true); - if (ret != null) { - ret.$isUnderneathDocArray = - ret.$isUnderneathDocArray || !schema.$isSingleNested; - return ret; - } - } - } - return foundschema; - } + // Support skipping timestamps at the query level, see gh-6980 + if (!timestamps || updates == null) { + return currentUpdate; + } + + const skipCreatedAt = timestamps != null && timestamps.createdAt === false; + const skipUpdatedAt = timestamps != null && timestamps.updatedAt === false; + + if (overwrite) { + if (currentUpdate && currentUpdate.$set) { + currentUpdate = currentUpdate.$set; + updates.$set = {}; + _updates = updates.$set; + } + if (!skipUpdatedAt && updatedAt && !currentUpdate[updatedAt]) { + _updates[updatedAt] = now; + } + if (!skipCreatedAt && createdAt && !currentUpdate[createdAt]) { + _updates[createdAt] = now; + } + return updates; + } + currentUpdate = currentUpdate || {}; + + if (Array.isArray(updates)) { + // Update with aggregation pipeline + updates.push({ $set: { updatedAt: now } }); + + return updates; + } + + updates.$set = updates.$set || {}; + if (!skipUpdatedAt && updatedAt && + (!currentUpdate.$currentDate || !currentUpdate.$currentDate[updatedAt])) { + let timestampSet = false; + if (updatedAt.indexOf('.') !== -1) { + const pieces = updatedAt.split('.'); + for (let i = 1; i < pieces.length; ++i) { + const remnant = pieces.slice(-i).join('.'); + const start = pieces.slice(0, -i).join('.'); + if (currentUpdate[start] != null) { + currentUpdate[start][remnant] = now; + timestampSet = true; + break; + } else if (currentUpdate.$set && currentUpdate.$set[start]) { + currentUpdate.$set[start][remnant] = now; + timestampSet = true; + break; } - // look for arrays - const parts = path.split("."); - for (let i = 0; i < parts.length; ++i) { - if (parts[i] === "$") { - // Re: gh-5628, because `schema.path()` doesn't take $ into account. - parts[i] = "0"; - } + } + } + + if (!timestampSet) { + updates.$set[updatedAt] = now; + } + + if (updates.hasOwnProperty(updatedAt)) { + delete updates[updatedAt]; + } + } + + if (!skipCreatedAt && createdAt) { + + if (currentUpdate[createdAt]) { + delete currentUpdate[createdAt]; + } + if (currentUpdate.$set && currentUpdate.$set[createdAt]) { + delete currentUpdate.$set[createdAt]; + } + let timestampSet = false; + if (createdAt.indexOf('.') !== -1) { + const pieces = createdAt.split('.'); + for (let i = 1; i < pieces.length; ++i) { + const remnant = pieces.slice(-i).join('.'); + const start = pieces.slice(0, -i).join('.'); + if (currentUpdate[start] != null) { + currentUpdate[start][remnant] = now; + timestampSet = true; + break; + } else if (currentUpdate.$set && currentUpdate.$set[start]) { + currentUpdate.$set[start][remnant] = now; + timestampSet = true; + break; } - return search(parts, schema, doc, []); - }; + } + } - /***/ - }, + if (!timestampSet) { + updates.$setOnInsert = updates.$setOnInsert || {}; + updates.$setOnInsert[createdAt] = now; + } + } + + if (Object.keys(updates.$set).length === 0) { + delete updates.$set; + } + return updates; +} + + +/***/ }), - /***/ 6371: /***/ (module) => { - "use strict"; +/***/ 4856: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - module.exports = getVirtual; +"use strict"; - /*! - * ignore - */ - function getVirtual(schema, name) { - if (schema.virtuals[name]) { - return { virtual: schema.virtuals[name], path: void 0 }; +const castFilterPath = __nccwpck_require__(8045); +const cleanPositionalOperators = __nccwpck_require__(1119); +const getPath = __nccwpck_require__(7453); +const updatedPathsByArrayFilter = __nccwpck_require__(6507); + +module.exports = function castArrayFilters(query) { + const arrayFilters = query.options.arrayFilters; + const update = query.getUpdate(); + const schema = query.schema; + const updatedPathsByFilter = updatedPathsByArrayFilter(update); + + let strictQuery = schema.options.strict; + if (query._mongooseOptions.strict != null) { + strictQuery = query._mongooseOptions.strict; + } + if (schema._userProvidedOptions.strictQuery != null) { + strictQuery = schema._userProvidedOptions.strictQuery; + } + if (query._mongooseOptions.strictQuery != null) { + strictQuery = query._mongooseOptions.strictQuery; + } + + _castArrayFilters(arrayFilters, schema, strictQuery, updatedPathsByFilter, query); +}; + +function _castArrayFilters(arrayFilters, schema, strictQuery, updatedPathsByFilter, query) { + if (!Array.isArray(arrayFilters)) { + return; + } + + for (const filter of arrayFilters) { + if (filter == null) { + throw new Error(`Got null array filter in ${arrayFilters}`); + } + for (const key of Object.keys(filter)) { + if (key === '$and' || key === '$or') { + _castArrayFilters(filter[key], schema, strictQuery, updatedPathsByFilter, query); + continue; + } + if (filter[key] == null) { + continue; + } + if (updatedPathsByFilter[key] === null) { + continue; + } + if (Object.keys(updatedPathsByFilter).length === 0) { + continue; + } + const dot = key.indexOf('.'); + let filterPath = dot === -1 ? + updatedPathsByFilter[key] + '.0' : + updatedPathsByFilter[key.substr(0, dot)] + '.0' + key.substr(dot); + if (filterPath == null) { + throw new Error(`Filter path not found for ${key}`); + } + + // If there are multiple array filters in the path being updated, make sure + // to replace them so we can get the schema path. + filterPath = cleanPositionalOperators(filterPath); + const schematype = getPath(schema, filterPath); + if (schematype == null) { + if (!strictQuery) { + return; } + // For now, treat `strictQuery = true` and `strictQuery = 'throw'` as + // equivalent for casting array filters. `strictQuery = true` doesn't + // quite work in this context because we never want to silently strip out + // array filters, even if the path isn't in the schema. + throw new Error(`Could not find path "${filterPath}" in schema`); + } + if (typeof filter[key] === 'object') { + filter[key] = castFilterPath(query, schematype, filter[key]); + } else { + filter[key] = schematype.castForQuery(filter[key]); + } + } + } +} - const parts = name.split("."); - let cur = ""; - let nestedSchemaPath = ""; - for (let i = 0; i < parts.length; ++i) { - cur += (cur.length > 0 ? "." : "") + parts[i]; - if (schema.virtuals[cur]) { - if (i === parts.length - 1) { - return { virtual: schema.virtuals[cur], path: nestedSchemaPath }; - } - continue; - } +/***/ }), - if (schema.nested[cur]) { - continue; - } +/***/ 587: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (schema.paths[cur] && schema.paths[cur].schema) { - schema = schema.paths[cur].schema; - const rest = parts.slice(i + 1).join("."); - - if (schema.virtuals[rest]) { - if (i === parts.length - 2) { - return { - virtual: schema.virtuals[rest], - nestedSchemaPath: [nestedSchemaPath, cur] - .filter((v) => !!v) - .join("."), - }; - } - continue; - } +"use strict"; - if (i + 1 < parts.length && schema.discriminators) { - for (const key of Object.keys(schema.discriminators)) { - const res = getVirtual(schema.discriminators[key], rest); - if (res != null) { - const _path = [nestedSchemaPath, cur, res.nestedSchemaPath] - .filter((v) => !!v) - .join("."); - return { - virtual: res.virtual, - nestedSchemaPath: _path, - }; - } - } - } - nestedSchemaPath += (nestedSchemaPath.length > 0 ? "." : "") + cur; - cur = ""; - continue; - } +const _modifiedPaths = __nccwpck_require__(3719)/* .modifiedPaths */ .M; + +/** + * Given an update document with potential update operators (`$set`, etc.) + * returns an object whose keys are the directly modified paths. + * + * If there are any top-level keys that don't start with `$`, we assume those + * will get wrapped in a `$set`. The Mongoose Query is responsible for wrapping + * top-level keys in `$set`. + * + * @param {Object} update + * @return {Object} modified + */ + +module.exports = function modifiedPaths(update) { + const keys = Object.keys(update); + const res = {}; - if (schema.discriminators) { - for (const discriminatorKey of Object.keys(schema.discriminators)) { - const virtualFromDiscriminator = getVirtual( - schema.discriminators[discriminatorKey], - name - ); - if (virtualFromDiscriminator) return virtualFromDiscriminator; - } - } + const withoutDollarKeys = {}; + for (const key of keys) { + if (key.startsWith('$')) { + _modifiedPaths(update[key], '', res); + continue; + } + withoutDollarKeys[key] = update[key]; + } - return null; - } - } + _modifiedPaths(withoutDollarKeys, '', res); - /***/ - }, + return res; +}; - /***/ 914: /***/ (module) => { - "use strict"; - /*! - * ignore - */ +/***/ }), - module.exports = new WeakMap(); +/***/ 4632: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /***/ - }, +"use strict"; - /***/ 1296: /***/ (module) => { - "use strict"; - module.exports = function lookupLocalFields(cur, path, val) { - if (cur == null) { - return cur; - } +const get = __nccwpck_require__(8730); - if (cur._doc != null) { - cur = cur._doc; - } +/** + * Given an update, move all $set on immutable properties to $setOnInsert. + * This should only be called for upserts, because $setOnInsert bypasses the + * strictness check for immutable properties. + */ - if (arguments.length >= 3) { - if (typeof cur !== "object") { - return void 0; - } - cur[path] = val; - return val; - } +module.exports = function moveImmutableProperties(schema, update, ctx) { + if (update == null) { + return; + } - // Support populating paths under maps using `map.$*.subpath` - if (path === "$*") { - return cur instanceof Map - ? Array.from(cur.values()) - : Object.keys(cur).map((key) => cur[key]); - } - return cur[path]; - }; + const keys = Object.keys(update); + for (const key of keys) { + const isDollarKey = key.startsWith('$'); - /***/ - }, + if (key === '$set') { + const updatedPaths = Object.keys(update[key]); + for (const path of updatedPaths) { + _walkUpdatePath(schema, update[key], path, update, ctx); + } + } else if (!isDollarKey) { + _walkUpdatePath(schema, update, key, update, ctx); + } - /***/ 3360: /***/ (module) => { - "use strict"; + } +}; - module.exports = function normalizeRefPath(refPath, doc, populatedPath) { - if (refPath == null) { - return refPath; - } +function _walkUpdatePath(schema, op, path, update, ctx) { + const schematype = schema.path(path); + if (schematype == null) { + return; + } - if (typeof refPath === "function") { - refPath = refPath.call(doc, doc, populatedPath); - } + let immutable = get(schematype, 'options.immutable', null); + if (immutable == null) { + return; + } + if (typeof immutable === 'function') { + immutable = immutable.call(ctx, ctx); + } - // If populated path has numerics, the end `refPath` should too. For example, - // if populating `a.0.b` instead of `a.b` and `b` has `refPath = a.c`, we - // should return `a.0.c` for the refPath. - const hasNumericProp = /(\.\d+$|\.\d+\.)/g; + if (!immutable) { + return; + } - if (hasNumericProp.test(populatedPath)) { - const chunks = populatedPath.split(hasNumericProp); + update.$setOnInsert = update.$setOnInsert || {}; + update.$setOnInsert[path] = op[path]; + delete op[path]; +} - if (chunks[chunks.length - 1] === "") { - throw new Error("Can't populate individual element in an array"); - } +/***/ }), - let _refPath = ""; - let _remaining = refPath; - // 2nd, 4th, etc. will be numeric props. For example: `[ 'a', '.0.', 'b' ]` - for (let i = 0; i < chunks.length; i += 2) { - const chunk = chunks[i]; - if (_remaining.startsWith(chunk + ".")) { - _refPath += _remaining.substr(0, chunk.length) + chunks[i + 1]; - _remaining = _remaining.substr(chunk.length + 1); - } else if (i === chunks.length - 1) { - _refPath += _remaining; - _remaining = ""; - break; - } else { - throw new Error( - "Could not normalize ref path, chunk " + - chunk + - " not in populated path" - ); - } - } +/***/ 8909: +/***/ ((module) => { - return _refPath; - } +"use strict"; - return refPath; - }; - /***/ - }, +/** + * MongoDB throws an error if there's unused array filters. That is, if `options.arrayFilters` defines + * a filter, but none of the `update` keys use it. This should be enough to filter out all unused array + * filters. + */ - /***/ 6962: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const get = __nccwpck_require__(8730); - const mpath = __nccwpck_require__(8586); - const parseProjection = __nccwpck_require__(7201); - - /*! - * ignore - */ - - module.exports = function removeDeselectedForeignField( - foreignFields, - options, - docs - ) { - const projection = - parseProjection(get(options, "select", null), true) || - parseProjection(get(options, "options.select", null), true); - - if (projection == null) { - return; - } - for (const foreignField of foreignFields) { - if (!projection.hasOwnProperty("-" + foreignField)) { - continue; - } +module.exports = function removeUnusedArrayFilters(update, arrayFilters) { + const updateKeys = Object.keys(update). + map(key => Object.keys(update[key])). + reduce((cur, arr) => cur.concat(arr), []); + return arrayFilters.filter(obj => { + return _checkSingleFilterKey(obj, updateKeys); + }); +}; + +function _checkSingleFilterKey(arrayFilter, updateKeys) { + const firstKey = Object.keys(arrayFilter)[0]; + + if (firstKey === '$and' || firstKey === '$or') { + if (!Array.isArray(arrayFilter[firstKey])) { + return false; + } + return arrayFilter[firstKey].find(filter => _checkSingleFilterKey(filter, updateKeys)) != null; + } - for (const val of docs) { - if (val.$__ != null) { - mpath.unset(foreignField, val._doc); - } else { - mpath.unset(foreignField, val); - } - } - } - }; + const firstDot = firstKey.indexOf('.'); + const arrayFilterKey = firstDot === -1 ? firstKey : firstKey.slice(0, firstDot); - /***/ - }, + return updateKeys.find(key => key.includes('$[' + arrayFilterKey + ']')) != null; +} - /***/ 5458: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +/***/ }), - const MongooseError = __nccwpck_require__(5953); - const util = __nccwpck_require__(1669); +/***/ 6507: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - module.exports = validateRef; +"use strict"; - function validateRef(ref, path) { - if (typeof ref === "string") { - return; - } - if (typeof ref === "function") { - return; - } +const modifiedPaths = __nccwpck_require__(587); - throw new MongooseError( - 'Invalid ref at path "' + - path + - '". Got ' + - util.inspect(ref, { depth: 0 }) - ); - } +module.exports = function updatedPathsByArrayFilter(update) { + if (update == null) { + return {}; + } + const updatedPaths = modifiedPaths(update); - /***/ - }, + return Object.keys(updatedPaths).reduce((cur, path) => { + const matches = path.match(/\$\[[^\]]+\]/g); + if (matches == null) { + return cur; + } + for (const match of matches) { + const firstMatch = path.indexOf(match); + if (firstMatch !== path.lastIndexOf(match)) { + throw new Error(`Path '${path}' contains the same array filter multiple times`); + } + cur[match.substring(2, match.length - 1)] = path. + substr(0, firstMatch - 1). + replace(/\$\[[^\]]+\]/g, '0'); + } + return cur; + }, {}); +}; - /***/ 2312: /***/ () => { - "use strict"; +/***/ }), - if (typeof jest !== "undefined" && typeof window !== "undefined") { - console.warn( - "Mongoose: looks like you're trying to test a Mongoose app " + - "with Jest's default jsdom test environment. Please make sure you read " + - "Mongoose's docs on configuring Jest to test Node.js apps: " + - "http://mongoosejs.com/docs/jest.html" - ); - } +/***/ 9009: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ( - typeof jest !== "undefined" && - process.nextTick.toString().indexOf("nextTick") === -1 - ) { - console.warn( - "Mongoose: looks like you're trying to test a Mongoose app " + - "with Jest's mock timers enabled. Please make sure you read " + - "Mongoose's docs on configuring Jest to test Node.js apps: " + - "http://mongoosejs.com/docs/jest.html" - ); - } +"use strict"; - /***/ - }, - /***/ 1903: /***/ (module) => { - "use strict"; +/*! + * Module dependencies. + */ + +const ValidationError = __nccwpck_require__(8460); +const cleanPositionalOperators = __nccwpck_require__(1119); +const flatten = __nccwpck_require__(3719)/* .flatten */ .x; +const modifiedPaths = __nccwpck_require__(3719)/* .modifiedPaths */ .M; - /*! - * ignore - */ +/** + * Applies validators and defaults to update and findOneAndUpdate operations, + * specifically passing a null doc as `this` to validators and defaults + * + * @param {Query} query + * @param {Schema} schema + * @param {Object} castedDoc + * @param {Object} options + * @method runValidatorsOnUpdate + * @api private + */ - module.exports = function isDefiningProjection(val) { - if (val == null) { - // `undefined` or `null` become exclusive projections - return true; +module.exports = function(query, schema, castedDoc, options, callback) { + const keys = Object.keys(castedDoc || {}); + let updatedKeys = {}; + let updatedValues = {}; + const isPull = {}; + const arrayAtomicUpdates = {}; + const numKeys = keys.length; + let hasDollarUpdate = false; + const modified = {}; + let currentUpdate; + let key; + let i; + + for (i = 0; i < numKeys; ++i) { + if (keys[i].startsWith('$')) { + hasDollarUpdate = true; + if (keys[i] === '$push' || keys[i] === '$addToSet') { + const _keys = Object.keys(castedDoc[keys[i]]); + for (let ii = 0; ii < _keys.length; ++ii) { + currentUpdate = castedDoc[keys[i]][_keys[ii]]; + if (currentUpdate && currentUpdate.$each) { + arrayAtomicUpdates[_keys[ii]] = (arrayAtomicUpdates[_keys[ii]] || []). + concat(currentUpdate.$each); + } else { + arrayAtomicUpdates[_keys[ii]] = (arrayAtomicUpdates[_keys[ii]] || []). + concat([currentUpdate]); + } + } + continue; + } + modifiedPaths(castedDoc[keys[i]], '', modified); + const flat = flatten(castedDoc[keys[i]], null, null, schema); + const paths = Object.keys(flat); + const numPaths = paths.length; + for (let j = 0; j < numPaths; ++j) { + const updatedPath = cleanPositionalOperators(paths[j]); + key = keys[i]; + // With `$pull` we might flatten `$in`. Skip stuff nested under `$in` + // for the rest of the logic, it will get handled later. + if (updatedPath.includes('$')) { + continue; } - if (typeof val === "object") { - // Only cases where a value does **not** define whether the whole projection - // is inclusive or exclusive are `$meta` and `$slice`. - return !("$meta" in val) && !("$slice" in val); + if (key === '$set' || key === '$setOnInsert' || + key === '$pull' || key === '$pullAll') { + updatedValues[updatedPath] = flat[paths[j]]; + isPull[updatedPath] = key === '$pull' || key === '$pullAll'; + } else if (key === '$unset') { + updatedValues[updatedPath] = undefined; } - return true; - }; + updatedKeys[updatedPath] = true; + } + } + } - /***/ - }, + if (!hasDollarUpdate) { + modifiedPaths(castedDoc, '', modified); + updatedValues = flatten(castedDoc, null, null, schema); + updatedKeys = Object.keys(updatedValues); + } - /***/ 9197: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + const updates = Object.keys(updatedValues); + const numUpdates = updates.length; + const validatorsToExecute = []; + const validationErrors = []; - const isDefiningProjection = __nccwpck_require__(1903); + const alreadyValidated = []; - /*! - * ignore - */ + const context = query; + function iter(i, v) { + const schemaPath = schema._getSchema(updates[i]); + if (schemaPath == null) { + return; + } + if (schemaPath.instance === 'Mixed' && schemaPath.path !== updates[i]) { + return; + } - module.exports = function isExclusive(projection) { - if (projection == null) { - return null; - } + if (v && Array.isArray(v.$in)) { + v.$in.forEach((v, i) => { + validatorsToExecute.push(function(callback) { + schemaPath.doValidate( + v, + function(err) { + if (err) { + err.path = updates[i] + '.$in.' + i; + validationErrors.push(err); + } + callback(null); + }, + context, + { updateValidator: true }); + }); + }); + } else { + if (isPull[updates[i]] && + schemaPath.$isMongooseArray) { + return; + } - const keys = Object.keys(projection); - let ki = keys.length; - let exclude = null; + if (schemaPath.$isMongooseDocumentArrayElement && v != null && v.$__ != null) { + alreadyValidated.push(updates[i]); + validatorsToExecute.push(function(callback) { + schemaPath.doValidate(v, function(err) { + if (err) { + err.path = updates[i]; + validationErrors.push(err); + return callback(null); + } - if (ki === 1 && keys[0] === "_id") { - exclude = !!projection[keys[ki]]; - } else { - while (ki--) { - // Does this projection explicitly define inclusion/exclusion? - // Explicitly avoid `$meta` and `$slice` - if ( - keys[ki] !== "_id" && - isDefiningProjection(projection[keys[ki]]) - ) { - exclude = !projection[keys[ki]]; - break; + v.validate(function(err) { + if (err) { + if (err.errors) { + for (const key of Object.keys(err.errors)) { + const _err = err.errors[key]; + _err.path = updates[i] + '.' + key; + validationErrors.push(_err); + } + } else { + err.path = updates[i]; + validationErrors.push(err); + } + } + callback(null); + }); + }, context, { updateValidator: true }); + }); + } else { + validatorsToExecute.push(function(callback) { + for (const path of alreadyValidated) { + if (updates[i].startsWith(path + '.')) { + return callback(null); } } - } - return exclude; - }; + schemaPath.doValidate(v, function(err) { + if (schemaPath.schema != null && + schemaPath.schema.options.storeSubdocValidationError === false && + err instanceof ValidationError) { + return callback(null); + } - /***/ - }, + if (err) { + err.path = updates[i]; + validationErrors.push(err); + } + callback(null); + }, context, { updateValidator: true }); + }); + } + } + } + for (i = 0; i < numUpdates; ++i) { + iter(i, updatedValues[updates[i]]); + } - /***/ 2951: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + const arrayUpdates = Object.keys(arrayAtomicUpdates); + for (const arrayUpdate of arrayUpdates) { + let schemaPath = schema._getSchema(arrayUpdate); + if (schemaPath && schemaPath.$isMongooseDocumentArray) { + validatorsToExecute.push(function(callback) { + schemaPath.doValidate( + arrayAtomicUpdates[arrayUpdate], + getValidationCallback(arrayUpdate, validationErrors, callback), + options && options.context === 'query' ? query : null); + }); + } else { + schemaPath = schema._getSchema(arrayUpdate + '.0'); + for (const atomicUpdate of arrayAtomicUpdates[arrayUpdate]) { + validatorsToExecute.push(function(callback) { + schemaPath.doValidate( + atomicUpdate, + getValidationCallback(arrayUpdate, validationErrors, callback), + options && options.context === 'query' ? query : null, + { updateValidator: true }); + }); + } + } + } - const isDefiningProjection = __nccwpck_require__(1903); + if (callback != null) { + let numValidators = validatorsToExecute.length; + if (numValidators === 0) { + return _done(callback); + } + for (const validator of validatorsToExecute) { + validator(function() { + if (--numValidators <= 0) { + _done(callback); + } + }); + } - /*! - * ignore - */ + return; + } - module.exports = function isInclusive(projection) { - if (projection == null) { - return false; + return function(callback) { + let numValidators = validatorsToExecute.length; + if (numValidators === 0) { + return _done(callback); + } + for (const validator of validatorsToExecute) { + validator(function() { + if (--numValidators <= 0) { + _done(callback); } + }); + } + }; - const props = Object.keys(projection); - const numProps = props.length; - if (numProps === 0) { - return false; - } + function _done(callback) { + if (validationErrors.length) { + const err = new ValidationError(null); - for (let i = 0; i < numProps; ++i) { - const prop = props[i]; - // Plus paths can't define the projection (see gh-7050) - if (prop.startsWith("+")) { - continue; - } - // If field is truthy (1, true, etc.) and not an object, then this - // projection must be inclusive. If object, assume its $meta, $slice, etc. - if (isDefiningProjection(projection[prop]) && !!projection[prop]) { - return true; - } - } + for (const validationError of validationErrors) { + err.addError(validationError.path, validationError); + } - return false; - }; + return callback(err); + } + callback(null); + } - /***/ - }, + function getValidationCallback(arrayUpdate, validationErrors, callback) { + return function(err) { + if (err) { + err.path = arrayUpdate; + validationErrors.push(err); + } + callback(null); + }; + } +}; - /***/ 1126: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - const isDefiningProjection = __nccwpck_require__(1903); - /*! - * Determines if `path` is excluded by `projection` - * - * @param {Object} projection - * @param {string} path - * @return {Boolean} - */ +/***/ }), - module.exports = function isPathExcluded(projection, path) { - if (path === "_id") { - return projection._id === 0; - } +/***/ 1028: +/***/ ((module, exports, __nccwpck_require__) => { - const paths = Object.keys(projection); - let type = null; +"use strict"; - for (const _path of paths) { - if (isDefiningProjection(projection[_path])) { - type = projection[path] === 1 ? "inclusive" : "exclusive"; - break; - } - } - if (type === "inclusive") { - return projection[path] !== 1; - } - if (type === "exclusive") { - return projection[path] === 0; - } - return false; - }; +/*! + * Module dependencies. + */ - /***/ - }, +__nccwpck_require__(2324).set(__nccwpck_require__(2676)); + +const Document = __nccwpck_require__(6717); +const EventEmitter = __nccwpck_require__(8614).EventEmitter; +const Schema = __nccwpck_require__(7606); +const SchemaType = __nccwpck_require__(5660); +const SchemaTypes = __nccwpck_require__(2987); +const VirtualType = __nccwpck_require__(1423); +const STATES = __nccwpck_require__(932); +const VALID_OPTIONS = __nccwpck_require__(481); +const Types = __nccwpck_require__(3000); +const Query = __nccwpck_require__(1615); +const Model = __nccwpck_require__(7688); +const applyPlugins = __nccwpck_require__(6990); +const driver = __nccwpck_require__(2324); +const get = __nccwpck_require__(8730); +const promiseOrCallback = __nccwpck_require__(4046); +const legacyPluralize = __nccwpck_require__(2145); +const utils = __nccwpck_require__(9232); +const pkg = __nccwpck_require__(306); +const cast = __nccwpck_require__(9179); +const clearValidating = __nccwpck_require__(7560); +const removeSubdocs = __nccwpck_require__(1058); +const saveSubdocs = __nccwpck_require__(7277); +const trackTransaction = __nccwpck_require__(8675); +const validateBeforeSave = __nccwpck_require__(1752); + +const Aggregate = __nccwpck_require__(4336); +const PromiseProvider = __nccwpck_require__(5176); +const shardingPlugin = __nccwpck_require__(94); +const trusted = __nccwpck_require__(7776).trusted; +const sanitizeFilter = __nccwpck_require__(3824); + +const defaultMongooseSymbol = Symbol.for('mongoose:default'); + +__nccwpck_require__(2312); + +/** + * Mongoose constructor. + * + * The exports object of the `mongoose` module is an instance of this class. + * Most apps will only use this one instance. + * + * ####Example: + * const mongoose = require('mongoose'); + * mongoose instanceof mongoose.Mongoose; // true + * + * // Create a new Mongoose instance with its own `connect()`, `set()`, `model()`, etc. + * const m = new mongoose.Mongoose(); + * + * @api public + * @param {Object} options see [`Mongoose#set()` docs](/docs/api/mongoose.html#mongoose_Mongoose-set) + */ +function Mongoose(options) { + this.connections = []; + this.models = {}; + this.events = new EventEmitter(); + // default global options + this.options = Object.assign({ + pluralization: true, + autoIndex: true, + autoCreate: true + }, options); + const conn = this.createConnection(); // default connection + conn.models = this.models; + + if (this.options.pluralization) { + this._pluralize = legacyPluralize; + } - /***/ 2000: /***/ (module) => { - "use strict"; - - /*! - * ignore - */ - - module.exports = function isPathSelectedInclusive(fields, path) { - const chunks = path.split("."); - let cur = ""; - let j; - let keys; - let numKeys; - for (let i = 0; i < chunks.length; ++i) { - cur += cur.length ? "." : "" + chunks[i]; - if (fields[cur]) { - keys = Object.keys(fields); - numKeys = keys.length; - for (j = 0; j < numKeys; ++j) { - if ( - keys[i].indexOf(cur + ".") === 0 && - keys[i].indexOf(path) !== 0 - ) { - continue; - } - } - return true; - } - } + // If a user creates their own Mongoose instance, give them a separate copy + // of the `Schema` constructor so they get separate custom types. (gh-6933) + if (!options || !options[defaultMongooseSymbol]) { + const _this = this; + this.Schema = function() { + this.base = _this; + return Schema.apply(this, arguments); + }; + this.Schema.prototype = Object.create(Schema.prototype); + + Object.assign(this.Schema, Schema); + this.Schema.base = this; + this.Schema.Types = Object.assign({}, Schema.Types); + } else { + // Hack to work around babel's strange behavior with + // `import mongoose, { Schema } from 'mongoose'`. Because `Schema` is not + // an own property of a Mongoose global, Schema will be undefined. See gh-5648 + for (const key of ['Schema', 'model']) { + this[key] = Mongoose.prototype[key]; + } + } + this.Schema.prototype.base = this; + + Object.defineProperty(this, 'plugins', { + configurable: false, + enumerable: true, + writable: false, + value: [ + [saveSubdocs, { deduplicate: true }], + [validateBeforeSave, { deduplicate: true }], + [shardingPlugin, { deduplicate: true }], + [removeSubdocs, { deduplicate: true }], + [trackTransaction, { deduplicate: true }], + [clearValidating, { deduplicate: true }] + ] + }); +} +Mongoose.prototype.cast = cast; +/** + * Expose connection states for user-land + * + * @memberOf Mongoose + * @property STATES + * @api public + */ +Mongoose.prototype.STATES = STATES; - return false; - }; +/** + * Expose connection states for user-land + * + * @memberOf Mongoose + * @property ConnectionStates + * @api public + */ +Mongoose.prototype.ConnectionStates = STATES; - /***/ - }, +/** + * Object with `get()` and `set()` containing the underlying driver this Mongoose instance + * uses to communicate with the database. A driver is a Mongoose-specific interface that defines functions + * like `find()`. + * + * @memberOf Mongoose + * @property driver + * @api public + */ - /***/ 7201: /***/ (module) => { - "use strict"; +Mongoose.prototype.driver = driver; - /** - * Convert a string or array into a projection object, retaining all - * `-` and `+` paths. - */ +/** + * Sets mongoose options + * + * ####Example: + * + * mongoose.set('test', value) // sets the 'test' option to `value` + * + * mongoose.set('debug', true) // enable logging collection methods + arguments to the console/file + * + * mongoose.set('debug', function(collectionName, methodName, ...methodArgs) {}); // use custom function to log collection methods + arguments + * + * Currently supported options are: + * - 'debug': If `true`, prints the operations mongoose sends to MongoDB to the console. If a writable stream is passed, it will log to that stream, without colorization. If a callback function is passed, it will receive the collection name, the method name, then all arugments passed to the method. For example, if you wanted to replicate the default logging, you could output from the callback `Mongoose: ${collectionName}.${methodName}(${methodArgs.join(', ')})`. + * - 'returnOriginal': If `false`, changes the default `returnOriginal` option to `findOneAndUpdate()`, `findByIdAndUpdate`, and `findOneAndReplace()` to false. This is equivalent to setting the `new` option to `true` for `findOneAndX()` calls by default. Read our [`findOneAndUpdate()` tutorial](/docs/tutorials/findoneandupdate.html) for more information. + * - 'bufferCommands': enable/disable mongoose's buffering mechanism for all connections and models + * - 'cloneSchemas': false by default. Set to `true` to `clone()` all schemas before compiling into a model. + * - 'applyPluginsToDiscriminators': false by default. Set to true to apply global plugins to discriminator schemas. This typically isn't necessary because plugins are applied to the base schema and discriminators copy all middleware, methods, statics, and properties from the base schema. + * - 'applyPluginsToChildSchemas': true by default. Set to false to skip applying global plugins to child schemas + * - 'objectIdGetter': true by default. Mongoose adds a getter to MongoDB ObjectId's called `_id` that returns `this` for convenience with populate. Set this to false to remove the getter. + * - 'runValidators': false by default. Set to true to enable [update validators](/docs/validation.html#update-validators) for all validators by default. + * - 'toObject': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toObject()`](/docs/api.html#document_Document-toObject) + * - 'toJSON': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toJSON()`](/docs/api.html#document_Document-toJSON), for determining how Mongoose documents get serialized by `JSON.stringify()` + * - 'strict': true by default, may be `false`, `true`, or `'throw'`. Sets the default strict mode for schemas. + * - 'strictQuery': same value as 'strict' by default (`true`), may be `false`, `true`, or `'throw'`. Sets the default [strictQuery](/docs/guide.html#strictQuery) mode for schemas. + * - 'selectPopulatedPaths': true by default. Set to false to opt out of Mongoose adding all fields that you `populate()` to your `select()`. The schema-level option `selectPopulatedPaths` overwrites this one. + * - 'maxTimeMS': If set, attaches [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) to every query + * - 'autoIndex': true by default. Set to false to disable automatic index creation for all models associated with this Mongoose instance. + * - 'autoCreate': Set to `true` to make Mongoose call [`Model.createCollection()`](/docs/api/model.html#model_Model.createCollection) automatically when you create a model with `mongoose.model()` or `conn.model()`. This is useful for testing transactions, change streams, and other features that require the collection to exist. + * - 'overwriteModels': Set to `true` to default to overwriting models with the same name when calling `mongoose.model()`, as opposed to throwing an `OverwriteModelError`. + * + * @param {String} key + * @param {String|Function|Boolean} value + * @api public + */ - module.exports = function parseProjection(v, retainMinusPaths) { - const type = typeof v; +Mongoose.prototype.set = function(key, value) { + const _mongoose = this instanceof Mongoose ? this : mongoose; - if (type === "string") { - v = v.split(/\s+/); - } - if ( - !Array.isArray(v) && - Object.prototype.toString.call(v) !== "[object Arguments]" - ) { - return v; - } + if (VALID_OPTIONS.indexOf(key) === -1) throw new Error(`\`${key}\` is an invalid option.`); - const len = v.length; - const ret = {}; - for (let i = 0; i < len; ++i) { - let field = v[i]; - if (!field) { - continue; - } - const include = "-" == field[0] ? 0 : 1; - if (!retainMinusPaths && include === 0) { - field = field.substring(1); - } - ret[field] = include; + if (arguments.length === 1) { + return _mongoose.options[key]; + } + + _mongoose.options[key] = value; + + if (key === 'objectIdGetter') { + if (value) { + Object.defineProperty(mongoose.Types.ObjectId.prototype, '_id', { + enumerable: false, + configurable: true, + get: function() { + return this; } + }); + } else { + delete mongoose.Types.ObjectId.prototype._id; + } + } - return ret; - }; + return _mongoose; +}; - /***/ - }, +/** + * Gets mongoose options + * + * ####Example: + * + * mongoose.get('test') // returns the 'test' value + * + * @param {String} key + * @method get + * @api public + */ - /***/ 4046: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const PromiseProvider = __nccwpck_require__(5176); - const immediate = __nccwpck_require__(4830); - - const emittedSymbol = Symbol("mongoose:emitted"); - - module.exports = function promiseOrCallback(callback, fn, ee, Promise) { - if (typeof callback === "function") { - return fn(function (error) { - if (error != null) { - if ( - ee != null && - ee.listeners != null && - ee.listeners("error").length > 0 && - !error[emittedSymbol] - ) { - error[emittedSymbol] = true; - ee.emit("error", error); - } - try { - callback(error); - } catch (error) { - return immediate(() => { - throw error; - }); - } - return; - } - callback.apply(this, arguments); - }); - } +Mongoose.prototype.get = Mongoose.prototype.set; + +/** + * Creates a Connection instance. + * + * Each `connection` instance maps to a single database. This method is helpful when managing multiple db connections. + * + * + * _Options passed take precedence over options included in connection strings._ + * + * ####Example: + * + * // with mongodb:// URI + * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); + * + * // and options + * const opts = { db: { native_parser: true }} + * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts); + * + * // replica sets + * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database'); + * + * // and options + * const opts = { replset: { strategy: 'ping', rs_name: 'testSet' }} + * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts); + * + * // and options + * const opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' } + * db = mongoose.createConnection('localhost', 'database', port, opts) + * + * // initialize now, connect later + * db = mongoose.createConnection(); + * db.openUri('localhost', 'database', port, [opts]); + * + * @param {String} [uri] a mongodb:// URI + * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below. + * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. + * @param {String} [options.dbName] The name of the database you want to use. If not provided, Mongoose uses the database name from connection string. + * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. + * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. + * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. + * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections. + * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above. + * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html). + * @param {Number} [options.maxPoolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). + * @param {Number} [options.minPoolSize=1] The minimum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). + * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback). + * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes. + * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0`, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both. + * @return {Connection} the created Connection object. Connections are thenable, so you can do `await mongoose.createConnection()` + * @api public + */ + +Mongoose.prototype.createConnection = function(uri, options, callback) { + const _mongoose = this instanceof Mongoose ? this : mongoose; + + const conn = new Connection(_mongoose); + if (typeof options === 'function') { + callback = options; + options = null; + } + _mongoose.connections.push(conn); + _mongoose.events.emit('createConnection', conn); - Promise = Promise || PromiseProvider.get(); + if (arguments.length > 0) { + conn.openUri(uri, options, callback); + } + + return conn; +}; + +/** + * Opens the default mongoose connection. + * + * ####Example: + * + * mongoose.connect('mongodb://user:pass@localhost:port/database'); + * + * // replica sets + * const uri = 'mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/mydatabase'; + * mongoose.connect(uri); + * + * // with options + * mongoose.connect(uri, options); + * + * // optional callback that gets fired when initial connection completed + * const uri = 'mongodb://nonexistent.domain:27000'; + * mongoose.connect(uri, function(error) { + * // if error is truthy, the initial connection failed. + * }) + * + * @param {String} uri(s) + * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below. + * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. + * @param {Number} [options.bufferTimeoutMS=10000] Mongoose specific option. If `bufferCommands` is true, Mongoose will throw an error after `bufferTimeoutMS` if the operation is still buffered. + * @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string. + * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. + * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. + * @param {Number} [options.maxPoolSize=100] The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). + * @param {Number} [options.minPoolSize=0] The minimum number of sockets the MongoDB driver will keep open for this connection. + * @param {Number} [options.serverSelectionTimeoutMS] If `useUnifiedTopology = true`, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for `serverSelectionTimeoutMS` milliseconds before erroring out. If not set, the MongoDB driver defaults to using `30000` (30 seconds). + * @param {Number} [options.heartbeatFrequencyMS] If `useUnifiedTopology = true`, the MongoDB driver sends a heartbeat every `heartbeatFrequencyMS` to check on the status of the connection. A heartbeat is subject to `serverSelectionTimeoutMS`, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a `'disconnected'` event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits `'disconnected'`. We recommend you do **not** set this setting below 1000, too many heartbeats can lead to performance degradation. + * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. + * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections. + * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above. + * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html). + * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback). + * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes. + * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0`, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both. + * @param {Boolean} [options.autoCreate=false] Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. + * @param {Function} [callback] + * @see Mongoose#createConnection #index_Mongoose-createConnection + * @api public + * @return {Promise} resolves to `this` if connection succeeded + */ - return new Promise((resolve, reject) => { - fn(function (error, res) { - if (error != null) { - if ( - ee != null && - ee.listeners != null && - ee.listeners("error").length > 0 && - !error[emittedSymbol] - ) { - error[emittedSymbol] = true; - ee.emit("error", error); - } - return reject(error); - } - if (arguments.length > 2) { - return resolve(Array.prototype.slice.call(arguments, 1)); - } - resolve(res); - }); - }); - }; +Mongoose.prototype.connect = function(uri, options, callback) { + const _mongoose = this instanceof Mongoose ? this : mongoose; + const conn = _mongoose.connection; - /***/ - }, + return _mongoose._promiseOrCallback(callback, cb => { + conn.openUri(uri, options, err => { + if (err != null) { + return cb(err); + } + return cb(null, _mongoose); + }); + }); +}; - /***/ 7428: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +/** + * Runs `.close()` on all connections in parallel. + * + * @param {Function} [callback] called after all connection close, or when first error occurred. + * @return {Promise} resolves when all connections are closed, or rejects with the first error that occurred. + * @api public + */ - const utils = __nccwpck_require__(9232); +Mongoose.prototype.disconnect = function(callback) { + const _mongoose = this instanceof Mongoose ? this : mongoose; - module.exports = function applyGlobalMaxTimeMS(options, model) { - if (utils.hasUserDefinedProperty(options, "maxTimeMS")) { - return; + return _mongoose._promiseOrCallback(callback, cb => { + let remaining = _mongoose.connections.length; + if (remaining <= 0) { + return cb(null); + } + _mongoose.connections.forEach(conn => { + conn.close(function(error) { + if (error) { + return cb(error); } - - if (utils.hasUserDefinedProperty(model.db.options, "maxTimeMS")) { - options.maxTimeMS = model.db.options.maxTimeMS; - } else if ( - utils.hasUserDefinedProperty(model.base.options, "maxTimeMS") - ) { - options.maxTimeMS = model.base.options.maxTimeMS; + if (!--remaining) { + cb(null); } - }; + }); + }); + }); +}; - /***/ - }, +/** + * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) + * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), + * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). + * + * Calling `mongoose.startSession()` is equivalent to calling `mongoose.connection.startSession()`. + * Sessions are scoped to a connection, so calling `mongoose.startSession()` + * starts a session on the [default mongoose connection](/docs/api.html#mongoose_Mongoose-connection). + * + * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) + * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency + * @param {Function} [callback] + * @return {Promise} promise that resolves to a MongoDB driver `ClientSession` + * @api public + */ - /***/ 7378: /***/ (module) => { - "use strict"; - - /*! - * ignore - */ - - module.exports = applyQueryMiddleware; - - /*! - * ignore - */ - - applyQueryMiddleware.middlewareFunctions = [ - "count", - "countDocuments", - "deleteMany", - "deleteOne", - "distinct", - "estimatedDocumentCount", - "find", - "findOne", - "findOneAndDelete", - "findOneAndRemove", - "findOneAndReplace", - "findOneAndUpdate", - "remove", - "replaceOne", - "update", - "updateMany", - "updateOne", - "validate", - ]; +Mongoose.prototype.startSession = function() { + const _mongoose = this instanceof Mongoose ? this : mongoose; - /*! - * Apply query middleware - * - * @param {Query} query constructor - * @param {Model} model - */ - - function applyQueryMiddleware(Query, model) { - const kareemOptions = { - useErrorHandlers: true, - numCallbackParams: 1, - nullResultByDefault: true, - }; + return _mongoose.connection.startSession.apply(_mongoose.connection, arguments); +}; - const middleware = model.hooks.filter((hook) => { - const contexts = _getContexts(hook); - if (hook.name === "updateOne") { - return contexts.query == null || !!contexts.query; - } - if (hook.name === "deleteOne") { - return !!contexts.query || Object.keys(contexts).length === 0; - } - if (hook.name === "validate" || hook.name === "remove") { - return !!contexts.query; - } - if (hook.query != null || hook.document != null) { - return !!hook.query; - } - return true; - }); +/** + * Getter/setter around function for pluralizing collection names. + * + * @param {Function|null} [fn] overwrites the function used to pluralize collection names + * @return {Function|null} the current function used to pluralize collection names, defaults to the legacy function from `mongoose-legacy-pluralize`. + * @api public + */ - // `update()` thunk has a different name because `_update` was already taken - Query.prototype._execUpdate = middleware.createWrapper( - "update", - Query.prototype._execUpdate, - null, - kareemOptions - ); - // `distinct()` thunk has a different name because `_distinct` was already taken - Query.prototype.__distinct = middleware.createWrapper( - "distinct", - Query.prototype.__distinct, - null, - kareemOptions - ); +Mongoose.prototype.pluralize = function(fn) { + const _mongoose = this instanceof Mongoose ? this : mongoose; - // `validate()` doesn't have a thunk because it doesn't execute a query. - Query.prototype.validate = middleware.createWrapper( - "validate", - Query.prototype.validate, - null, - kareemOptions - ); + if (arguments.length > 0) { + _mongoose._pluralize = fn; + } + return _mongoose._pluralize; +}; - applyQueryMiddleware.middlewareFunctions - .filter((v) => v !== "update" && v !== "distinct" && v !== "validate") - .forEach((fn) => { - Query.prototype[`_${fn}`] = middleware.createWrapper( - fn, - Query.prototype[`_${fn}`], - null, - kareemOptions - ); - }); - } +/** + * Defines a model or retrieves it. + * + * Models defined on the `mongoose` instance are available to all connection + * created by the same `mongoose` instance. + * + * If you call `mongoose.model()` with twice the same name but a different schema, + * you will get an `OverwriteModelError`. If you call `mongoose.model()` with + * the same name and same schema, you'll get the same schema back. + * + * ####Example: + * + * const mongoose = require('mongoose'); + * + * // define an Actor model with this mongoose instance + * const schema = new Schema({ name: String }); + * mongoose.model('Actor', schema); + * + * // create a new connection + * const conn = mongoose.createConnection(..); + * + * // create Actor model + * const Actor = conn.model('Actor', schema); + * conn.model('Actor') === Actor; // true + * conn.model('Actor', schema) === Actor; // true, same schema + * conn.model('Actor', schema, 'actors') === Actor; // true, same schema and collection name + * + * // This throws an `OverwriteModelError` because the schema is different. + * conn.model('Actor', new Schema({ name: String })); + * + * _When no `collection` argument is passed, Mongoose uses the model name. If you don't like this behavior, either pass a collection name, use `mongoose.pluralize()`, or set your schemas collection name option._ + * + * ####Example: + * + * const schema = new Schema({ name: String }, { collection: 'actor' }); + * + * // or + * + * schema.set('collection', 'actor'); + * + * // or + * + * const collectionName = 'actor' + * const M = mongoose.model('Actor', schema, collectionName) + * + * @param {String|Function} name model name or class extending Model + * @param {Schema} [schema] the schema to use. + * @param {String} [collection] name (optional, inferred from model name) + * @return {Model} The model associated with `name`. Mongoose will create the model if it doesn't already exist. + * @api public + */ - function _getContexts(hook) { - const ret = {}; - if (hook.hasOwnProperty("query")) { - ret.query = hook.query; - } - if (hook.hasOwnProperty("document")) { - ret.document = hook.document; - } - return ret; - } +Mongoose.prototype.model = function(name, schema, collection, options) { + const _mongoose = this instanceof Mongoose ? this : mongoose; - /***/ - }, + if (typeof schema === 'string') { + collection = schema; + schema = false; + } - /***/ 8045: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + if (utils.isObject(schema) && !(schema instanceof Schema)) { + schema = new Schema(schema); + } + if (schema && !(schema instanceof Schema)) { + throw new Error('The 2nd parameter to `mongoose.model()` should be a ' + + 'schema or a POJO'); + } - const isOperator = __nccwpck_require__(3342); + // handle internal options from connection.model() + options = options || {}; - module.exports = function castFilterPath(query, schematype, val) { - const ctx = query; - const any$conditionals = Object.keys(val).some(isOperator); + const originalSchema = schema; + if (schema) { + if (_mongoose.get('cloneSchemas')) { + schema = schema.clone(); + } + _mongoose._applyPlugins(schema); + } - if (!any$conditionals) { - return schematype.castForQueryWrapper({ - val: val, - context: ctx, - }); - } + // connection.model() may be passing a different schema for + // an existing model name. in this case don't read from cache. + const overwriteModels = _mongoose.options.hasOwnProperty('overwriteModels') ? + _mongoose.options.overwriteModels : + options.overwriteModels; + if (_mongoose.models.hasOwnProperty(name) && options.cache !== false && overwriteModels !== true) { + if (originalSchema && + originalSchema.instanceOfSchema && + originalSchema !== _mongoose.models[name].schema) { + throw new _mongoose.Error.OverwriteModelError(name); + } + if (collection && collection !== _mongoose.models[name].collection.name) { + // subclass current model with alternate collection + const model = _mongoose.models[name]; + schema = model.prototype.schema; + const sub = model.__subclass(_mongoose.connection, schema, collection); + // do not cache the sub model + return sub; + } + return _mongoose.models[name]; + } + if (schema == null) { + throw new _mongoose.Error.MissingSchemaError(name); + } - const ks = Object.keys(val); + const model = _mongoose._model(name, schema, collection, options); - let k = ks.length; + _mongoose.connection.models[name] = model; + _mongoose.models[name] = model; - while (k--) { - const $cond = ks[k]; - const nested = val[$cond]; + return model; +}; - if ($cond === "$not") { - if (nested && schematype && !schematype.caster) { - const _keys = Object.keys(nested); - if (_keys.length && isOperator(_keys[0])) { - for (const key of Object.keys(nested)) { - nested[key] = schematype.castForQueryWrapper({ - $conditional: key, - val: nested[key], - context: ctx, - }); - } - } else { - val[$cond] = schematype.castForQueryWrapper({ - $conditional: $cond, - val: nested, - context: ctx, - }); - } - continue; - } - // cast(schematype.caster ? schematype.caster.schema : schema, nested, options, context); - } else { - val[$cond] = schematype.castForQueryWrapper({ - $conditional: $cond, - val: nested, - context: ctx, - }); - } - } +/*! + * ignore + */ - return val; - }; +Mongoose.prototype._model = function(name, schema, collection, options) { + const _mongoose = this instanceof Mongoose ? this : mongoose; - /***/ - }, + let model; + if (typeof name === 'function') { + model = name; + name = model.name; + if (!(model.prototype instanceof Model)) { + throw new _mongoose.Error('The provided class ' + name + ' must extend Model'); + } + } - /***/ 3303: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const CastError = __nccwpck_require__(2798); - const MongooseError = __nccwpck_require__(5953); - const StrictModeError = __nccwpck_require__(703); - const ValidationError = __nccwpck_require__(8460); - const castNumber = __nccwpck_require__(1582); - const cast = __nccwpck_require__(8874); - const getConstructorName = __nccwpck_require__(7323); - const getEmbeddedDiscriminatorPath = __nccwpck_require__(5087); - const handleImmutable = __nccwpck_require__(8176); - const moveImmutableProperties = __nccwpck_require__(4632); - const schemaMixedSymbol = __nccwpck_require__(1205).schemaMixedSymbol; - const setDottedPath = __nccwpck_require__(9152); - const utils = __nccwpck_require__(9232); - - /*! - * Casts an update op based on the given schema - * - * @param {Schema} schema - * @param {Object} obj - * @param {Object} options - * @param {Boolean} [options.overwrite] defaults to false - * @param {Boolean|String} [options.strict] defaults to true - * @param {Query} context passed to setters - * @return {Boolean} true iff the update is non-empty - */ - - module.exports = function castUpdate( - schema, - obj, - options, - context, - filter - ) { - if (obj == null) { - return undefined; - } - options = options || {}; + if (schema) { + if (_mongoose.get('cloneSchemas')) { + schema = schema.clone(); + } + _mongoose._applyPlugins(schema); + } - // Update pipeline - if (Array.isArray(obj)) { - const len = obj.length; - for (let i = 0; i < len; ++i) { - const ops = Object.keys(obj[i]); - for (const op of ops) { - obj[i][op] = castPipelineOperator(op, obj[i][op]); - } - } - return obj; - } + // Apply relevant "global" options to the schema + if (schema == null || !('pluralization' in schema.options)) { + schema.options.pluralization = _mongoose.options.pluralization; + } - if (options.upsert) { - moveImmutableProperties(schema, obj, context); - } + if (!collection) { + collection = schema.get('collection') || + utils.toCollectionName(name, _mongoose.pluralize()); + } - const ops = Object.keys(obj); - let i = ops.length; - const ret = {}; - let val; - let hasDollarKey = false; - const overwrite = options.overwrite; + const connection = options.connection || _mongoose.connection; + model = _mongoose.Model.compile(model || name, schema, collection, connection, _mongoose); - filter = filter || {}; + // Errors handled internally, so safe to ignore error + model.init(function $modelInitNoop() {}); - while (i--) { - const op = ops[i]; - // if overwrite is set, don't do any of the special $set stuff - if (op[0] !== "$" && !overwrite) { - // fix up $set sugar - if (!ret.$set) { - if (obj.$set) { - ret.$set = obj.$set; - } else { - ret.$set = {}; - } - } - ret.$set[op] = obj[op]; - ops.splice(i, 1); - if (!~ops.indexOf("$set")) ops.push("$set"); - } else if (op === "$set") { - if (!ret.$set) { - ret[op] = obj[op]; - } - } else { - ret[op] = obj[op]; - } - } + connection.emit('model', model); - // cast each value - i = ops.length; + return model; +}; - while (i--) { - const op = ops[i]; - val = ret[op]; - hasDollarKey = hasDollarKey || op.startsWith("$"); +/** + * Removes the model named `name` from the default connection, if it exists. + * You can use this function to clean up any models you created in your tests to + * prevent OverwriteModelErrors. + * + * Equivalent to `mongoose.connection.deleteModel(name)`. + * + * ####Example: + * + * mongoose.model('User', new Schema({ name: String })); + * console.log(mongoose.model('User')); // Model object + * mongoose.deleteModel('User'); + * console.log(mongoose.model('User')); // undefined + * + * // Usually useful in a Mocha `afterEach()` hook + * afterEach(function() { + * mongoose.deleteModel(/.+/); // Delete every model + * }); + * + * @api public + * @param {String|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. + * @return {Mongoose} this + */ - if ( - val && - typeof val === "object" && - !Buffer.isBuffer(val) && - (!overwrite || hasDollarKey) - ) { - walkUpdatePath(schema, val, op, options, context, filter); - } else if (overwrite && ret && typeof ret === "object") { - walkUpdatePath(schema, ret, "$set", options, context, filter); - } else { - const msg = - "Invalid atomic update value for " + - op + - ". " + - "Expected an object, received " + - typeof val; - throw new Error(msg); - } +Mongoose.prototype.deleteModel = function(name) { + const _mongoose = this instanceof Mongoose ? this : mongoose; - if (op.startsWith("$") && utils.isEmptyObject(val)) { - delete ret[op]; - } - } + _mongoose.connection.deleteModel(name); + delete _mongoose.models[name]; + return _mongoose; +}; - if ( - Object.keys(ret).length === 0 && - options.upsert && - Object.keys(filter).length > 0 - ) { - // Trick the driver into allowing empty upserts to work around - // https://github.com/mongodb/node-mongodb-native/pull/2490 - return { $setOnInsert: filter }; - } +/** + * Returns an array of model names created on this instance of Mongoose. + * + * ####Note: + * + * _Does not include names of models created using `connection.model()`._ + * + * @api public + * @return {Array} + */ - return ret; - }; +Mongoose.prototype.modelNames = function() { + const _mongoose = this instanceof Mongoose ? this : mongoose; - /*! - * ignore - */ + const names = Object.keys(_mongoose.models); + return names; +}; - function castPipelineOperator(op, val) { - if (op === "$unset") { - if (!Array.isArray(val) || val.find((v) => typeof v !== "string")) { - throw new MongooseError( - "Invalid $unset in pipeline, must be " + "an array of strings" - ); - } - return val; - } - if (op === "$project") { - if (val == null || typeof val !== "object") { - throw new MongooseError( - "Invalid $project in pipeline, must be an object" - ); - } - return val; - } - if (op === "$addFields" || op === "$set") { - if (val == null || typeof val !== "object") { - throw new MongooseError( - "Invalid " + op + " in pipeline, must be an object" - ); - } - return val; - } else if (op === "$replaceRoot" || op === "$replaceWith") { - if (val == null || typeof val !== "object") { - throw new MongooseError( - "Invalid " + op + " in pipeline, must be an object" - ); - } - return val; - } +/** + * Applies global plugins to `schema`. + * + * @param {Schema} schema + * @api private + */ - throw new MongooseError( - 'Invalid update pipeline operator: "' + op + '"' - ); - } +Mongoose.prototype._applyPlugins = function(schema, options) { + const _mongoose = this instanceof Mongoose ? this : mongoose; - /*! - * Walk each path of obj and cast its values - * according to its schema. - * - * @param {Schema} schema - * @param {Object} obj - part of a query - * @param {String} op - the atomic operator ($pull, $set, etc) - * @param {Object} options - * @param {Boolean|String} [options.strict] - * @param {Boolean} [options.omitUndefined] - * @param {Query} context - * @param {String} pref - path prefix (internal only) - * @return {Bool} true if this path has keys to update - * @api private - */ - - function walkUpdatePath(schema, obj, op, options, context, filter, pref) { - const strict = options.strict; - const prefix = pref ? pref + "." : ""; - const keys = Object.keys(obj); - let i = keys.length; - let hasKeys = false; - let schematype; - let key; - let val; - - let aggregatedError = null; - - let useNestedStrict; - if (options.useNestedStrict === undefined) { - useNestedStrict = schema.options.useNestedStrict; - } else { - useNestedStrict = options.useNestedStrict; - } + options = options || {}; + options.applyPluginsToDiscriminators = get(_mongoose, + 'options.applyPluginsToDiscriminators', false); + options.applyPluginsToChildSchemas = get(_mongoose, + 'options.applyPluginsToChildSchemas', true); + applyPlugins(schema, _mongoose.plugins, options, '$globalPluginsApplied'); +}; - while (i--) { - key = keys[i]; - val = obj[key]; +/** + * Declares a global plugin executed on all Schemas. + * + * Equivalent to calling `.plugin(fn)` on each Schema you create. + * + * @param {Function} fn plugin callback + * @param {Object} [opts] optional options + * @return {Mongoose} this + * @see plugins ./plugins.html + * @api public + */ - // `$pull` is special because we need to cast the RHS as a query, not as - // an update. - if (op === "$pull") { - schematype = schema._getSchema(prefix + key); - if (schematype != null && schematype.schema != null) { - obj[key] = cast(schematype.schema, obj[key], options, context); - hasKeys = true; - continue; - } - } +Mongoose.prototype.plugin = function(fn, opts) { + const _mongoose = this instanceof Mongoose ? this : mongoose; - if (getConstructorName(val) === "Object") { - // watch for embedded doc schemas - schematype = schema._getSchema(prefix + key); + _mongoose.plugins.push([fn, opts]); + return _mongoose; +}; - if (schematype == null) { - const _res = getEmbeddedDiscriminatorPath( - schema, - obj, - filter, - prefix + key, - options - ); - if (_res.schematype != null) { - schematype = _res.schematype; - } - } +/** + * The Mongoose module's default connection. Equivalent to `mongoose.connections[0]`, see [`connections`](#mongoose_Mongoose-connections). + * + * ####Example: + * + * const mongoose = require('mongoose'); + * mongoose.connect(...); + * mongoose.connection.on('error', cb); + * + * This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model). + * + * To create a new connection, use [`createConnection()`](#mongoose_Mongoose-createConnection). + * + * @memberOf Mongoose + * @instance + * @property {Connection} connection + * @api public + */ - if ( - op !== "$setOnInsert" && - handleImmutable( - schematype, - strict, - obj, - key, - prefix + key, - context - ) - ) { - continue; - } +Mongoose.prototype.__defineGetter__('connection', function() { + return this.connections[0]; +}); - if (schematype && schematype.caster && op in castOps) { - // embedded doc schema - if ("$each" in val) { - hasKeys = true; - try { - obj[key] = { - $each: castUpdateVal( - schematype, - val.$each, - op, - key, - context, - prefix + key - ), - }; - } catch (error) { - aggregatedError = _handleCastError( - error, - context, - key, - aggregatedError - ); - } +Mongoose.prototype.__defineSetter__('connection', function(v) { + if (v instanceof Connection) { + this.connections[0] = v; + this.models = v.models; + } +}); - if (val.$slice != null) { - obj[key].$slice = val.$slice | 0; - } +/** + * An array containing all [connections](connections.html) associated with this + * Mongoose instance. By default, there is 1 connection. Calling + * [`createConnection()`](#mongoose_Mongoose-createConnection) adds a connection + * to this array. + * + * ####Example: + * + * const mongoose = require('mongoose'); + * mongoose.connections.length; // 1, just the default connection + * mongoose.connections[0] === mongoose.connection; // true + * + * mongoose.createConnection('mongodb://localhost:27017/test'); + * mongoose.connections.length; // 2 + * + * @memberOf Mongoose + * @instance + * @property {Array} connections + * @api public + */ - if (val.$sort) { - obj[key].$sort = val.$sort; - } +Mongoose.prototype.connections; - if (val.$position != null) { - obj[key].$position = castNumber(val.$position); - } - } else { - if (schematype != null && schematype.$isSingleNested) { - // Special case to make sure `strict` bubbles down correctly to - // single nested re: gh-8735 - let _strict = strict; - if ( - useNestedStrict !== false && - schematype.schema.options.hasOwnProperty("strict") - ) { - _strict = schematype.schema.options.strict; - } else if (useNestedStrict === false) { - _strict = schema.options.strict; - } - try { - obj[key] = schematype.castForQuery(val, context, { - strict: _strict, - }); - } catch (error) { - aggregatedError = _handleCastError( - error, - context, - key, - aggregatedError - ); - } - } else { - try { - obj[key] = castUpdateVal( - schematype, - val, - op, - key, - context, - prefix + key - ); - } catch (error) { - aggregatedError = _handleCastError( - error, - context, - key, - aggregatedError - ); - } - } +/*! + * Connection + */ - if (options.omitUndefined && obj[key] === void 0) { - delete obj[key]; - continue; - } +const Connection = driver.get().getConnection(); - hasKeys = true; - } - } else if (op === "$currentDate" || (op in castOps && schematype)) { - // $currentDate can take an object - try { - obj[key] = castUpdateVal( - schematype, - val, - op, - key, - context, - prefix + key - ); - } catch (error) { - aggregatedError = _handleCastError( - error, - context, - key, - aggregatedError - ); - } +/*! + * Collection + */ - if (options.omitUndefined && obj[key] === void 0) { - delete obj[key]; - continue; - } +const Collection = driver.get().Collection; - hasKeys = true; - } else { - const pathToCheck = prefix + key; - const v = schema._getPathType(pathToCheck); - let _strict = strict; - if ( - useNestedStrict && - v && - v.schema && - "strict" in v.schema.options - ) { - _strict = v.schema.options.strict; - } +/** + * The Mongoose Aggregate constructor + * + * @method Aggregate + * @api public + */ - if (v.pathType === "undefined") { - if (_strict === "throw") { - throw new StrictModeError(pathToCheck); - } else if (_strict) { - delete obj[key]; - continue; - } - } +Mongoose.prototype.Aggregate = Aggregate; - // gh-2314 - // we should be able to set a schema-less field - // to an empty object literal - hasKeys |= - walkUpdatePath( - schema, - val, - op, - options, - context, - filter, - prefix + key - ) || - (utils.isObject(val) && Object.keys(val).length === 0); - } - } else { - const checkPath = - key === "$each" || - key === "$or" || - key === "$and" || - key === "$in" - ? pref - : prefix + key; - schematype = schema._getSchema(checkPath); - - // You can use `$setOnInsert` with immutable keys - if ( - op !== "$setOnInsert" && - handleImmutable( - schematype, - strict, - obj, - key, - prefix + key, - context - ) - ) { - continue; - } +/** + * The Mongoose Collection constructor + * + * @method Collection + * @api public + */ - let pathDetails = schema._getPathType(checkPath); +Mongoose.prototype.Collection = Collection; - // If no schema type, check for embedded discriminators because the - // filter or update may imply an embedded discriminator type. See #8378 - if (schematype == null) { - const _res = getEmbeddedDiscriminatorPath( - schema, - obj, - filter, - checkPath, - options - ); - if (_res.schematype != null) { - schematype = _res.schematype; - pathDetails = _res.type; - } - } +/** + * The Mongoose [Connection](#connection_Connection) constructor + * + * @memberOf Mongoose + * @instance + * @method Connection + * @api public + */ - let isStrict = strict; - if ( - useNestedStrict && - pathDetails && - pathDetails.schema && - "strict" in pathDetails.schema.options - ) { - isStrict = pathDetails.schema.options.strict; - } +Mongoose.prototype.Connection = Connection; - const skip = - isStrict && - !schematype && - !/real|nested/.test(pathDetails.pathType); +/** + * The Mongoose version + * + * #### Example + * + * console.log(mongoose.version); // '5.x.x' + * + * @property version + * @api public + */ - if (skip) { - // Even if strict is `throw`, avoid throwing an error because of - // virtuals because of #6731 - if (isStrict === "throw" && schema.virtuals[checkPath] == null) { - throw new StrictModeError(prefix + key); - } else { - delete obj[key]; - } - } else { - // gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking - // improving this. - if (op === "$rename") { - hasKeys = true; - continue; - } +Mongoose.prototype.version = pkg.version; - try { - if (prefix.length === 0 || key.indexOf(".") === -1) { - obj[key] = castUpdateVal( - schematype, - val, - op, - key, - context, - prefix + key - ); - } else { - // Setting a nested dotted path that's in the schema. We don't allow paths with '.' in - // a schema, so replace the dotted path with a nested object to avoid ending up with - // dotted properties in the updated object. See (gh-10200) - setDottedPath( - obj, - key, - castUpdateVal( - schematype, - val, - op, - key, - context, - prefix + key - ) - ); - delete obj[key]; - } - } catch (error) { - aggregatedError = _handleCastError( - error, - context, - key, - aggregatedError - ); - } +/** + * The Mongoose constructor + * + * The exports of the mongoose module is an instance of this class. + * + * ####Example: + * + * const mongoose = require('mongoose'); + * const mongoose2 = new mongoose.Mongoose(); + * + * @method Mongoose + * @api public + */ - if ( - Array.isArray(obj[key]) && - (op === "$addToSet" || op === "$push") && - key !== "$each" - ) { - if ( - schematype && - schematype.caster && - !schematype.caster.$isMongooseArray - ) { - obj[key] = { $each: obj[key] }; - } - } +Mongoose.prototype.Mongoose = Mongoose; - if (options.omitUndefined && obj[key] === void 0) { - delete obj[key]; - continue; - } +/** + * The Mongoose [Schema](#schema_Schema) constructor + * + * ####Example: + * + * const mongoose = require('mongoose'); + * const Schema = mongoose.Schema; + * const CatSchema = new Schema(..); + * + * @method Schema + * @api public + */ - hasKeys = true; - } - } - } +Mongoose.prototype.Schema = Schema; - if (aggregatedError != null) { - throw aggregatedError; - } +/** + * The Mongoose [SchemaType](#schematype_SchemaType) constructor + * + * @method SchemaType + * @api public + */ - return hasKeys; - } +Mongoose.prototype.SchemaType = SchemaType; - /*! - * ignore - */ +/** + * The various Mongoose SchemaTypes. + * + * ####Note: + * + * _Alias of mongoose.Schema.Types for backwards compatibility._ + * + * @property SchemaTypes + * @see Schema.SchemaTypes #schema_Schema.Types + * @api public + */ - function _handleCastError(error, query, key, aggregatedError) { - if (typeof query !== "object" || !query.options.multipleCastError) { - throw error; - } - aggregatedError = aggregatedError || new ValidationError(); - aggregatedError.addError(key, error); - return aggregatedError; - } +Mongoose.prototype.SchemaTypes = Schema.Types; - /*! - * These operators should be cast to numbers instead - * of their path schema type. - */ +/** + * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor + * + * @method VirtualType + * @api public + */ - const numberOps = { - $pop: 1, - $inc: 1, - }; +Mongoose.prototype.VirtualType = VirtualType; - /*! - * These ops require no casting because the RHS doesn't do anything. - */ +/** + * The various Mongoose Types. + * + * ####Example: + * + * const mongoose = require('mongoose'); + * const array = mongoose.Types.Array; + * + * ####Types: + * + * - [Array](/docs/schematypes.html#arrays) + * - [Buffer](/docs/schematypes.html#buffers) + * - [Embedded](/docs/schematypes.html#schemas) + * - [DocumentArray](/docs/api/documentarraypath.html) + * - [Decimal128](/docs/api.html#mongoose_Mongoose-Decimal128) + * - [ObjectId](/docs/schematypes.html#objectids) + * - [Map](/docs/schematypes.html#maps) + * - [Subdocument](/docs/schematypes.html#schemas) + * + * Using this exposed access to the `ObjectId` type, we can construct ids on demand. + * + * const ObjectId = mongoose.Types.ObjectId; + * const id1 = new ObjectId; + * + * @property Types + * @api public + */ - const noCastOps = { - $unset: 1, - }; +Mongoose.prototype.Types = Types; - /*! - * These operators require casting docs - * to real Documents for Update operations. - */ +/** + * The Mongoose [Query](#query_Query) constructor. + * + * @method Query + * @api public + */ - const castOps = { - $push: 1, - $addToSet: 1, - $set: 1, - $setOnInsert: 1, - }; +Mongoose.prototype.Query = Query; - /*! - * ignore - */ +/** + * The Mongoose [Promise](#promise_Promise) constructor. + * + * @memberOf Mongoose + * @instance + * @property Promise + * @api public + */ - const overwriteOps = { - $set: 1, - $setOnInsert: 1, - }; +Object.defineProperty(Mongoose.prototype, 'Promise', { + get: function() { + return PromiseProvider.get(); + }, + set: function(lib) { + PromiseProvider.set(lib); + } +}); - /*! - * Casts `val` according to `schema` and atomic `op`. - * - * @param {SchemaType} schema - * @param {Object} val - * @param {String} op - the atomic operator ($pull, $set, etc) - * @param {String} $conditional - * @param {Query} context - * @api private - */ - - function castUpdateVal(schema, val, op, $conditional, context, path) { - if (!schema) { - // non-existing schema path - if (op in numberOps) { - try { - return castNumber(val); - } catch (err) { - throw new CastError("number", val, path); - } - } - return val; - } +/** + * Storage layer for mongoose promises + * + * @method PromiseProvider + * @api public + */ - const cond = - schema.caster && - op in castOps && - (utils.isObject(val) || Array.isArray(val)); - if (cond && !overwriteOps[op]) { - // Cast values for ops that add data to MongoDB. - // Ensures embedded documents get ObjectIds etc. - let schemaArrayDepth = 0; - let cur = schema; - while (cur.$isMongooseArray) { - ++schemaArrayDepth; - cur = cur.caster; - } - let arrayDepth = 0; - let _val = val; - while (Array.isArray(_val)) { - ++arrayDepth; - _val = _val[0]; - } +Mongoose.prototype.PromiseProvider = PromiseProvider; - const additionalNesting = schemaArrayDepth - arrayDepth; - while (arrayDepth < schemaArrayDepth) { - val = [val]; - ++arrayDepth; - } +/** + * The Mongoose [Model](#model_Model) constructor. + * + * @method Model + * @api public + */ - let tmp = schema.applySetters( - Array.isArray(val) ? val : [val], - context - ); +Mongoose.prototype.Model = Model; - for (let i = 0; i < additionalNesting; ++i) { - tmp = tmp[0]; - } - return tmp; - } +/** + * The Mongoose [Document](/api/document.html) constructor. + * + * @method Document + * @api public + */ - if (op in noCastOps) { - return val; - } - if (op in numberOps) { - // Null and undefined not allowed for $pop, $inc - if (val == null) { - throw new CastError("number", val, schema.path); - } - if (op === "$inc") { - // Support `$inc` with long, int32, etc. (gh-4283) - return schema.castForQueryWrapper({ - val: val, - context: context, - }); - } - try { - return castNumber(val); - } catch (error) { - throw new CastError("number", val, schema.path); - } - } - if (op === "$currentDate") { - if (typeof val === "object") { - return { $type: val.$type }; - } - return Boolean(val); - } +Mongoose.prototype.Document = Document; - if (/^\$/.test($conditional)) { - return schema.castForQueryWrapper({ - $conditional: $conditional, - val: val, - context: context, - }); - } +/** + * The Mongoose DocumentProvider constructor. Mongoose users should not have to + * use this directly + * + * @method DocumentProvider + * @api public + */ - if (overwriteOps[op]) { - return schema.castForQueryWrapper({ - val: val, - context: context, - $skipQueryCastForUpdate: - val != null && - schema.$isMongooseArray && - schema.$fullPath != null && - !schema.$fullPath.match(/\d+$/), - $applySetters: schema[schemaMixedSymbol] != null, - }); - } +Mongoose.prototype.DocumentProvider = __nccwpck_require__(1860); - return schema.castForQueryWrapper({ val: val, context: context }); - } +/** + * The Mongoose ObjectId [SchemaType](/docs/schematypes.html). Used for + * declaring paths in your schema that should be + * [MongoDB ObjectIds](https://docs.mongodb.com/manual/reference/method/ObjectId/). + * Do not use this to create a new ObjectId instance, use `mongoose.Types.ObjectId` + * instead. + * + * ####Example: + * + * const childSchema = new Schema({ parentId: mongoose.ObjectId }); + * + * @property ObjectId + * @api public + */ - /***/ - }, +Mongoose.prototype.ObjectId = SchemaTypes.ObjectId; - /***/ 2941: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const helpers = __nccwpck_require__(5299); - const immediate = __nccwpck_require__(4830); - - module.exports = completeMany; - - /*! - * Given a model and an array of docs, hydrates all the docs to be instances - * of the model. Used to initialize docs returned from the db from `find()` - * - * @param {Model} model - * @param {Array} docs - * @param {Object} fields the projection used, including `select` from schemas - * @param {Object} userProvidedFields the user-specified projection - * @param {Object} opts - * @param {Array} [opts.populated] - * @param {ClientSession} [opts.session] - * @param {Function} callback - */ - - function completeMany( - model, - docs, - fields, - userProvidedFields, - opts, - callback - ) { - const arr = []; - let count = docs.length; - const len = count; - let error = null; - - function init(_error) { - if (_error != null) { - error = error || _error; - } - if (error != null) { - --count || immediate(() => callback(error)); - return; - } - --count || immediate(() => callback(error, arr)); - } +/** + * Returns true if Mongoose can cast the given value to an ObjectId, or + * false otherwise. + * + * ####Example: + * + * mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true + * mongoose.isValidObjectId('0123456789ab'); // true + * mongoose.isValidObjectId(6); // false + * + * @method isValidObjectId + * @api public + */ - for (let i = 0; i < len; ++i) { - arr[i] = helpers.createModel( - model, - docs[i], - fields, - userProvidedFields - ); - try { - arr[i].init(docs[i], opts, init); - } catch (error) { - init(error); - } +Mongoose.prototype.isValidObjectId = function(v) { + if (v == null) { + return true; + } + const base = this || mongoose; + const ObjectId = base.driver.get().ObjectId; + if (v instanceof ObjectId) { + return true; + } - if (opts.session != null) { - arr[i].$session(opts.session); - } - } + if (v._id != null) { + if (v._id instanceof ObjectId) { + return true; + } + if (v._id.toString instanceof Function) { + v = v._id.toString(); + if (typeof v === 'string' && v.length === 12) { + return true; } + if (typeof v === 'string' && /^[0-9A-Fa-f]{24}$/.test(v)) { + return true; + } + return false; + } + } - /***/ - }, - - /***/ 5087: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const cleanPositionalOperators = __nccwpck_require__(1119); - const get = __nccwpck_require__(8730); - const getDiscriminatorByValue = __nccwpck_require__(8689); - const updatedPathsByArrayFilter = __nccwpck_require__(6507); - - /*! - * Like `schema.path()`, except with a document, because impossible to - * determine path type without knowing the embedded discriminator key. - */ - - module.exports = function getEmbeddedDiscriminatorPath( - schema, - update, - filter, - path, - options - ) { - const parts = path.split("."); - let schematype = null; - let type = "adhocOrUndefined"; - - filter = filter || {}; - update = update || {}; - const arrayFilters = - options != null && Array.isArray(options.arrayFilters) - ? options.arrayFilters - : []; - const updatedPathsByFilter = updatedPathsByArrayFilter(update); - - for (let i = 0; i < parts.length; ++i) { - const subpath = cleanPositionalOperators( - parts.slice(0, i + 1).join(".") - ); - schematype = schema.path(subpath); - if (schematype == null) { - continue; - } + if (v.toString instanceof Function) { + v = v.toString(); + } - type = schema.pathType(subpath); - if ( - (schematype.$isSingleNested || - schematype.$isMongooseDocumentArrayElement) && - schematype.schema.discriminators != null - ) { - const key = get(schematype, "schema.options.discriminatorKey"); - const discriminatorValuePath = subpath + "." + key; - const discriminatorFilterPath = discriminatorValuePath.replace( - /\.\d+\./, - "." - ); - let discriminatorKey = null; + if (typeof v === 'string' && v.length === 12) { + return true; + } + if (typeof v === 'string' && /^[0-9A-Fa-f]{24}$/.test(v)) { + return true; + } - if (discriminatorValuePath in filter) { - discriminatorKey = filter[discriminatorValuePath]; - } - if (discriminatorFilterPath in filter) { - discriminatorKey = filter[discriminatorFilterPath]; - } + return false; +}; - const wrapperPath = subpath.replace(/\.\d+$/, ""); - if ( - schematype.$isMongooseDocumentArrayElement && - get(filter[wrapperPath], "$elemMatch." + key) != null - ) { - discriminatorKey = filter[wrapperPath].$elemMatch[key]; - } +Mongoose.prototype.syncIndexes = function() { + const _mongoose = this instanceof Mongoose ? this : mongoose; + return _mongoose.connection.syncIndexes(); +}; - if (discriminatorValuePath in update) { - discriminatorKey = update[discriminatorValuePath]; - } +/** + * The Mongoose Decimal128 [SchemaType](/docs/schematypes.html). Used for + * declaring paths in your schema that should be + * [128-bit decimal floating points](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html). + * Do not use this to create a new Decimal128 instance, use `mongoose.Types.Decimal128` + * instead. + * + * ####Example: + * + * const vehicleSchema = new Schema({ fuelLevel: mongoose.Decimal128 }); + * + * @property Decimal128 + * @api public + */ - for (const filterKey of Object.keys(updatedPathsByFilter)) { - const schemaKey = updatedPathsByFilter[filterKey] + "." + key; - const arrayFilterKey = filterKey + "." + key; - if (schemaKey === discriminatorFilterPath) { - const filter = arrayFilters.find((filter) => - filter.hasOwnProperty(arrayFilterKey) - ); - if (filter != null) { - discriminatorKey = filter[arrayFilterKey]; - } - } - } +Mongoose.prototype.Decimal128 = SchemaTypes.Decimal128; - if (discriminatorKey == null) { - continue; - } +/** + * The Mongoose Mixed [SchemaType](/docs/schematypes.html). Used for + * declaring paths in your schema that Mongoose's change tracking, casting, + * and validation should ignore. + * + * ####Example: + * + * const schema = new Schema({ arbitrary: mongoose.Mixed }); + * + * @property Mixed + * @api public + */ - const discriminatorSchema = getDiscriminatorByValue( - schematype.caster.discriminators, - discriminatorKey - ).schema; +Mongoose.prototype.Mixed = SchemaTypes.Mixed; - const rest = parts.slice(i + 1).join("."); - schematype = discriminatorSchema.path(rest); - if (schematype != null) { - type = discriminatorSchema._getPathType(rest); - break; - } - } - } +/** + * The Mongoose Date [SchemaType](/docs/schematypes.html). + * + * ####Example: + * + * const schema = new Schema({ test: Date }); + * schema.path('test') instanceof mongoose.Date; // true + * + * @property Date + * @api public + */ - return { type: type, schematype: schematype }; - }; +Mongoose.prototype.Date = SchemaTypes.Date; - /***/ - }, +/** + * The Mongoose Number [SchemaType](/docs/schematypes.html). Used for + * declaring paths in your schema that Mongoose should cast to numbers. + * + * ####Example: + * + * const schema = new Schema({ num: mongoose.Number }); + * // Equivalent to: + * const schema = new Schema({ num: 'number' }); + * + * @property Number + * @api public + */ - /***/ 8176: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const StrictModeError = __nccwpck_require__(703); - - module.exports = function handleImmutable( - schematype, - strict, - obj, - key, - fullPath, - ctx - ) { - if ( - schematype == null || - !schematype.options || - !schematype.options.immutable - ) { - return false; - } - let immutable = schematype.options.immutable; +Mongoose.prototype.Number = SchemaTypes.Number; - if (typeof immutable === "function") { - immutable = immutable.call(ctx, ctx); - } - if (!immutable) { - return false; - } +/** + * The [MongooseError](#error_MongooseError) constructor. + * + * @method Error + * @api public + */ - if (strict === false) { - return false; - } - if (strict === "throw") { - throw new StrictModeError( - null, - `Field ${fullPath} is immutable and strict = 'throw'` - ); - } +Mongoose.prototype.Error = __nccwpck_require__(4327); - delete obj[key]; - return true; - }; +/** + * Mongoose uses this function to get the current time when setting + * [timestamps](/docs/guide.html#timestamps). You may stub out this function + * using a tool like [Sinon](https://www.npmjs.com/package/sinon) for testing. + * + * @method now + * @returns Date the current time + * @api public + */ - /***/ - }, +Mongoose.prototype.now = function now() { return new Date(); }; - /***/ 8309: /***/ (module) => { - "use strict"; +/** + * The Mongoose CastError constructor + * + * @method CastError + * @param {String} type The name of the type + * @param {Any} value The value that failed to cast + * @param {String} path The path `a.b.c` in the doc where this cast error occurred + * @param {Error} [reason] The original error that was thrown + * @api public + */ - /*! - * ignore - */ +Mongoose.prototype.CastError = __nccwpck_require__(2798); - module.exports = function (obj) { - if (obj == null) { - return false; - } - const keys = Object.keys(obj); - const len = keys.length; - for (let i = 0; i < len; ++i) { - if (keys[i].startsWith("$")) { - return true; - } - } - return false; - }; +/** + * The constructor used for schematype options + * + * @method SchemaTypeOptions + * @api public + */ - /***/ - }, +Mongoose.prototype.SchemaTypeOptions = __nccwpck_require__(7544); - /***/ 3342: /***/ (module) => { - "use strict"; +/** + * The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses. + * + * @property mongo + * @api public + */ - const specialKeys = new Set(["$ref", "$id", "$db"]); +Mongoose.prototype.mongo = __nccwpck_require__(8821); - module.exports = function isOperator(path) { - return path.startsWith("$") && !specialKeys.has(path); - }; +/** + * The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses. + * + * @property mquery + * @api public + */ - /***/ - }, +Mongoose.prototype.mquery = __nccwpck_require__(3821); - /***/ 8276: /***/ (module) => { - "use strict"; +/** + * Sanitizes query filters against [query selector injection attacks](https://thecodebarbarian.com/2014/09/04/defending-against-query-selector-injection-attacks.html) + * by wrapping any nested objects that have a property whose name starts with `$` in a `$eq`. + * + * ```javascript + * const obj = { username: 'val', pwd: { $ne: null } }; + * sanitizeFilter(obj); + * obj; // { username: 'val', pwd: { $eq: { $ne: null } } }); + * ``` + * + * @method sanitizeFilter + * @param {Object} filter + * @returns Object the sanitized object + * @api public + */ - module.exports = function sanitizeProjection(projection) { - if (projection == null) { - return; - } +Mongoose.prototype.sanitizeFilter = sanitizeFilter; - const keys = Object.keys(projection); - for (let i = 0; i < keys.length; ++i) { - if (typeof projection[keys[i]] === "string") { - projection[keys[i]] = 1; - } - } - }; +/** + * Tells `sanitizeFilter()` to skip the given object when filtering out potential [query selector injection attacks](https://thecodebarbarian.com/2014/09/04/defending-against-query-selector-injection-attacks.html). + * Use this method when you have a known query selector that you want to use. + * + * ```javascript + * const obj = { username: 'val', pwd: trusted({ $type: 'string', $eq: 'my secret' }) }; + * sanitizeFilter(obj); + * + * // Note that `sanitizeFilter()` did not add `$eq` around `$type`. + * obj; // { username: 'val', pwd: { $type: 'string', $eq: 'my secret' } }); + * ``` + * + * @method trusted + * @param {Object} obj + * @returns Object the passed in object + * @api public + */ - /***/ - }, +Mongoose.prototype.trusted = trusted; - /***/ 1907: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const isExclusive = __nccwpck_require__(9197); - const isInclusive = __nccwpck_require__(2951); - - /*! - * ignore - */ - - module.exports = function selectPopulatedFields( - fields, - userProvidedFields, - populateOptions - ) { - if (populateOptions == null) { - return; - } +/*! + * ignore + */ - const paths = Object.keys(populateOptions); - userProvidedFields = userProvidedFields || {}; - if (isInclusive(fields)) { - for (const path of paths) { - if (!isPathInFields(userProvidedFields, path)) { - fields[path] = 1; - } else if (userProvidedFields[path] === 0) { - delete fields[path]; - } - } - } else if (isExclusive(fields)) { - for (const path of paths) { - if (userProvidedFields[path] == null) { - delete fields[path]; - } - } - } - }; +Mongoose.prototype._promiseOrCallback = function(callback, fn, ee) { + return promiseOrCallback(callback, fn, ee, this.Promise); +}; - /*! - * ignore - */ +/*! + * The exports object is an instance of Mongoose. + * + * @api public + */ - function isPathInFields(userProvidedFields, path) { - const pieces = path.split("."); - const len = pieces.length; - let cur = pieces[0]; - for (let i = 1; i < len; ++i) { - if ( - userProvidedFields[cur] != null || - userProvidedFields[cur + ".$"] != null - ) { - return true; - } - cur += "." + pieces[i]; - } - return ( - userProvidedFields[cur] != null || - userProvidedFields[cur + ".$"] != null - ); - } +const mongoose = module.exports = exports = new Mongoose({ + [defaultMongooseSymbol]: true +}); - /***/ - }, - /***/ 2006: /***/ (module) => { - "use strict"; +/***/ }), - /*! - * A query thunk is the function responsible for sending the query to MongoDB, - * like `Query#_findOne()` or `Query#_execUpdate()`. The `Query#exec()` function - * calls a thunk. The term "thunk" here is the traditional Node.js definition: - * a function that takes exactly 1 parameter, a callback. - * - * This function defines common behavior for all query thunks. - */ +/***/ 5963: +/***/ ((module, exports, __nccwpck_require__) => { - module.exports = function wrapThunk(fn) { - return function _wrappedThunk(cb) { - ++this._executionCount; +"use strict"; +/*! + * Dependencies + */ - fn.call(this, cb); - }; - }; - /***/ - }, - /***/ 9115: /***/ (module) => { - "use strict"; +const StateMachine = __nccwpck_require__(3532); +const ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default', 'ignore'); - module.exports = function addAutoId(schema) { - const _obj = { _id: { auto: true } }; - _obj._id[schema.options.typeKey] = "ObjectId"; - schema.add(_obj); - }; +module.exports = exports = InternalCache; - /***/ - }, +function InternalCache() { + this.activePaths = new ActiveRoster; + this.strictMode = undefined; +} - /***/ 6990: /***/ (module) => { - "use strict"; +InternalCache.prototype.fullPath = undefined; +InternalCache.prototype.strictMode = undefined; +InternalCache.prototype.selected = undefined; +InternalCache.prototype.shardval = undefined; +InternalCache.prototype.saveError = undefined; +InternalCache.prototype.validationError = undefined; +InternalCache.prototype.adhocPaths = undefined; +InternalCache.prototype.removing = undefined; +InternalCache.prototype.inserting = undefined; +InternalCache.prototype.saving = undefined; +InternalCache.prototype.version = undefined; +InternalCache.prototype._id = undefined; +InternalCache.prototype.ownerDocument = undefined; +InternalCache.prototype.populate = undefined; // what we want to populate in this doc +InternalCache.prototype.populated = undefined;// the _ids that have been populated +InternalCache.prototype.wasPopulated = false; // if this doc was the result of a population +InternalCache.prototype.scope = undefined; - module.exports = function applyPlugins( - schema, - plugins, - options, - cacheKey - ) { - if (schema[cacheKey]) { - return; - } - schema[cacheKey] = true; +InternalCache.prototype.session = null; +InternalCache.prototype.pathsToScopes = null; +InternalCache.prototype.cachedRequired = null; - if (!options || !options.skipTopLevel) { - for (const plugin of plugins) { - schema.plugin(plugin[0], plugin[1]); - } - } - options = Object.assign({}, options); - delete options.skipTopLevel; +/***/ }), - if (options.applyPluginsToChildSchemas !== false) { - for (const path of Object.keys(schema.paths)) { - const type = schema.paths[path]; - if (type.schema != null) { - applyPlugins(type.schema, plugins, options, cacheKey); +/***/ 7688: +/***/ ((module, exports, __nccwpck_require__) => { - // Recompile schema because plugins may have changed it, see gh-7572 - type.caster.prototype.$__setSchema(type.schema); - } - } - } +"use strict"; - const discriminators = schema.discriminators; - if (discriminators == null) { - return; - } - const applyPluginsToDiscriminators = - options.applyPluginsToDiscriminators; +/*! + * Module dependencies. + */ - const keys = Object.keys(discriminators); - for (const discriminatorKey of keys) { - const discriminatorSchema = discriminators[discriminatorKey]; +const Aggregate = __nccwpck_require__(4336); +const ChangeStream = __nccwpck_require__(1662); +const Document = __nccwpck_require__(6717); +const DocumentNotFoundError = __nccwpck_require__(5147); +const DivergentArrayError = __nccwpck_require__(8912); +const EventEmitter = __nccwpck_require__(8614).EventEmitter; +const MongooseBuffer = __nccwpck_require__(5505); +const MongooseError = __nccwpck_require__(4327); +const OverwriteModelError = __nccwpck_require__(970); +const PromiseProvider = __nccwpck_require__(5176); +const Query = __nccwpck_require__(1615); +const RemoveOptions = __nccwpck_require__(2258); +const SaveOptions = __nccwpck_require__(8792); +const Schema = __nccwpck_require__(7606); +const ServerSelectionError = __nccwpck_require__(3070); +const ValidationError = __nccwpck_require__(8460); +const VersionError = __nccwpck_require__(4305); +const ParallelSaveError = __nccwpck_require__(618); +const applyQueryMiddleware = __nccwpck_require__(7378); +const applyHooks = __nccwpck_require__(5373); +const applyMethods = __nccwpck_require__(3543); +const applyStaticHooks = __nccwpck_require__(3739); +const applyStatics = __nccwpck_require__(5220); +const applyWriteConcern = __nccwpck_require__(5661); +const assignVals = __nccwpck_require__(6414); +const castBulkWrite = __nccwpck_require__(4531); +const createPopulateQueryFilter = __nccwpck_require__(5138); +const getDefaultBulkwriteResult = __nccwpck_require__(3039); +const discriminator = __nccwpck_require__(1462); +const each = __nccwpck_require__(9965); +const get = __nccwpck_require__(8730); +const getConstructorName = __nccwpck_require__(7323); +const getDiscriminatorByValue = __nccwpck_require__(8689); +const getModelsMapForPopulate = __nccwpck_require__(1684); +const immediate = __nccwpck_require__(4830); +const internalToObjectOptions = __nccwpck_require__(5684)/* .internalToObjectOptions */ .h; +const isDefaultIdIndex = __nccwpck_require__(7720); +const isIndexEqual = __nccwpck_require__(4749); +const isPathSelectedInclusive = __nccwpck_require__(2000); +const leanPopulateMap = __nccwpck_require__(914); +const modifiedPaths = __nccwpck_require__(587); +const parallelLimit = __nccwpck_require__(7716); +const prepareDiscriminatorPipeline = __nccwpck_require__(9337); +const removeDeselectedForeignField = __nccwpck_require__(6962); +const util = __nccwpck_require__(1669); +const utils = __nccwpck_require__(9232); + +const VERSION_WHERE = 1; +const VERSION_INC = 2; +const VERSION_ALL = VERSION_WHERE | VERSION_INC; + +const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; +const modelCollectionSymbol = Symbol('mongoose#Model#collection'); +const modelDbSymbol = Symbol('mongoose#Model#db'); +const modelSymbol = __nccwpck_require__(3240).modelSymbol; +const subclassedSymbol = Symbol('mongoose#Model#subclassed'); + +const saveToObjectOptions = Object.assign({}, internalToObjectOptions, { + bson: true +}); + +/** + * A Model is a class that's your primary tool for interacting with MongoDB. + * An instance of a Model is called a [Document](./api.html#Document). + * + * In Mongoose, the term "Model" refers to subclasses of the `mongoose.Model` + * class. You should not use the `mongoose.Model` class directly. The + * [`mongoose.model()`](./api.html#mongoose_Mongoose-model) and + * [`connection.model()`](./api.html#connection_Connection-model) functions + * create subclasses of `mongoose.Model` as shown below. + * + * ####Example: + * + * // `UserModel` is a "Model", a subclass of `mongoose.Model`. + * const UserModel = mongoose.model('User', new Schema({ name: String })); + * + * // You can use a Model to create new documents using `new`: + * const userDoc = new UserModel({ name: 'Foo' }); + * await userDoc.save(); + * + * // You also use a model to create queries: + * const userFromDb = await UserModel.findOne({ name: 'Foo' }); + * + * @param {Object} doc values for initial set + * @param [fields] optional object containing the fields that were selected in the query which returned this document. You do **not** need to set this parameter to ensure Mongoose handles your [query projection](./api.html#query_Query-select). + * @param {Boolean} [skipId=false] optional boolean. If true, mongoose doesn't add an `_id` field to the document. + * @inherits Document http://mongoosejs.com/docs/api/document.html + * @event `error`: If listening to this event, 'error' is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model. + * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event. + * @event `index-single-start`: Emitted when an individual index starts within `Model#ensureIndexes`. The fields and options being used to build the index are also passed with the event. + * @event `index-single-done`: Emitted when an individual index finishes within `Model#ensureIndexes`. If an error occurred it is passed with the event. The fields, options, and index name are also passed. + * @api public + */ - applyPlugins( - discriminatorSchema, - plugins, - { skipTopLevel: !applyPluginsToDiscriminators }, - cacheKey - ); - } - }; +function Model(doc, fields, skipId) { + if (fields instanceof Schema) { + throw new TypeError('2nd argument to `Model` must be a POJO or string, ' + + '**not** a schema. Make sure you\'re calling `mongoose.model()`, not ' + + '`mongoose.Model()`.'); + } + Document.call(this, doc, fields, skipId); +} - /***/ - }, +/*! + * Inherits from Document. + * + * All Model.prototype features are available on + * top level (non-sub) documents. + */ - /***/ 5661: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const get = __nccwpck_require__(8730); - - module.exports = function applyWriteConcern(schema, options) { - const writeConcern = get(schema, "options.writeConcern", {}); - if (Object.keys(writeConcern).length != 0) { - options.writeConcern = {}; - if (!("w" in options) && writeConcern.w != null) { - options.writeConcern.w = writeConcern.w; - } - if (!("j" in options) && writeConcern.j != null) { - options.writeConcern.j = writeConcern.j; - } - if (!("wtimeout" in options) && writeConcern.wtimeout != null) { - options.writeConcern.wtimeout = writeConcern.wtimeout; - } - } else { - if (!("w" in options) && writeConcern.w != null) { - options.w = writeConcern.w; - } - if (!("j" in options) && writeConcern.j != null) { - options.j = writeConcern.j; - } - if (!("wtimeout" in options) && writeConcern.wtimeout != null) { - options.wtimeout = writeConcern.wtimeout; - } - } - }; +Model.prototype.__proto__ = Document.prototype; +Model.prototype.$isMongooseModelPrototype = true; - /***/ - }, +/** + * Connection the model uses. + * + * @api public + * @property db + * @memberOf Model + * @instance + */ - /***/ 1119: /***/ (module) => { - "use strict"; +Model.prototype.db; - /** - * For consistency's sake, we replace positional operator `$` and array filters - * `$[]` and `$[foo]` with `0` when looking up schema paths. - */ +/** + * Collection the model uses. + * + * This property is read-only. Modifying this property is a no-op. + * + * @api public + * @property collection + * @memberOf Model + * @instance + */ - module.exports = function cleanPositionalOperators(path) { - return path - .replace(/\.\$(\[[^\]]*\])?(?=\.)/g, ".0") - .replace(/\.\$(\[[^\]]*\])?$/g, ".0"); - }; +Model.prototype.collection; - /***/ - }, +/** + * Internal collection the model uses. + * + * This property is read-only. Modifying this property is a no-op. + * + * @api private + * @property collection + * @memberOf Model + * @instance + */ - /***/ 8373: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const get = __nccwpck_require__(8730); - const helperIsObject = __nccwpck_require__(273); - - /*! - * Gather all indexes defined in the schema, including single nested, - * document arrays, and embedded discriminators. - */ - - module.exports = function getIndexes(schema) { - let indexes = []; - const schemaStack = new WeakMap(); - const indexTypes = schema.constructor.indexTypes; - const indexByName = new Map(); - - collectIndexes(schema); - return indexes; - - function collectIndexes(schema, prefix, baseSchema) { - // Ignore infinitely nested schemas, if we've already seen this schema - // along this path there must be a cycle - if (schemaStack.has(schema)) { - return; - } - schemaStack.set(schema, true); - prefix = prefix || ""; - const keys = Object.keys(schema.paths); +Model.prototype.$__collection; - for (const key of keys) { - const path = schema.paths[key]; - if (baseSchema != null && baseSchema.paths[key]) { - // If looking at an embedded discriminator schema, don't look at paths - // that the - continue; - } +/** + * The name of the model + * + * @api public + * @property modelName + * @memberOf Model + * @instance + */ - if (path.$isMongooseDocumentArray || path.$isSingleNested) { - if ( - get(path, "options.excludeIndexes") !== true && - get(path, "schemaOptions.excludeIndexes") !== true && - get(path, "schema.options.excludeIndexes") !== true - ) { - collectIndexes(path.schema, prefix + key + "."); - } +Model.prototype.modelName; - if (path.schema.discriminators != null) { - const discriminators = path.schema.discriminators; - const discriminatorKeys = Object.keys(discriminators); - for (const discriminatorKey of discriminatorKeys) { - collectIndexes( - discriminators[discriminatorKey], - prefix + key + ".", - path.schema - ); - } - } +/** + * Additional properties to attach to the query when calling `save()` and + * `isNew` is false. + * + * @api public + * @property $where + * @memberOf Model + * @instance + */ - // Retained to minimize risk of backwards breaking changes due to - // gh-6113 - if (path.$isMongooseDocumentArray) { - continue; - } - } +Model.prototype.$where; - const index = path._index || (path.caster && path.caster._index); - - if (index !== false && index !== null && index !== undefined) { - const field = {}; - const isObject = helperIsObject(index); - const options = isObject ? index : {}; - const type = - typeof index === "string" - ? index - : isObject - ? index.type - : false; - - if (type && indexTypes.indexOf(type) !== -1) { - field[prefix + key] = type; - } else if (options.text) { - field[prefix + key] = "text"; - delete options.text; - } else { - const isDescendingIndex = Number(index) === -1; - field[prefix + key] = isDescendingIndex ? -1 : 1; - } +/** + * If this is a discriminator model, `baseModelName` is the name of + * the base model. + * + * @api public + * @property baseModelName + * @memberOf Model + * @instance + */ - delete options.type; - if (!("background" in options)) { - options.background = true; - } - if (schema.options.autoIndex != null) { - options._autoIndex = schema.options.autoIndex; - } +Model.prototype.baseModelName; - const indexName = options && options.name; - if (typeof indexName === "string") { - if (indexByName.has(indexName)) { - Object.assign(indexByName.get(indexName), field); - } else { - indexes.push([field, options]); - indexByName.set(indexName, field); - } - } else { - indexes.push([field, options]); - indexByName.set(indexName, field); - } - } - } +/** + * Event emitter that reports any errors that occurred. Useful for global error + * handling. + * + * ####Example: + * + * MyModel.events.on('error', err => console.log(err.message)); + * + * // Prints a 'CastError' because of the above handler + * await MyModel.findOne({ _id: 'notanid' }).catch(noop); + * + * @api public + * @fires error whenever any query or model function errors + * @memberOf Model + * @static events + */ - schemaStack.delete(schema); +Model.events; - if (prefix) { - fixSubIndexPaths(schema, prefix); - } else { - schema._indexes.forEach(function (index) { - if (!("background" in index[1])) { - index[1].background = true; - } - }); - indexes = indexes.concat(schema._indexes); - } - } +/*! + * Compiled middleware for this model. Set in `applyHooks()`. + * + * @api private + * @property _middleware + * @memberOf Model + * @static + */ - /*! - * Checks for indexes added to subdocs using Schema.index(). - * These indexes need their paths prefixed properly. - * - * schema._indexes = [ [indexObj, options], [indexObj, options] ..] - */ +Model._middleware; - function fixSubIndexPaths(schema, prefix) { - const subindexes = schema._indexes; - const len = subindexes.length; - for (let i = 0; i < len; ++i) { - const indexObj = subindexes[i][0]; - const indexOptions = subindexes[i][1]; - const keys = Object.keys(indexObj); - const klen = keys.length; - const newindex = {}; - - // use forward iteration, order matters - for (let j = 0; j < klen; ++j) { - const key = keys[j]; - newindex[prefix + key] = indexObj[key]; - } - - const newIndexOptions = Object.assign({}, indexOptions); - if ( - indexOptions != null && - indexOptions.partialFilterExpression != null - ) { - newIndexOptions.partialFilterExpression = {}; - const partialFilterExpression = - indexOptions.partialFilterExpression; - for (const key of Object.keys(partialFilterExpression)) { - newIndexOptions.partialFilterExpression[prefix + key] = - partialFilterExpression[key]; - } - } +/*! + * ignore + */ - indexes.push([newindex, newIndexOptions]); - } - } - }; +function _applyCustomWhere(doc, where) { + if (doc.$where == null) { + return; + } + for (const key of Object.keys(doc.$where)) { + where[key] = doc.$where[key]; + } +} - /***/ - }, +/*! + * ignore + */ - /***/ 7453: /***/ (module) => { - "use strict"; +Model.prototype.$__handleSave = function(options, callback) { + const _this = this; + let saveOptions = {}; - /*! - * Behaves like `Schema#path()`, except for it also digs into arrays without - * needing to put `.0.`, so `getPath(schema, 'docArr.elProp')` works. - */ + applyWriteConcern(this.$__schema, options); + if (typeof options.writeConcern != 'undefined') { + saveOptions.writeConcern = {}; + if ('w' in options.writeConcern) { + saveOptions.writeConcern.w = options.writeConcern.w; + } + if ('j' in options.writeConcern) { + saveOptions.writeConcern.j = options.writeConcern.j; + } + if ('wtimeout' in options.writeConcern) { + saveOptions.writeConcern.wtimeout = options.writeConcern.wtimeout; + } + } else { + if ('w' in options) { + saveOptions.w = options.w; + } + if ('j' in options) { + saveOptions.j = options.j; + } + if ('wtimeout' in options) { + saveOptions.wtimeout = options.wtimeout; + } + } + if ('checkKeys' in options) { + saveOptions.checkKeys = options.checkKeys; + } + const session = this.$session(); + if (!saveOptions.hasOwnProperty('session')) { + saveOptions.session = session; + } - module.exports = function getPath(schema, path) { - let schematype = schema.path(path); - if (schematype != null) { - return schematype; - } + if (Object.keys(saveOptions).length === 0) { + saveOptions = null; + } + if (this.$isNew) { + // send entire doc + const obj = this.toObject(saveToObjectOptions); + if ((obj || {})._id === void 0) { + // documents must have an _id else mongoose won't know + // what to update later if more changes are made. the user + // wouldn't know what _id was generated by mongodb either + // nor would the ObjectId generated by mongodb necessarily + // match the schema definition. + immediate(function() { + callback(new MongooseError('document must have an _id before saving')); + }); + return; + } - const pieces = path.split("."); - let cur = ""; - let isArray = false; + this.$__version(true, obj); + this[modelCollectionSymbol].insertOne(obj, saveOptions, function(err, ret) { + if (err) { + _setIsNew(_this, true); - for (const piece of pieces) { - if (/^\d+$/.test(piece) && isArray) { - continue; - } - cur = cur.length === 0 ? piece : cur + "." + piece; + callback(err, null); + return; + } - schematype = schema.path(cur); - if (schematype != null && schematype.schema) { - schema = schematype.schema; - cur = ""; - if (schematype.$isMongooseDocumentArray) { - isArray = true; - } - } + callback(null, ret); + }); + this.$__reset(); + _setIsNew(this, false); + // Make it possible to retry the insert + this.$__.inserting = true; + } else { + // Make sure we don't treat it as a new object on error, + // since it already exists + this.$__.inserting = false; + + const delta = this.$__delta(); + if (delta) { + if (delta instanceof MongooseError) { + callback(delta); + return; + } + + const where = this.$__where(delta[0]); + if (where instanceof MongooseError) { + callback(where); + return; + } + + _applyCustomWhere(this, where); + this[modelCollectionSymbol].updateOne(where, delta[1], saveOptions, (err, ret) => { + if (err) { + this.$__undoReset(); + + callback(err); + return; + } + ret.$where = where; + callback(null, ret); + }); + } else { + const optionsWithCustomValues = Object.assign({}, options, saveOptions); + const where = this.$__where(); + if (this.$__schema.options.optimisticConcurrency) { + const key = this.$__schema.options.versionKey; + const val = this.$__getValue(key); + if (val != null) { + where[key] = val; } + } + this.constructor.exists(where, optionsWithCustomValues). + then((documentExists) => { + if (!documentExists) { + const matchedCount = 0; + return callback(null, { $where: where, matchedCount }); + } - return schematype; - }; + const matchedCount = 1; + callback(null, { $where: where, matchedCount }); + }). + catch(callback); + return; + } - /***/ - }, + // store the modified paths before the document is reset + this.$__.modifiedPaths = this.modifiedPaths(); + this.$__reset(); - /***/ 8965: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + _setIsNew(this, false); + } +}; - const addAutoId = __nccwpck_require__(9115); +/*! + * ignore + */ - module.exports = function handleIdOption(schema, options) { - if (options == null || options._id == null) { - return schema; +Model.prototype.$__save = function(options, callback) { + this.$__handleSave(options, (error, result) => { + const hooks = this.$__schema.s.hooks; + if (error) { + return hooks.execPost('save:error', this, [this], { error: error }, (error) => { + callback(error, this); + }); + } + let numAffected = 0; + if (get(options, 'safe.w') !== 0 && get(options, 'w') !== 0) { + // Skip checking if write succeeded if writeConcern is set to + // unacknowledged writes, because otherwise `numAffected` will always be 0 + if (result != null) { + if (Array.isArray(result)) { + numAffected = result.length; + } else if (result.matchedCount != null) { + numAffected = result.matchedCount; + } else { + numAffected = result; + } + } + // was this an update that required a version bump? + if (this.$__.version && !this.$__.inserting) { + const doIncrement = VERSION_INC === (VERSION_INC & this.$__.version); + this.$__.version = undefined; + const key = this.$__schema.options.versionKey; + const version = this.$__getValue(key) || 0; + if (numAffected <= 0) { + // the update failed. pass an error back + this.$__undoReset(); + const err = this.$__.$versionError || + new VersionError(this, version, this.$__.modifiedPaths); + return callback(err); } - schema = schema.clone(); - if (!options._id) { - schema.remove("_id"); - schema.options._id = false; - } else if (!schema.paths["_id"]) { - addAutoId(schema); - schema.options._id = true; + // increment version if was successful + if (doIncrement) { + this.$__setValue(key, version + 1); } + } + if (result != null && numAffected <= 0) { + this.$__undoReset(); + error = new DocumentNotFoundError(result.$where, + this.constructor.modelName, numAffected, result); + return hooks.execPost('save:error', this, [this], { error: error }, (error) => { + callback(error, this); + }); + } + } + this.$__.saving = undefined; + this.$__.savedState = {}; + this.$emit('save', this, numAffected); + this.constructor.emit('save', this, numAffected); + callback(null, this); + }); +}; + +/*! + * ignore + */ - return schema; - }; +function generateVersionError(doc, modifiedPaths) { + const key = doc.$__schema.options.versionKey; + if (!key) { + return null; + } + const version = doc.$__getValue(key) || 0; + return new VersionError(doc, version, modifiedPaths); +} - /***/ - }, +/** + * Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`, + * or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation with just the modified paths if `isNew` is `false`. + * + * ####Example: + * + * product.sold = Date.now(); + * product = await product.save(); + * + * If save is successful, the returned promise will fulfill with the document + * saved. + * + * ####Example: + * + * const newProduct = await product.save(); + * newProduct === product; // true + * + * @param {Object} [options] options optional options + * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). + * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead. + * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. + * @param {Boolean} [options.validateModifiedOnly=false] if `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths. + * @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) + * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) + * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern). + * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names) + * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`. + * @param {Function} [fn] optional callback + * @throws {DocumentNotFoundError} if this [save updates an existing document](api.html#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating). + * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise. + * @api public + * @see middleware http://mongoosejs.com/docs/middleware.html + */ - /***/ 2850: /***/ (module) => { - "use strict"; +Model.prototype.save = function(options, fn) { + let parallelSave; + this.$op = 'save'; - module.exports = handleTimestampOption; + if (this.$__.saving) { + parallelSave = new ParallelSaveError(this); + } else { + this.$__.saving = new ParallelSaveError(this); + } - /*! - * ignore - */ + if (typeof options === 'function') { + fn = options; + options = undefined; + } - function handleTimestampOption(arg, prop) { - if (arg == null) { - return null; - } + options = new SaveOptions(options); + if (options.hasOwnProperty('session')) { + this.$session(options.session); + } + this.$__.$versionError = generateVersionError(this, this.modifiedPaths()); - if (typeof arg === "boolean") { - return prop; - } - if (typeof arg[prop] === "boolean") { - return arg[prop] ? prop : null; - } - if (!(prop in arg)) { - return prop; - } - return arg[prop]; + fn = this.constructor.$handleCallbackError(fn); + return this.constructor.db.base._promiseOrCallback(fn, cb => { + cb = this.constructor.$wrapCallback(cb); + + if (parallelSave) { + this.$__handleReject(parallelSave); + return cb(parallelSave); + } + + this.$__.saveOptions = options; + + this.$__save(options, error => { + this.$__.saving = undefined; + delete this.$__.saveOptions; + delete this.$__.$versionError; + this.$op = null; + + if (error) { + this.$__handleReject(error); + return cb(error); } + cb(null, this); + }); + }, this.constructor.events); +}; - /***/ - }, +Model.prototype.$save = Model.prototype.save; - /***/ 2830: /***/ (module) => { - "use strict"; - - module.exports = function merge(s1, s2, skipConflictingPaths) { - const paths = Object.keys(s2.tree); - const pathsToAdd = {}; - for (const key of paths) { - if ( - skipConflictingPaths && - (s1.paths[key] || s1.nested[key] || s1.singleNestedPaths[key]) - ) { - continue; - } - pathsToAdd[key] = s2.tree[key]; - } - s1.add(pathsToAdd); +/*! + * Determines whether versioning should be skipped for the given path + * + * @param {Document} self + * @param {String} path + * @return {Boolean} true if versioning should be skipped for the given path + */ +function shouldSkipVersioning(self, path) { + const skipVersioning = self.$__schema.options.skipVersioning; + if (!skipVersioning) return false; - s1.callQueue = s1.callQueue.concat(s2.callQueue); - s1.method(s2.methods); - s1.static(s2.statics); + // Remove any array indexes from the path + path = path.replace(/\.\d+\./, '.'); - for (const query in s2.query) { - s1.query[query] = s2.query[query]; - } + return skipVersioning[path]; +} - for (const virtual in s2.virtuals) { - s1.virtuals[virtual] = s2.virtuals[virtual].clone(); - } +/*! + * Apply the operation to the delta (update) clause as + * well as track versioning for our where clause. + * + * @param {Document} self + * @param {Object} where + * @param {Object} delta + * @param {Object} data + * @param {Mixed} val + * @param {String} [operation] + */ - s1.s.hooks.merge(s2.s.hooks, false); - }; +function operand(self, where, delta, data, val, op) { + // delta + op || (op = '$set'); + if (!delta[op]) delta[op] = {}; + delta[op][data.path] = val; + // disabled versioning? + if (self.$__schema.options.versionKey === false) return; - /***/ - }, + // path excluded from versioning? + if (shouldSkipVersioning(self, data.path)) return; - /***/ 773: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + // already marked for versioning? + if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return; - const StrictModeError = __nccwpck_require__(703); + if (self.$__schema.options.optimisticConcurrency) { + self.$__.version = VERSION_ALL; + return; + } - /*! - * ignore - */ + switch (op) { + case '$set': + case '$unset': + case '$pop': + case '$pull': + case '$pullAll': + case '$push': + case '$addToSet': + break; + default: + // nothing to do + return; + } - module.exports = function (schematype) { - if (schematype.$immutable) { - schematype.$immutableSetter = createImmutableSetter( - schematype.path, - schematype.options.immutable - ); - schematype.set(schematype.$immutableSetter); - } else if (schematype.$immutableSetter) { - schematype.setters = schematype.setters.filter( - (fn) => fn !== schematype.$immutableSetter - ); - delete schematype.$immutableSetter; - } - }; + // ensure updates sent with positional notation are + // editing the correct array element. + // only increment the version if an array position changes. + // modifying elements of an array is ok if position does not change. + if (op === '$push' || op === '$addToSet' || op === '$pullAll' || op === '$pull') { + self.$__.version = VERSION_INC; + } else if (/^\$p/.test(op)) { + // potentially changing array positions + increment.call(self); + } else if (Array.isArray(val)) { + // $set an array + increment.call(self); + } else if (/\.\d+\.|\.\d+$/.test(data.path)) { + // now handling $set, $unset + // subpath of array + self.$__.version = VERSION_WHERE; + } +} - function createImmutableSetter(path, immutable) { - return function immutableSetter(v) { - if (this == null || this.$__ == null) { - return v; - } - if (this.isNew) { - return v; - } +/*! + * Compiles an update and where clause for a `val` with _atomics. + * + * @param {Document} self + * @param {Object} where + * @param {Object} delta + * @param {Object} data + * @param {Array} value + */ - const _immutable = - typeof immutable === "function" - ? immutable.call(this, this) - : immutable; - if (!_immutable) { - return v; - } +function handleAtomics(self, where, delta, data, value) { + if (delta.$set && delta.$set[data.path]) { + // $set has precedence over other atomics + return; + } - const _value = this.$__getValue(path); - if (this.$__.strictMode === "throw" && v !== _value) { - throw new StrictModeError( - path, - "Path `" + - path + - "` is immutable " + - "and strict mode is set to throw.", - true - ); - } + if (typeof value.$__getAtomics === 'function') { + value.$__getAtomics().forEach(function(atomic) { + const op = atomic[0]; + const val = atomic[1]; + operand(self, where, delta, data, val, op); + }); + return; + } - return _value; - }; - } + // legacy support for plugins - /***/ - }, + const atomics = value[arrayAtomicsSymbol]; + const ops = Object.keys(atomics); + let i = ops.length; + let val; + let op; - /***/ 5937: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const modifiedPaths = __nccwpck_require__(3719) /* .modifiedPaths */.M; - const get = __nccwpck_require__(8730); - - /** - * Applies defaults to update and findOneAndUpdate operations. - * - * @param {Object} filter - * @param {Schema} schema - * @param {Object} castedDoc - * @param {Object} options - * @method setDefaultsOnInsert - * @api private - */ - - module.exports = function (filter, schema, castedDoc, options) { - options = options || {}; + if (i === 0) { + // $set - const shouldSetDefaultsOnInsert = - options.setDefaultsOnInsert != null - ? options.setDefaultsOnInsert - : schema.base.options.setDefaultsOnInsert; + if (utils.isMongooseObject(value)) { + value = value.toObject({ depopulate: 1, _isNested: true }); + } else if (value.valueOf) { + value = value.valueOf(); + } - if (!options.upsert || !shouldSetDefaultsOnInsert) { - return castedDoc; - } + return operand(self, where, delta, data, value); + } - const keys = Object.keys(castedDoc || {}); - const updatedKeys = {}; - const updatedValues = {}; - const numKeys = keys.length; - const modified = {}; + function iter(mem) { + return utils.isMongooseObject(mem) + ? mem.toObject({ depopulate: 1, _isNested: true }) + : mem; + } - let hasDollarUpdate = false; + while (i--) { + op = ops[i]; + val = atomics[op]; - for (let i = 0; i < numKeys; ++i) { - if (keys[i].startsWith("$")) { - modifiedPaths(castedDoc[keys[i]], "", modified); - hasDollarUpdate = true; - } + if (utils.isMongooseObject(val)) { + val = val.toObject({ depopulate: true, transform: false, _isNested: true }); + } else if (Array.isArray(val)) { + val = val.map(iter); + } else if (val.valueOf) { + val = val.valueOf(); + } + + if (op === '$addToSet') { + val = { $each: val }; + } + + operand(self, where, delta, data, val, op); + } +} + +/** + * Produces a special query document of the modified properties used in updates. + * + * @api private + * @method $__delta + * @memberOf Model + * @instance + */ + +Model.prototype.$__delta = function() { + const dirty = this.$__dirty(); + if (!dirty.length && VERSION_ALL !== this.$__.version) { + return; + } + const where = {}; + const delta = {}; + const len = dirty.length; + const divergent = []; + let d = 0; + + where._id = this._doc._id; + // If `_id` is an object, need to depopulate, but also need to be careful + // because `_id` can technically be null (see gh-6406) + if (get(where, '_id.$__', null) != null) { + where._id = where._id.toObject({ transform: false, depopulate: true }); + } + for (; d < len; ++d) { + const data = dirty[d]; + let value = data.value; + const match = checkDivergentArray(this, data.path, value); + if (match) { + divergent.push(match); + continue; + } + + const pop = this.$populated(data.path, true); + if (!pop && this.$__.selected) { + // If any array was selected using an $elemMatch projection, we alter the path and where clause + // NOTE: MongoDB only supports projected $elemMatch on top level array. + const pathSplit = data.path.split('.'); + const top = pathSplit[0]; + if (this.$__.selected[top] && this.$__.selected[top].$elemMatch) { + // If the selected array entry was modified + if (pathSplit.length > 1 && pathSplit[1] == 0 && typeof where[top] === 'undefined') { + where[top] = this.$__.selected[top]; + pathSplit[1] = '$'; + data.path = pathSplit.join('.'); + } + // if the selected array was modified in any other way throw an error + else { + divergent.push(data.path); + continue; } + } + } + + if (divergent.length) continue; + if (value === undefined) { + operand(this, where, delta, data, 1, '$unset'); + } else if (value === null) { + operand(this, where, delta, data, null); + } else if (value.isMongooseArray && value.$path() && value[arrayAtomicsSymbol]) { + // arrays and other custom types (support plugins etc) + handleAtomics(this, where, delta, data, value); + } else if (value[MongooseBuffer.pathSymbol] && Buffer.isBuffer(value)) { + // MongooseBuffer + value = value.toObject(); + operand(this, where, delta, data, value); + } else { + value = utils.clone(value, { + depopulate: true, + transform: false, + virtuals: false, + getters: false, + _isNested: true + }); + operand(this, where, delta, data, value); + } + } + + if (divergent.length) { + return new DivergentArrayError(divergent); + } + + if (this.$__.version) { + this.$__version(where, delta); + } + return [where, delta]; +}; + +/*! + * Determine if array was populated with some form of filter and is now + * being updated in a manner which could overwrite data unintentionally. + * + * @see https://github.com/Automattic/mongoose/issues/1334 + * @param {Document} doc + * @param {String} path + * @return {String|undefined} + */ + +function checkDivergentArray(doc, path, array) { + // see if we populated this path + const pop = doc.$populated(path, true); - if (!hasDollarUpdate) { - modifiedPaths(castedDoc, "", modified); - } + if (!pop && doc.$__.selected) { + // If any array was selected using an $elemMatch projection, we deny the update. + // NOTE: MongoDB only supports projected $elemMatch on top level array. + const top = path.split('.')[0]; + if (doc.$__.selected[top + '.$']) { + return top; + } + } - const paths = Object.keys(filter); - const numPaths = paths.length; - for (let i = 0; i < numPaths; ++i) { - const path = paths[i]; - const condition = filter[path]; - if (condition && typeof condition === "object") { - const conditionKeys = Object.keys(condition); - const numConditionKeys = conditionKeys.length; - let hasDollarKey = false; - for (let j = 0; j < numConditionKeys; ++j) { - if (conditionKeys[j].startsWith("$")) { - hasDollarKey = true; - break; - } - } - if (hasDollarKey) { - continue; - } - } - updatedKeys[path] = true; - modified[path] = true; - } - - if (options && options.overwrite && !hasDollarUpdate) { - // Defaults will be set later, since we're overwriting we'll cast - // the whole update to a document - return castedDoc; - } - - schema.eachPath(function (path, schemaType) { - // Skip single nested paths if underneath a map - const isUnderneathMap = - schemaType.path.endsWith(".$*") || - schemaType.path.indexOf(".$*.") !== -1; - if (schemaType.$isSingleNested && !isUnderneathMap) { - // Only handle nested schemas 1-level deep to avoid infinite - // recursion re: https://github.com/mongodb-js/mongoose-autopopulate/issues/11 - schemaType.schema.eachPath(function (_path, _schemaType) { - if (_path === "_id" && _schemaType.auto) { - // Ignore _id if auto id so we don't create subdocs - return; - } + if (!(pop && array && array.isMongooseArray)) return; + + // If the array was populated using options that prevented all + // documents from being returned (match, skip, limit) or they + // deselected the _id field, $pop and $set of the array are + // not safe operations. If _id was deselected, we do not know + // how to remove elements. $pop will pop off the _id from the end + // of the array in the db which is not guaranteed to be the + // same as the last element we have here. $set of the entire array + // would be similarly destructive as we never received all + // elements of the array and potentially would overwrite data. + const check = pop.options.match || + pop.options.options && utils.object.hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted + pop.options.options && pop.options.options.skip || // 0 is permitted + pop.options.select && // deselected _id? + (pop.options.select._id === 0 || + /\s?-_id\s?/.test(pop.options.select)); + + if (check) { + const atomics = array[arrayAtomicsSymbol]; + if (Object.keys(atomics).length === 0 || atomics.$set || atomics.$pop) { + return path; + } + } +} - const def = _schemaType.getDefault(null, true); - if ( - !isModified(modified, path + "." + _path) && - typeof def !== "undefined" - ) { - castedDoc = castedDoc || {}; - castedDoc.$setOnInsert = castedDoc.$setOnInsert || {}; - castedDoc.$setOnInsert[path + "." + _path] = def; - updatedValues[path + "." + _path] = def; - } - }); - } else { - const def = schemaType.getDefault(null, true); - if (!isModified(modified, path) && typeof def !== "undefined") { - castedDoc = castedDoc || {}; - castedDoc.$setOnInsert = castedDoc.$setOnInsert || {}; - if (get(castedDoc, path) == null) { - castedDoc.$setOnInsert[path] = def; - } - updatedValues[path] = def; - } - } - }); +/** + * Appends versioning to the where and update clauses. + * + * @api private + * @method $__version + * @memberOf Model + * @instance + */ - return castedDoc; - }; +Model.prototype.$__version = function(where, delta) { + const key = this.$__schema.options.versionKey; - function isModified(modified, path) { - if (modified[path]) { - return true; - } - const sp = path.split("."); - let cur = sp[0]; - for (let i = 1; i < sp.length; ++i) { - if (modified[cur]) { - return true; - } - cur += "." + sp[i]; - } - return false; - } + if (where === true) { + // this is an insert + if (key) { + this.$__setValue(key, delta[key] = 0); + } + return; + } - /***/ - }, + // updates - /***/ 6786: /***/ (module) => { - "use strict"; + // only apply versioning if our versionKey was selected. else + // there is no way to select the correct version. we could fail + // fast here and force them to include the versionKey but + // thats a bit intrusive. can we do this automatically? + if (!this.$__isSelected(key)) { + return; + } - module.exports = new Set(["__proto__", "constructor", "prototype"]); + // $push $addToSet don't need the where clause set + if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) { + const value = this.$__getValue(key); + if (value != null) where[key] = value; + } - /***/ - }, + if (VERSION_INC === (VERSION_INC & this.$__.version)) { + if (get(delta.$set, key, null) != null) { + // Version key is getting set, means we'll increment the doc's version + // after a successful save, so we should set the incremented version so + // future saves don't fail (gh-5779) + ++delta.$set[key]; + } else { + delta.$inc = delta.$inc || {}; + delta.$inc[key] = 1; + } + } +}; - /***/ 3240: /***/ (__unused_webpack_module, exports) => { - "use strict"; - - exports.arrayAtomicsSymbol = Symbol("mongoose#Array#_atomics"); - exports.arrayParentSymbol = Symbol("mongoose#Array#_parent"); - exports.arrayPathSymbol = Symbol("mongoose#Array#_path"); - exports.arraySchemaSymbol = Symbol("mongoose#Array#_schema"); - exports.documentArrayParent = Symbol("mongoose:documentArrayParent"); - exports.documentIsSelected = Symbol("mongoose#Document#isSelected"); - exports.documentIsModified = Symbol("mongoose#Document#isModified"); - exports.documentModifiedPaths = Symbol("mongoose#Document#modifiedPaths"); - exports.documentSchemaSymbol = Symbol("mongoose#Document#schema"); - exports.getSymbol = Symbol("mongoose#Document#get"); - exports.modelSymbol = Symbol("mongoose#Model"); - exports.objectIdSymbol = Symbol("mongoose#ObjectId"); - exports.populateModelSymbol = Symbol("mongoose.PopulateOptions#Model"); - exports.schemaTypeSymbol = Symbol("mongoose#schemaType"); - exports.sessionNewDocuments = Symbol( - "mongoose:ClientSession#newDocuments" - ); - exports.scopeSymbol = Symbol("mongoose#Document#scope"); - exports.validatorErrorSymbol = Symbol("mongoose:validatorError"); +/** + * Signal that we desire an increment of this documents version. + * + * ####Example: + * + * Model.findById(id, function (err, doc) { + * doc.increment(); + * doc.save(function (err) { .. }) + * }) + * + * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey + * @api public + */ - /***/ - }, +function increment() { + this.$__.version = VERSION_ALL; + return this; +} - /***/ 82: /***/ (__unused_webpack_module, exports) => { - "use strict"; +Model.prototype.increment = increment; - exports.i = setTimeout; +/** + * Returns a query object + * + * @api private + * @method $__where + * @memberOf Model + * @instance + */ - /***/ - }, +Model.prototype.$__where = function _where(where) { + where || (where = {}); - /***/ 3151: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + if (!where._id) { + where._id = this._doc._id; + } - const applyTimestampsToChildren = __nccwpck_require__(1975); - const applyTimestampsToUpdate = __nccwpck_require__(1162); - const get = __nccwpck_require__(8730); - const handleTimestampOption = __nccwpck_require__(2850); - const symbols = __nccwpck_require__(1205); + if (this._doc._id === void 0) { + return new MongooseError('No _id found on document!'); + } - module.exports = function setupTimestamps(schema, timestamps) { - const childHasTimestamp = schema.childSchemas.find(withTimestamp); + return where; +}; - function withTimestamp(s) { - const ts = s.schema.options.timestamps; - return !!ts; - } +/** + * Removes this document from the db. + * + * ####Example: + * product.remove(function (err, product) { + * if (err) return handleError(err); + * Product.findById(product._id, function (err, product) { + * console.log(product) // null + * }) + * }) + * + * + * As an extra measure of flow control, remove will return a Promise (bound to `fn` if passed) so it could be chained, or hooked to receive errors + * + * ####Example: + * product.remove().then(function (product) { + * ... + * }).catch(function (err) { + * assert.ok(err) + * }) + * + * @param {Object} [options] + * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). + * @param {function(err,product)} [fn] optional callback + * @return {Promise} Promise + * @api public + */ - if (!timestamps && !childHasTimestamp) { - return; - } +Model.prototype.remove = function remove(options, fn) { + if (typeof options === 'function') { + fn = options; + options = undefined; + } - const createdAt = handleTimestampOption(timestamps, "createdAt"); - const updatedAt = handleTimestampOption(timestamps, "updatedAt"); - const currentTime = - timestamps != null && timestamps.hasOwnProperty("currentTime") - ? timestamps.currentTime - : null; - const schemaAdditions = {}; + options = new RemoveOptions(options); + if (options.hasOwnProperty('session')) { + this.$session(options.session); + } + this.$op = 'remove'; - schema.$timestamps = { createdAt: createdAt, updatedAt: updatedAt }; + fn = this.constructor.$handleCallbackError(fn); - if (updatedAt && !schema.paths[updatedAt]) { - schemaAdditions[updatedAt] = Date; - } + return this.constructor.db.base._promiseOrCallback(fn, cb => { + cb = this.constructor.$wrapCallback(cb); + this.$__remove(options, (err, res) => { + this.$op = null; + cb(err, res); + }); + }, this.constructor.events); +}; - if (createdAt && !schema.paths[createdAt]) { - schemaAdditions[createdAt] = Date; - } +/*! + * Alias for remove + */ - schema.add(schemaAdditions); +Model.prototype.$remove = Model.prototype.remove; +Model.prototype.delete = Model.prototype.remove; - schema.pre("save", function (next) { - const timestampOption = get(this, "$__.saveOptions.timestamps"); - if (timestampOption === false) { - return next(); - } +/** + * Removes this document from the db. Equivalent to `.remove()`. + * + * ####Example: + * product = await product.deleteOne(); + * await Product.findById(product._id); // null + * + * @param {function(err,product)} [fn] optional callback + * @return {Promise} Promise + * @api public + */ - const skipUpdatedAt = - timestampOption != null && timestampOption.updatedAt === false; - const skipCreatedAt = - timestampOption != null && timestampOption.createdAt === false; - - const defaultTimestamp = - currentTime != null - ? currentTime() - : (this.ownerDocument - ? this.ownerDocument() - : this - ).constructor.base.now(); - const auto_id = this._id && this._id.auto; - - if ( - !skipCreatedAt && - createdAt && - !this.get(createdAt) && - this.$__isSelected(createdAt) - ) { - this.$set( - createdAt, - auto_id ? this._id.getTimestamp() : defaultTimestamp - ); - } +Model.prototype.deleteOne = function deleteOne(options, fn) { + if (typeof options === 'function') { + fn = options; + options = undefined; + } - if ( - !skipUpdatedAt && - updatedAt && - (this.isNew || this.isModified()) - ) { - let ts = defaultTimestamp; - if (this.isNew) { - if (createdAt != null) { - ts = this.$__getValue(createdAt); - } else if (auto_id) { - ts = this._id.getTimestamp(); - } - } - this.$set(updatedAt, ts); - } + if (!options) { + options = {}; + } - next(); - }); + fn = this.constructor.$handleCallbackError(fn); - schema.methods.initializeTimestamps = function () { - const ts = - currentTime != null ? currentTime() : this.constructor.base.now(); - if (createdAt && !this.get(createdAt)) { - this.$set(createdAt, ts); - } - if (updatedAt && !this.get(updatedAt)) { - this.$set(updatedAt, ts); - } - return this; - }; + return this.constructor.db.base._promiseOrCallback(fn, cb => { + cb = this.constructor.$wrapCallback(cb); + this.$__deleteOne(options, cb); + }, this.constructor.events); +}; - _setTimestampsOnUpdate[symbols.builtInMiddleware] = true; +/*! + * ignore + */ - const opts = { query: true, model: false }; - schema.pre("findOneAndReplace", opts, _setTimestampsOnUpdate); - schema.pre("findOneAndUpdate", opts, _setTimestampsOnUpdate); - schema.pre("replaceOne", opts, _setTimestampsOnUpdate); - schema.pre("update", opts, _setTimestampsOnUpdate); - schema.pre("updateOne", opts, _setTimestampsOnUpdate); - schema.pre("updateMany", opts, _setTimestampsOnUpdate); +Model.prototype.$__remove = function $__remove(options, cb) { + if (this.$__.isDeleted) { + return immediate(() => cb(null, this)); + } - function _setTimestampsOnUpdate(next) { - const now = - currentTime != null ? currentTime() : this.model.base.now(); + const where = this.$__where(); + if (where instanceof MongooseError) { + return cb(where); + } - // Replacing with null update should still trigger timestamps - if (this.op === "findOneAndReplace" && this.getUpdate() == null) { - this.setUpdate({}); - } + _applyCustomWhere(this, where); - applyTimestampsToUpdate( - now, - createdAt, - updatedAt, - this.getUpdate(), - this.options, - this.schema - ); - applyTimestampsToChildren(now, this.getUpdate(), this.model.schema); - next(); - } - }; + const session = this.$session(); + if (!options.hasOwnProperty('session')) { + options.session = session; + } - /***/ - }, + this[modelCollectionSymbol].deleteOne(where, options, err => { + if (!err) { + this.$__.isDeleted = true; + this.$emit('remove', this); + this.constructor.emit('remove', this); + return cb(null, this); + } + this.$__.isDeleted = false; + cb(err); + }); +}; - /***/ 8571: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +/*! + * ignore + */ - const getConstructorName = __nccwpck_require__(7323); +Model.prototype.$__deleteOne = Model.prototype.$__remove; - module.exports = function allServersUnknown(topologyDescription) { - if (getConstructorName(topologyDescription) !== "TopologyDescription") { - return false; - } +/** + * Returns another Model instance. + * + * ####Example: + * + * const doc = new Tank; + * doc.model('User').findById(id, callback); + * + * @param {String} name model name + * @api public + */ - const servers = Array.from(topologyDescription.servers.values()); - return ( - servers.length > 0 && - servers.every((server) => server.type === "Unknown") - ); - }; +Model.prototype.model = function model(name) { + return this[modelDbSymbol].model(name); +}; - /***/ - }, +/** + * Returns true if at least one document exists in the database that matches + * the given `filter`, and false otherwise. + * + * Under the hood, `MyModel.exists({ answer: 42 })` is equivalent to + * `MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean()` + * + * ####Example: + * await Character.deleteMany({}); + * await Character.create({ name: 'Jean-Luc Picard' }); + * + * await Character.exists({ name: /picard/i }); // { _id: ... } + * await Character.exists({ name: /riker/i }); // null + * + * This function triggers the following middleware. + * + * - `findOne()` + * + * @param {Object} filter + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] callback + * @return {Query} + */ - /***/ 7352: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +Model.exists = function exists(filter, options, callback) { + _checkContext(this, 'exists'); + if (typeof options === 'function') { + callback = options; + options = null; + } - const getConstructorName = __nccwpck_require__(7323); + const query = this.findOne(filter). + select({ _id: 1 }). + lean(). + setOptions(options); - module.exports = function isAtlas(topologyDescription) { - if (getConstructorName(topologyDescription) !== "TopologyDescription") { - return false; - } + if (typeof callback === 'function') { + return query.exec(callback); + } + options = options || {}; + if (!options.explain) { + return query.then(doc => !!doc); + } - const hostnames = Array.from(topologyDescription.servers.keys()); - return ( - hostnames.length > 0 && - hostnames.every((host) => host.endsWith(".mongodb.net:27017")) - ); - }; + return query; +}; - /***/ - }, +/** + * Adds a discriminator type. + * + * ####Example: + * + * function BaseSchema() { + * Schema.apply(this, arguments); + * + * this.add({ + * name: String, + * createdAt: Date + * }); + * } + * util.inherits(BaseSchema, Schema); + * + * const PersonSchema = new BaseSchema(); + * const BossSchema = new BaseSchema({ department: String }); + * + * const Person = mongoose.model('Person', PersonSchema); + * const Boss = Person.discriminator('Boss', BossSchema); + * new Boss().__t; // "Boss". `__t` is the default `discriminatorKey` + * + * const employeeSchema = new Schema({ boss: ObjectId }); + * const Employee = Person.discriminator('Employee', employeeSchema, 'staff'); + * new Employee().__t; // "staff" because of 3rd argument above + * + * @param {String} name discriminator model name + * @param {Schema} schema discriminator model schema + * @param {Object|String} [options] If string, same as `options.value`. + * @param {String} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. + * @param {Boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning. + * @return {Model} The newly created discriminator model + * @api public + */ - /***/ 5437: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +Model.discriminator = function(name, schema, options) { + let model; + if (typeof name === 'function') { + model = name; + name = utils.getFunctionName(model); + if (!(model.prototype instanceof Model)) { + throw new MongooseError('The provided class ' + name + ' must extend Model'); + } + } - const getConstructorName = __nccwpck_require__(7323); + options = options || {}; + const value = utils.isPOJO(options) ? options.value : options; + const clone = get(options, 'clone', true); - const nonSSLMessage = - "Client network socket disconnected before secure TLS " + - "connection was established"; + _checkContext(this, 'discriminator'); - module.exports = function isSSLError(topologyDescription) { - if (getConstructorName(topologyDescription) !== "TopologyDescription") { - return false; - } + if (utils.isObject(schema) && !schema.instanceOfSchema) { + schema = new Schema(schema); + } + if (schema instanceof Schema && clone) { + schema = schema.clone(); + } - const descriptions = Array.from(topologyDescription.servers.values()); - return ( - descriptions.length > 0 && - descriptions.every( - (descr) => - descr.error && descr.error.message.indexOf(nonSSLMessage) !== -1 - ) - ); - }; + schema = discriminator(this, name, schema, value, true); + if (this.db.models[name]) { + throw new OverwriteModelError(name); + } - /***/ - }, + schema.$isRootDiscriminator = true; + schema.$globalPluginsApplied = true; + + model = this.db.model(model || name, schema, this.$__collection.name); + this.discriminators[name] = model; + const d = this.discriminators[name]; + d.prototype.__proto__ = this.prototype; + Object.defineProperty(d, 'baseModelName', { + value: this.modelName, + configurable: true, + writable: false + }); + + // apply methods and statics + applyMethods(d, schema); + applyStatics(d, schema); + + if (this[subclassedSymbol] != null) { + for (const submodel of this[subclassedSymbol]) { + submodel.discriminators = submodel.discriminators || {}; + submodel.discriminators[name] = + model.__subclass(model.db, schema, submodel.collection.name); + } + } - /***/ 1975: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + return d; +}; - const cleanPositionalOperators = __nccwpck_require__(1119); - const handleTimestampOption = __nccwpck_require__(2850); +/*! + * Make sure `this` is a model + */ - module.exports = applyTimestampsToChildren; +function _checkContext(ctx, fnName) { + // Check context, because it is easy to mistakenly type + // `new Model.discriminator()` and get an incomprehensible error + if (ctx == null || ctx === global) { + throw new MongooseError('`Model.' + fnName + '()` cannot run without a ' + + 'model as `this`. Make sure you are calling `MyModel.' + fnName + '()` ' + + 'where `MyModel` is a Mongoose model.'); + } else if (ctx[modelSymbol] == null) { + throw new MongooseError('`Model.' + fnName + '()` cannot run without a ' + + 'model as `this`. Make sure you are not calling ' + + '`new Model.' + fnName + '()`'); + } +} - /*! - * ignore - */ +// Model (class) features - function applyTimestampsToChildren(now, update, schema) { - if (update == null) { - return; - } +/*! + * Give the constructor the ability to emit events. + */ - const keys = Object.keys(update); - const hasDollarKey = keys.some((key) => key.startsWith("$")); +for (const i in EventEmitter.prototype) { + Model[i] = EventEmitter.prototype[i]; +} - if (hasDollarKey) { - if (update.$push) { - _applyTimestampToUpdateOperator(update.$push); - } - if (update.$addToSet) { - _applyTimestampToUpdateOperator(update.$addToSet); - } - if (update.$set != null) { - const keys = Object.keys(update.$set); - for (const key of keys) { - applyTimestampsToUpdateKey(schema, key, update.$set, now); - } - } - if (update.$setOnInsert != null) { - const keys = Object.keys(update.$setOnInsert); - for (const key of keys) { - applyTimestampsToUpdateKey(schema, key, update.$setOnInsert, now); - } - } - } +/** + * This function is responsible for building [indexes](https://docs.mongodb.com/manual/indexes/), + * unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off. + * + * Mongoose calls this function automatically when a model is created using + * [`mongoose.model()`](/docs/api.html#mongoose_Mongoose-model) or + * [`connection.model()`](/docs/api.html#connection_Connection-model), so you + * don't need to call it. This function is also idempotent, so you may call it + * to get back a promise that will resolve when your indexes are finished + * building as an alternative to [`MyModel.on('index')`](/docs/guide.html#indexes) + * + * ####Example: + * + * const eventSchema = new Schema({ thing: { type: 'string', unique: true }}) + * // This calls `Event.init()` implicitly, so you don't need to call + * // `Event.init()` on your own. + * const Event = mongoose.model('Event', eventSchema); + * + * Event.init().then(function(Event) { + * // You can also use `Event.on('index')` if you prefer event emitters + * // over promises. + * console.log('Indexes are done building!'); + * }); + * + * @api public + * @param {Function} [callback] + * @returns {Promise} + */ - const updateKeys = Object.keys(update).filter( - (key) => !key.startsWith("$") - ); - for (const key of updateKeys) { - applyTimestampsToUpdateKey(schema, key, update, now); - } +Model.init = function init(callback) { + _checkContext(this, 'init'); - function _applyTimestampToUpdateOperator(op) { - for (const key of Object.keys(op)) { - const $path = schema.path( - key.replace(/\.\$\./i, ".").replace(/.\$$/, "") - ); - if ( - op[key] && - $path && - $path.$isMongooseDocumentArray && - $path.schema.options.timestamps - ) { - const timestamps = $path.schema.options.timestamps; - const createdAt = handleTimestampOption(timestamps, "createdAt"); - const updatedAt = handleTimestampOption(timestamps, "updatedAt"); - if (op[key].$each) { - op[key].$each.forEach(function (subdoc) { - if (updatedAt != null) { - subdoc[updatedAt] = now; - } - if (createdAt != null) { - subdoc[createdAt] = now; - } - }); - } else { - if (updatedAt != null) { - op[key][updatedAt] = now; - } - if (createdAt != null) { - op[key][createdAt] = now; - } - } - } - } - } - } + this.schema.emit('init', this); - function applyTimestampsToDocumentArray(arr, schematype, now) { - const timestamps = schematype.schema.options.timestamps; + if (this.$init != null) { + if (callback) { + this.$init.then(() => callback(), err => callback(err)); + return null; + } + return this.$init; + } - if (!timestamps) { - return; + const Promise = PromiseProvider.get(); + const autoIndex = utils.getOption('autoIndex', + this.schema.options, this.db.config, this.db.base.options); + const autoCreate = utils.getOption('autoCreate', + this.schema.options, this.db.config, this.db.base.options); + + const _ensureIndexes = autoIndex ? + cb => this.ensureIndexes({ _automatic: true }, cb) : + cb => cb(); + const _createCollection = autoCreate ? + cb => this.createCollection({}, cb) : + cb => cb(); + + this.$init = new Promise((resolve, reject) => { + _createCollection(error => { + if (error) { + return reject(error); + } + _ensureIndexes(error => { + if (error) { + return reject(error); } + resolve(this); + }); + }); + }); + + if (callback) { + this.$init.then(() => callback(), err => callback(err)); + this.$caught = true; + return null; + } else { + const _catch = this.$init.catch; + const _this = this; + this.$init.catch = function() { + this.$caught = true; + return _catch.apply(_this.$init, arguments); + }; + } - const len = arr.length; + return this.$init; +}; - const createdAt = handleTimestampOption(timestamps, "createdAt"); - const updatedAt = handleTimestampOption(timestamps, "updatedAt"); - for (let i = 0; i < len; ++i) { - if (updatedAt != null) { - arr[i][updatedAt] = now; - } - if (createdAt != null) { - arr[i][createdAt] = now; - } - applyTimestampsToChildren(now, arr[i], schematype.schema); - } - } +/** + * Create the collection for this model. By default, if no indexes are specified, + * mongoose will not create the collection for the model until any documents are + * created. Use this method to create the collection explicitly. + * + * Note 1: You may need to call this before starting a transaction + * See https://docs.mongodb.com/manual/core/transactions/#transactions-and-operations + * + * Note 2: You don't have to call this if your schema contains index or unique field. + * In that case, just use `Model.init()` + * + * ####Example: + * + * const userSchema = new Schema({ name: String }) + * const User = mongoose.model('User', userSchema); + * + * User.createCollection().then(function(collection) { + * console.log('Collection is created!'); + * }); + * + * @api public + * @param {Object} [options] see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection) + * @param {Function} [callback] + * @returns {Promise} + */ - function applyTimestampsToSingleNested(subdoc, schematype, now) { - const timestamps = schematype.schema.options.timestamps; - if (!timestamps) { - return; - } +Model.createCollection = function createCollection(options, callback) { + _checkContext(this, 'createCollection'); - const createdAt = handleTimestampOption(timestamps, "createdAt"); - const updatedAt = handleTimestampOption(timestamps, "updatedAt"); - if (updatedAt != null) { - subdoc[updatedAt] = now; - } - if (createdAt != null) { - subdoc[createdAt] = now; - } + if (typeof options === 'string') { + throw new MongooseError('You can\'t specify a new collection name in Model.createCollection.' + + 'This is not like Connection.createCollection. Only options are accepted here.'); + } else if (typeof options === 'function') { + callback = options; + options = void 0; + } - applyTimestampsToChildren(now, subdoc, schematype.schema); - } + const schemaCollation = get(this, ['schema', 'options', 'collation'], null); + if (schemaCollation != null) { + options = Object.assign({ collation: schemaCollation }, options); + } + const capped = get(this, ['schema', 'options', 'capped']); + if (capped) { + options = Object.assign({ capped: true }, capped, options); + } + const timeseries = get(this, ['schema', 'options', 'timeseries']); + if (timeseries != null) { + options = Object.assign({ timeseries }, options); + } - function applyTimestampsToUpdateKey(schema, key, update, now) { - // Replace positional operator `$` and array filters `$[]` and `$[.*]` - const keyToSearch = cleanPositionalOperators(key); - const path = schema.path(keyToSearch); - if (!path) { - return; - } + callback = this.$handleCallbackError(callback); - const parentSchemaTypes = []; - const pieces = keyToSearch.split("."); - for (let i = pieces.length - 1; i > 0; --i) { - const s = schema.path(pieces.slice(0, i).join(".")); - if (s != null && (s.$isMongooseDocumentArray || s.$isSingleNested)) { - parentSchemaTypes.push({ - parentPath: key.split(".").slice(0, i).join("."), - parentSchemaType: s, - }); - } - } + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); - if (Array.isArray(update[key]) && path.$isMongooseDocumentArray) { - applyTimestampsToDocumentArray(update[key], path, now); - } else if (update[key] && path.$isSingleNested) { - applyTimestampsToSingleNested(update[key], path, now); - } else if (parentSchemaTypes.length > 0) { - for (const item of parentSchemaTypes) { - const parentPath = item.parentPath; - const parentSchemaType = item.parentSchemaType; - const timestamps = parentSchemaType.schema.options.timestamps; - const updatedAt = handleTimestampOption(timestamps, "updatedAt"); + this.db.createCollection(this.$__collection.collectionName, options, utils.tick((err) => { + if (err != null && (err.name !== 'MongoServerError' || err.code !== 48)) { + return cb(err); + } + this.$__collection = this.db.collection(this.$__collection.collectionName, options); + cb(null, this.$__collection); + })); + }, this.events); +}; - if (!timestamps || updatedAt == null) { - continue; - } +/** + * Makes the indexes in MongoDB match the indexes defined in this model's + * schema. This function will drop any indexes that are not defined in + * the model's schema except the `_id` index, and build any indexes that + * are in your schema but not in MongoDB. + * + * See the [introductory blog post](http://thecodebarbarian.com/whats-new-in-mongoose-5-2-syncindexes) + * for more information. + * + * ####Example: + * + * const schema = new Schema({ name: { type: String, unique: true } }); + * const Customer = mongoose.model('Customer', schema); + * await Customer.collection.createIndex({ age: 1 }); // Index is not in schema + * // Will drop the 'age' index and create an index on `name` + * await Customer.syncIndexes(); + * + * @param {Object} [options] options to pass to `ensureIndexes()` + * @param {Boolean} [options.background=null] if specified, overrides each index's `background` property + * @param {Function} [callback] optional callback + * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. + * @api public + */ - if (parentSchemaType.$isSingleNested) { - // Single nested is easy - update[parentPath + "." + updatedAt] = now; - } else if (parentSchemaType.$isMongooseDocumentArray) { - let childPath = key.substr(parentPath.length + 1); +Model.syncIndexes = function syncIndexes(options, callback) { + _checkContext(this, 'syncIndexes'); - if (/^\d+$/.test(childPath)) { - update[parentPath + "." + childPath][updatedAt] = now; - continue; - } + callback = this.$handleCallbackError(callback); - const firstDot = childPath.indexOf("."); - childPath = - firstDot !== -1 ? childPath.substr(0, firstDot) : childPath; + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); - update[parentPath + "." + childPath + "." + updatedAt] = now; - } + this.createCollection(err => { + if (err != null && (err.name !== 'MongoServerError' || err.code !== 48)) { + return cb(err); + } + this.cleanIndexes((err, dropped) => { + if (err != null) { + return cb(err); + } + this.createIndexes(options, err => { + if (err != null) { + return cb(err); } - } else if ( - path.schema != null && - path.schema != schema && - update[key] - ) { - const timestamps = path.schema.options.timestamps; - const createdAt = handleTimestampOption(timestamps, "createdAt"); - const updatedAt = handleTimestampOption(timestamps, "updatedAt"); + cb(null, dropped); + }); + }); + }); + }, this.events); +}; - if (!timestamps) { - return; - } +/** + * Does a dry-run of Model.syncIndexes(), meaning that + * the result of this function would be the result of + * Model.syncIndexes(). + * + * @param {Object} options not used at all. + * @param {Function} callback optional callback + * @returns {Promise} which containts an object, {toDrop, toCreate}, which + * are indexes that would be dropped in mongodb and indexes that would be created in mongodb. + */ - if (updatedAt != null) { - update[key][updatedAt] = now; - } - if (createdAt != null) { - update[key][createdAt] = now; +Model.diffIndexes = function diffIndexes(options, callback) { + const toDrop = []; + const toCreate = []; + callback = this.$handleCallbackError(callback); + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); + this.listIndexes((err, indexes) => { + if (indexes === undefined) { + indexes = []; + } + const schemaIndexes = this.schema.indexes(); + // Iterate through the indexes created in mongodb and + // compare against the indexes in the schema. + for (const index of indexes) { + let found = false; + // Never try to drop `_id` index, MongoDB server doesn't allow it + if (isDefaultIdIndex(index)) { + continue; + } + + for (const schemaIndex of schemaIndexes) { + const key = schemaIndex[0]; + const options = _decorateDiscriminatorIndexOptions(this, + utils.clone(schemaIndex[1])); + if (isIndexEqual(key, options, index)) { + found = true; } } - } - - /***/ - }, - /***/ 1162: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * ignore - */ - - const get = __nccwpck_require__(8730); - - module.exports = applyTimestampsToUpdate; - - /*! - * ignore - */ - - function applyTimestampsToUpdate( - now, - createdAt, - updatedAt, - currentUpdate, - options - ) { - const updates = currentUpdate; - let _updates = updates; - const overwrite = get(options, "overwrite", false); - const timestamps = get(options, "timestamps", true); - - // Support skipping timestamps at the query level, see gh-6980 - if (!timestamps || updates == null) { - return currentUpdate; - } - - const skipCreatedAt = - timestamps != null && timestamps.createdAt === false; - const skipUpdatedAt = - timestamps != null && timestamps.updatedAt === false; - - if (overwrite) { - if (currentUpdate && currentUpdate.$set) { - currentUpdate = currentUpdate.$set; - updates.$set = {}; - _updates = updates.$set; - } - if (!skipUpdatedAt && updatedAt && !currentUpdate[updatedAt]) { - _updates[updatedAt] = now; + if (!found) { + toDrop.push(index.name); + } + } + // Iterate through the indexes created on the schema and + // compare against the indexes in mongodb. + for (const schemaIndex of schemaIndexes) { + const key = schemaIndex[0]; + let found = false; + const options = _decorateDiscriminatorIndexOptions(this, + utils.clone(schemaIndex[1])); + for (const index of indexes) { + if (isDefaultIdIndex(index)) { + continue; } - if (!skipCreatedAt && createdAt && !currentUpdate[createdAt]) { - _updates[createdAt] = now; + if (isIndexEqual(key, options, index)) { + found = true; } - return updates; } - currentUpdate = currentUpdate || {}; + if (!found) { + toCreate.push(key); + } + } + cb(null, { toDrop, toCreate }); + }); + }); +}; - if (Array.isArray(updates)) { - // Update with aggregation pipeline - updates.push({ $set: { updatedAt: now } }); +/** + * Deletes all indexes that aren't defined in this model's schema. Used by + * `syncIndexes()`. + * + * The returned promise resolves to a list of the dropped indexes' names as an array + * + * @param {Function} [callback] optional callback + * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. + * @api public + */ - return updates; - } +Model.cleanIndexes = function cleanIndexes(callback) { + _checkContext(this, 'cleanIndexes'); - updates.$set = updates.$set || {}; - if ( - !skipUpdatedAt && - updatedAt && - (!currentUpdate.$currentDate || - !currentUpdate.$currentDate[updatedAt]) - ) { - let timestampSet = false; - if (updatedAt.indexOf(".") !== -1) { - const pieces = updatedAt.split("."); - for (let i = 1; i < pieces.length; ++i) { - const remnant = pieces.slice(-i).join("."); - const start = pieces.slice(0, -i).join("."); - if (currentUpdate[start] != null) { - currentUpdate[start][remnant] = now; - timestampSet = true; - break; - } else if (currentUpdate.$set && currentUpdate.$set[start]) { - currentUpdate.$set[start][remnant] = now; - timestampSet = true; - break; - } - } - } + callback = this.$handleCallbackError(callback); - if (!timestampSet) { - updates.$set[updatedAt] = now; - } + return this.db.base._promiseOrCallback(callback, cb => { + const collection = this.$__collection; - if (updates.hasOwnProperty(updatedAt)) { - delete updates[updatedAt]; - } - } + this.listIndexes((err, indexes) => { + if (err != null) { + return cb(err); + } - if (!skipCreatedAt && createdAt) { - if (currentUpdate[createdAt]) { - delete currentUpdate[createdAt]; - } - if (currentUpdate.$set && currentUpdate.$set[createdAt]) { - delete currentUpdate.$set[createdAt]; - } + const schemaIndexes = this.schema.indexes(); + const toDrop = []; - let timestampSet = false; - if (createdAt.indexOf(".") !== -1) { - const pieces = createdAt.split("."); - for (let i = 1; i < pieces.length; ++i) { - const remnant = pieces.slice(-i).join("."); - const start = pieces.slice(0, -i).join("."); - if (currentUpdate[start] != null) { - currentUpdate[start][remnant] = now; - timestampSet = true; - break; - } else if (currentUpdate.$set && currentUpdate.$set[start]) { - currentUpdate.$set[start][remnant] = now; - timestampSet = true; - break; - } - } - } + for (const index of indexes) { + let found = false; + // Never try to drop `_id` index, MongoDB server doesn't allow it + if (isDefaultIdIndex(index)) { + continue; + } - if (!timestampSet) { - updates.$setOnInsert = updates.$setOnInsert || {}; - updates.$setOnInsert[createdAt] = now; + for (const schemaIndex of schemaIndexes) { + const key = schemaIndex[0]; + const options = _decorateDiscriminatorIndexOptions(this, + utils.clone(schemaIndex[1])); + if (isIndexEqual(key, options, index)) { + found = true; } } - if (Object.keys(updates.$set).length === 0) { - delete updates.$set; + if (!found) { + toDrop.push(index.name); } + } - return updates; + if (toDrop.length === 0) { + return cb(null, []); } - /***/ - }, + dropIndexes(toDrop, cb); + }); - /***/ 4856: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const castFilterPath = __nccwpck_require__(8045); - const cleanPositionalOperators = __nccwpck_require__(1119); - const getPath = __nccwpck_require__(7453); - const updatedPathsByArrayFilter = __nccwpck_require__(6507); - - module.exports = function castArrayFilters(query) { - const arrayFilters = query.options.arrayFilters; - if (!Array.isArray(arrayFilters)) { - return; - } + function dropIndexes(toDrop, cb) { + let remaining = toDrop.length; + let error = false; + toDrop.forEach(indexName => { + collection.dropIndex(indexName, err => { + if (err != null) { + error = true; + return cb(err); + } + if (!error) { + --remaining || cb(null, toDrop); + } + }); + }); + } + }); +}; + +/** + * Lists the indexes currently defined in MongoDB. This may or may not be + * the same as the indexes defined in your schema depending on whether you + * use the [`autoIndex` option](/docs/guide.html#autoIndex) and if you + * build indexes manually. + * + * @param {Function} [cb] optional callback + * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. + * @api public + */ - const update = query.getUpdate(); - const schema = query.schema; - const strictQuery = schema.options.strictQuery; +Model.listIndexes = function init(callback) { + _checkContext(this, 'listIndexes'); - const updatedPathsByFilter = updatedPathsByArrayFilter(update); + const _listIndexes = cb => { + this.$__collection.listIndexes().toArray(cb); + }; - for (const filter of arrayFilters) { - if (filter == null) { - throw new Error(`Got null array filter in ${arrayFilters}`); - } - for (const key of Object.keys(filter)) { - if (filter[key] == null) { - continue; - } + callback = this.$handleCallbackError(callback); - const dot = key.indexOf("."); - let filterPath = - dot === -1 - ? updatedPathsByFilter[key] + ".0" - : updatedPathsByFilter[key.substr(0, dot)] + - ".0" + - key.substr(dot); + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); - if (filterPath == null) { - throw new Error(`Filter path not found for ${key}`); - } + // Buffering + if (this.$__collection.buffer) { + this.$__collection.addQueue(_listIndexes, [cb]); + } else { + _listIndexes(cb); + } + }, this.events); +}; - // If there are multiple array filters in the path being updated, make sure - // to replace them so we can get the schema path. - filterPath = cleanPositionalOperators(filterPath); +/** + * Sends `createIndex` commands to mongo for each index declared in the schema. + * The `createIndex` commands are sent in series. + * + * ####Example: + * + * Event.ensureIndexes(function (err) { + * if (err) return handleError(err); + * }); + * + * After completion, an `index` event is emitted on this `Model` passing an error if one occurred. + * + * ####Example: + * + * const eventSchema = new Schema({ thing: { type: 'string', unique: true }}) + * const Event = mongoose.model('Event', eventSchema); + * + * Event.on('index', function (err) { + * if (err) console.error(err); // error occurred during index creation + * }) + * + * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._ + * + * @param {Object} [options] internal options + * @param {Function} [cb] optional callback + * @return {Promise} + * @api public + */ - const schematype = getPath(schema, filterPath); - if (schematype == null) { - if (!strictQuery) { - return; - } - // For now, treat `strictQuery = true` and `strictQuery = 'throw'` as - // equivalent for casting array filters. `strictQuery = true` doesn't - // quite work in this context because we never want to silently strip out - // array filters, even if the path isn't in the schema. - throw new Error(`Could not find path "${filterPath}" in schema`); - } - if (typeof filter[key] === "object") { - filter[key] = castFilterPath(query, schematype, filter[key]); - } else { - filter[key] = schematype.castForQuery(filter[key]); - } - } - } - }; +Model.ensureIndexes = function ensureIndexes(options, callback) { + _checkContext(this, 'ensureIndexes'); - /***/ - }, + if (typeof options === 'function') { + callback = options; + options = null; + } - /***/ 587: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const _modifiedPaths = __nccwpck_require__(3719) /* .modifiedPaths */.M; - - /** - * Given an update document with potential update operators (`$set`, etc.) - * returns an object whose keys are the directly modified paths. - * - * If there are any top-level keys that don't start with `$`, we assume those - * will get wrapped in a `$set`. The Mongoose Query is responsible for wrapping - * top-level keys in `$set`. - * - * @param {Object} update - * @return {Object} modified - */ - - module.exports = function modifiedPaths(update) { - const keys = Object.keys(update); - const res = {}; + callback = this.$handleCallbackError(callback); - const withoutDollarKeys = {}; - for (const key of keys) { - if (key.startsWith("$")) { - _modifiedPaths(update[key], "", res); - continue; - } - withoutDollarKeys[key] = update[key]; - } + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); - _modifiedPaths(withoutDollarKeys, "", res); + _ensureIndexes(this, options || {}, error => { + if (error) { + return cb(error); + } + cb(null); + }); + }, this.events); +}; - return res; - }; +/** + * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex) + * function. + * + * @param {Object} [options] internal options + * @param {Function} [cb] optional callback + * @return {Promise} + * @api public + */ - /***/ - }, +Model.createIndexes = function createIndexes(options, callback) { + _checkContext(this, 'createIndexes'); - /***/ 4632: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + if (typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + options.createIndex = true; + return this.ensureIndexes(options, callback); +}; - const get = __nccwpck_require__(8730); +/*! + * ignore + */ - /** - * Given an update, move all $set on immutable properties to $setOnInsert. - * This should only be called for upserts, because $setOnInsert bypasses the - * strictness check for immutable properties. - */ +function _ensureIndexes(model, options, callback) { + const indexes = model.schema.indexes(); + let indexError; - module.exports = function moveImmutableProperties(schema, update, ctx) { - if (update == null) { - return; - } + options = options || {}; + const done = function(err) { + if (err && !model.$caught) { + model.emit('error', err); + } + model.emit('index', err || indexError); + callback && callback(err || indexError); + }; - const keys = Object.keys(update); - for (const key of keys) { - const isDollarKey = key.startsWith("$"); + for (const index of indexes) { + if (isDefaultIdIndex(index)) { + utils.warn('mongoose: Cannot specify a custom index on `_id` for ' + + 'model name "' + model.modelName + '", ' + + 'MongoDB does not allow overwriting the default `_id` index. See ' + + 'http://bit.ly/mongodb-id-index'); + } + } - if (key === "$set") { - const updatedPaths = Object.keys(update[key]); - for (const path of updatedPaths) { - _walkUpdatePath(schema, update[key], path, update, ctx); - } - } else if (!isDollarKey) { - _walkUpdatePath(schema, update, key, update, ctx); - } - } - }; + if (!indexes.length) { + immediate(function() { + done(); + }); + return; + } + // Indexes are created one-by-one to support how MongoDB < 2.4 deals + // with background indexes. - function _walkUpdatePath(schema, op, path, update, ctx) { - const schematype = schema.path(path); - if (schematype == null) { - return; - } + const indexSingleDone = function(err, fields, options, name) { + model.emit('index-single-done', err, fields, options, name); + }; + const indexSingleStart = function(fields, options) { + model.emit('index-single-start', fields, options); + }; - let immutable = get(schematype, "options.immutable", null); - if (immutable == null) { - return; - } - if (typeof immutable === "function") { - immutable = immutable.call(ctx, ctx); - } + const baseSchema = model.schema._baseSchema; + const baseSchemaIndexes = baseSchema ? baseSchema.indexes() : []; - if (!immutable) { - return; - } + const create = function() { + if (options._automatic) { + if (model.schema.options.autoIndex === false || + (model.schema.options.autoIndex == null && model.db.config.autoIndex === false)) { + return done(); + } + } + + const index = indexes.shift(); + if (!index) { + return done(); + } + if (options._automatic && index[1]._autoIndex === false) { + return create(); + } + + if (baseSchemaIndexes.find(i => utils.deepEqual(i, index))) { + return create(); + } - update.$setOnInsert = update.$setOnInsert || {}; - update.$setOnInsert[path] = op[path]; - delete op[path]; + const indexFields = utils.clone(index[0]); + const indexOptions = utils.clone(index[1]); + let isTextIndex = false; + for (const key of Object.keys(indexFields)) { + if (indexFields[key] === 'text') { + isTextIndex = true; } + } + delete indexOptions._autoIndex; + _decorateDiscriminatorIndexOptions(model, indexOptions); + applyWriteConcern(model.schema, indexOptions); - /***/ - }, + indexSingleStart(indexFields, options); - /***/ 8909: /***/ (module) => { - "use strict"; - - /** - * MongoDB throws an error if there's unused array filters. That is, if `options.arrayFilters` defines - * a filter, but none of the `update` keys use it. This should be enough to filter out all unused array - * filters. - */ - - module.exports = function removeUnusedArrayFilters(update, arrayFilters) { - const updateKeys = Object.keys(update) - .map((key) => Object.keys(update[key])) - .reduce((cur, arr) => cur.concat(arr), []); - return arrayFilters.filter((obj) => { - const firstKey = Object.keys(obj)[0]; - const firstDot = firstKey.indexOf("."); - const arrayFilterKey = - firstDot === -1 ? firstKey : firstKey.slice(0, firstDot); - - return ( - updateKeys.find((key) => - key.includes("$[" + arrayFilterKey + "]") - ) != null - ); - }); - }; + if ('background' in options) { + indexOptions.background = options.background; + } + if (model.schema.options.hasOwnProperty('collation') && + !indexOptions.hasOwnProperty('collation') && + !isTextIndex) { + indexOptions.collation = model.schema.options.collation; + } - /***/ - }, + model.collection.createIndex(indexFields, indexOptions, utils.tick(function(err, name) { + indexSingleDone(err, indexFields, indexOptions, name); + if (err) { + if (!indexError) { + indexError = err; + } + if (!model.$caught) { + model.emit('error', err); + } + } + create(); + })); + }; - /***/ 6507: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + immediate(function() { + // If buffering is off, do this manually. + if (options._automatic && !model.collection.collection) { + model.collection.addQueue(create, []); + } else { + create(); + } + }); +} + +function _decorateDiscriminatorIndexOptions(model, indexOptions) { + // If the model is a discriminator and it has a unique index, add a + // partialFilterExpression by default so the unique index will only apply + // to that discriminator. + if (model.baseModelName != null && + !('partialFilterExpression' in indexOptions) && + !('sparse' in indexOptions)) { + const value = ( + model.schema.discriminatorMapping && + model.schema.discriminatorMapping.value + ) || model.modelName; + const discriminatorKey = model.schema.options.discriminatorKey; + + indexOptions.partialFilterExpression = { [discriminatorKey]: value }; + } + return indexOptions; +} - const modifiedPaths = __nccwpck_require__(587); +/** + * Schema the model uses. + * + * @property schema + * @receiver Model + * @api public + * @memberOf Model + */ - module.exports = function updatedPathsByArrayFilter(update) { - const updatedPaths = modifiedPaths(update); +Model.schema; - return Object.keys(updatedPaths).reduce((cur, path) => { - const matches = path.match(/\$\[[^\]]+\]/g); - if (matches == null) { - return cur; - } - for (const match of matches) { - const firstMatch = path.indexOf(match); - if (firstMatch !== path.lastIndexOf(match)) { - throw new Error( - `Path '${path}' contains the same array filter multiple times` - ); - } - cur[match.substring(2, match.length - 1)] = path - .substr(0, firstMatch - 1) - .replace(/\$\[[^\]]+\]/g, "0"); - } - return cur; - }, {}); - }; +/*! + * Connection instance the model uses. + * + * @property db + * @api public + * @memberOf Model + */ - /***/ - }, +Model.db; - /***/ 9009: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const ValidationError = __nccwpck_require__(8460); - const cleanPositionalOperators = __nccwpck_require__(1119); - const flatten = __nccwpck_require__(3719) /* .flatten */.x; - const modifiedPaths = __nccwpck_require__(3719) /* .modifiedPaths */.M; - - /** - * Applies validators and defaults to update and findOneAndUpdate operations, - * specifically passing a null doc as `this` to validators and defaults - * - * @param {Query} query - * @param {Schema} schema - * @param {Object} castedDoc - * @param {Object} options - * @method runValidatorsOnUpdate - * @api private - */ - - module.exports = function (query, schema, castedDoc, options, callback) { - let _keys; - const keys = Object.keys(castedDoc || {}); - let updatedKeys = {}; - let updatedValues = {}; - const isPull = {}; - const arrayAtomicUpdates = {}; - const numKeys = keys.length; - let hasDollarUpdate = false; - const modified = {}; - let currentUpdate; - let key; - let i; - - for (i = 0; i < numKeys; ++i) { - if (keys[i].startsWith("$")) { - hasDollarUpdate = true; - if (keys[i] === "$push" || keys[i] === "$addToSet") { - _keys = Object.keys(castedDoc[keys[i]]); - for (let ii = 0; ii < _keys.length; ++ii) { - currentUpdate = castedDoc[keys[i]][_keys[ii]]; - if (currentUpdate && currentUpdate.$each) { - arrayAtomicUpdates[_keys[ii]] = ( - arrayAtomicUpdates[_keys[ii]] || [] - ).concat(currentUpdate.$each); - } else { - arrayAtomicUpdates[_keys[ii]] = ( - arrayAtomicUpdates[_keys[ii]] || [] - ).concat([currentUpdate]); - } - } - continue; - } - modifiedPaths(castedDoc[keys[i]], "", modified); - const flat = flatten(castedDoc[keys[i]], null, null, schema); - const paths = Object.keys(flat); - const numPaths = paths.length; - for (let j = 0; j < numPaths; ++j) { - const updatedPath = cleanPositionalOperators(paths[j]); - key = keys[i]; - // With `$pull` we might flatten `$in`. Skip stuff nested under `$in` - // for the rest of the logic, it will get handled later. - if (updatedPath.includes("$")) { - continue; - } - if ( - key === "$set" || - key === "$setOnInsert" || - key === "$pull" || - key === "$pullAll" - ) { - updatedValues[updatedPath] = flat[paths[j]]; - isPull[updatedPath] = key === "$pull" || key === "$pullAll"; - } else if (key === "$unset") { - updatedValues[updatedPath] = undefined; - } - updatedKeys[updatedPath] = true; - } - } - } +/*! + * Collection the model uses. + * + * @property collection + * @api public + * @memberOf Model + */ - if (!hasDollarUpdate) { - modifiedPaths(castedDoc, "", modified); - updatedValues = flatten(castedDoc, null, null, schema); - updatedKeys = Object.keys(updatedValues); - } +Model.collection; - const updates = Object.keys(updatedValues); - const numUpdates = updates.length; - const validatorsToExecute = []; - const validationErrors = []; +/** + * Internal collection the model uses. + * + * @property collection + * @api private + * @memberOf Model + */ +Model.$__collection; - const alreadyValidated = []; +/** + * Base Mongoose instance the model uses. + * + * @property base + * @api public + * @memberOf Model + */ - const context = options && options.context === "query" ? query : null; - function iter(i, v) { - const schemaPath = schema._getSchema(updates[i]); - if (schemaPath == null) { - return; - } - if ( - schemaPath.instance === "Mixed" && - schemaPath.path !== updates[i] - ) { - return; - } +Model.base; - if (v && Array.isArray(v.$in)) { - v.$in.forEach((v, i) => { - validatorsToExecute.push(function (callback) { - schemaPath.doValidate( - v, - function (err) { - if (err) { - err.path = updates[i] + ".$in." + i; - validationErrors.push(err); - } - callback(null); - }, - context, - { updateValidator: true } - ); - }); - }); - } else { - if (isPull[updates[i]] && schemaPath.$isMongooseArray) { - return; - } +/** + * Registered discriminators for this model. + * + * @property discriminators + * @api public + * @memberOf Model + */ - if ( - schemaPath.$isMongooseDocumentArrayElement && - v != null && - v.$__ != null - ) { - alreadyValidated.push(updates[i]); - validatorsToExecute.push(function (callback) { - schemaPath.doValidate( - v, - function (err) { - if (err) { - err.path = updates[i]; - validationErrors.push(err); - return callback(null); - } +Model.discriminators; - v.validate(function (err) { - if (err) { - if (err.errors) { - for (const key of Object.keys(err.errors)) { - const _err = err.errors[key]; - _err.path = updates[i] + "." + key; - validationErrors.push(_err); - } - } else { - err.path = updates[i]; - validationErrors.push(err); - } - } - callback(null); - }); - }, - context, - { updateValidator: true } - ); - }); - } else { - validatorsToExecute.push(function (callback) { - for (const path of alreadyValidated) { - if (updates[i].startsWith(path + ".")) { - return callback(null); - } - } +/** + * Translate any aliases fields/conditions so the final query or document object is pure + * + * ####Example: + * + * Character + * .find(Character.translateAliases({ + * '名': 'Eddard Stark' // Alias for 'name' + * }) + * .exec(function(err, characters) {}) + * + * ####Note: + * Only translate arguments of object type anything else is returned raw + * + * @param {Object} raw fields/conditions that may contain aliased keys + * @return {Object} the translated 'pure' fields/conditions + */ +Model.translateAliases = function translateAliases(fields) { + _checkContext(this, 'translateAliases'); + + const translate = (key, value) => { + let alias; + const translated = []; + const fieldKeys = key.split('.'); + let currentSchema = this.schema; + for (const i in fieldKeys) { + const name = fieldKeys[i]; + if (currentSchema && currentSchema.aliases[name]) { + alias = currentSchema.aliases[name]; + // Alias found, + translated.push(alias); + } else { + alias = name; + // Alias not found, so treat as un-aliased key + translated.push(name); + } - schemaPath.doValidate( - v, - function (err) { - if ( - schemaPath.schema != null && - schemaPath.schema.options.storeSubdocValidationError === - false && - err instanceof ValidationError - ) { - return callback(null); - } + // Check if aliased path is a schema + if (currentSchema && currentSchema.paths[alias]) { + currentSchema = currentSchema.paths[alias].schema; + } + else + currentSchema = null; + } - if (err) { - err.path = updates[i]; - validationErrors.push(err); - } - callback(null); - }, - context, - { updateValidator: true } - ); - }); - } - } - } - for (i = 0; i < numUpdates; ++i) { - iter(i, updatedValues[updates[i]]); - } + const translatedKey = translated.join('.'); + if (fields instanceof Map) + fields.set(translatedKey, value); + else + fields[translatedKey] = value; + + if (translatedKey !== key) { + // We'll be using the translated key instead + if (fields instanceof Map) { + // Delete from map + fields.delete(key); + } else { + // Delete from object + delete fields[key]; // We'll be using the translated key instead + } + } + return fields; + }; - const arrayUpdates = Object.keys(arrayAtomicUpdates); - for (const arrayUpdate of arrayUpdates) { - let schemaPath = schema._getSchema(arrayUpdate); - if (schemaPath && schemaPath.$isMongooseDocumentArray) { - validatorsToExecute.push(function (callback) { - schemaPath.doValidate( - arrayAtomicUpdates[arrayUpdate], - getValidationCallback(arrayUpdate, validationErrors, callback), - options && options.context === "query" ? query : null - ); - }); - } else { - schemaPath = schema._getSchema(arrayUpdate + ".0"); - for (const atomicUpdate of arrayAtomicUpdates[arrayUpdate]) { - validatorsToExecute.push(function (callback) { - schemaPath.doValidate( - atomicUpdate, - getValidationCallback( - arrayUpdate, - validationErrors, - callback - ), - options && options.context === "query" ? query : null, - { updateValidator: true } - ); - }); + if (typeof fields === 'object') { + // Fields is an object (query conditions or document fields) + if (fields instanceof Map) { + // A Map was supplied + for (const field of new Map(fields)) { + fields = translate(field[0], field[1]); + } + } else { + // Infer a regular object was supplied + for (const key of Object.keys(fields)) { + fields = translate(key, fields[key]); + if (key[0] === '$') { + if (Array.isArray(fields[key])) { + for (const i in fields[key]) { + // Recursively translate nested queries + fields[key][i] = this.translateAliases(fields[key][i]); } } } + } + } - if (callback != null) { - let numValidators = validatorsToExecute.length; - if (numValidators === 0) { - return _done(callback); - } - for (const validator of validatorsToExecute) { - validator(function () { - if (--numValidators <= 0) { - _done(callback); - } - }); - } - - return; - } - - return function (callback) { - let numValidators = validatorsToExecute.length; - if (numValidators === 0) { - return _done(callback); - } - for (const validator of validatorsToExecute) { - validator(function () { - if (--numValidators <= 0) { - _done(callback); - } - }); - } - }; + return fields; + } else { + // Don't know typeof fields + return fields; + } +}; - function _done(callback) { - if (validationErrors.length) { - const err = new ValidationError(null); +/** + * Removes all documents that match `conditions` from the collection. + * To remove just the first document that matches `conditions`, set the `single` + * option to true. + * + * This method is deprecated. See [Deprecation Warnings](../deprecations.html#remove) for details. + * + * ####Example: + * + * const res = await Character.remove({ name: 'Eddard Stark' }); + * res.deletedCount; // Number of documents removed + * + * ####Note: + * + * This method sends a remove command directly to MongoDB, no Mongoose documents + * are involved. Because no Mongoose documents are involved, Mongoose does + * not execute [document middleware](/docs/middleware.html#types-of-middleware). + * + * @deprecated + * @param {Object} conditions + * @param {Object} [options] + * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this operation. + * @param {Function} [callback] + * @return {Query} + * @api public + */ - for (const validationError of validationErrors) { - err.addError(validationError.path, validationError); - } +Model.remove = function remove(conditions, options, callback) { + _checkContext(this, 'remove'); - return callback(err); - } - callback(null); - } + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + options = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } - function getValidationCallback( - arrayUpdate, - validationErrors, - callback - ) { - return function (err) { - if (err) { - err.path = arrayUpdate; - validationErrors.push(err); - } - callback(null); - }; - } - }; + // get the mongodb collection object + const mq = new this.Query({}, {}, this, this.$__collection); + mq.setOptions(options); - /***/ - }, + callback = this.$handleCallbackError(callback); - /***/ 1028: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; + return mq.remove(conditions, callback); +}; - /*! - * Module dependencies. - */ +/** + * Deletes the first document that matches `conditions` from the collection. + * It returns an object with the property `deletedCount` indicating how many documents were deleted. + * Behaves like `remove()`, but deletes at most one document regardless of the + * `single` option. + * + * ####Example: + * + * await Character.deleteOne({ name: 'Eddard Stark' }); // returns {deletedCount: 1} + * + * ####Note: + * + * This function triggers `deleteOne` query hooks. Read the + * [middleware docs](/docs/middleware.html#naming) to learn more. + * + * @param {Object} conditions + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] + * @return {Query} + * @api public + */ - if (global.MONGOOSE_DRIVER_PATH) { - const deprecationWarning = - "The `MONGOOSE_DRIVER_PATH` global property is " + - "deprecated. Use `mongoose.driver.set()` instead."; - const setDriver = __nccwpck_require__(1669).deprecate(function () { - __nccwpck_require__(2324).set( - __nccwpck_require__(869)(global.MONGOOSE_DRIVER_PATH) - ); - }, deprecationWarning); - setDriver(); - } else { - __nccwpck_require__(2324).set(__nccwpck_require__(2676)); - } - - const Document = __nccwpck_require__(6717); - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const Schema = __nccwpck_require__(7606); - const SchemaType = __nccwpck_require__(5660); - const SchemaTypes = __nccwpck_require__(2987); - const VirtualType = __nccwpck_require__(1423); - const STATES = __nccwpck_require__(932); - const VALID_OPTIONS = __nccwpck_require__(481); - const Types = __nccwpck_require__(3000); - const Query = __nccwpck_require__(1615); - const Model = __nccwpck_require__(7688); - const applyPlugins = __nccwpck_require__(6990); - const driver = __nccwpck_require__(2324); - const get = __nccwpck_require__(8730); - const promiseOrCallback = __nccwpck_require__(4046); - const legacyPluralize = __nccwpck_require__(7539); - const utils = __nccwpck_require__(9232); - const pkg = __nccwpck_require__(306); - const cast = __nccwpck_require__(8874); - const removeSubdocs = __nccwpck_require__(1058); - const saveSubdocs = __nccwpck_require__(7277); - const trackTransaction = __nccwpck_require__(8675); - const validateBeforeSave = __nccwpck_require__(1752); - - const Aggregate = __nccwpck_require__(4336); - const PromiseProvider = __nccwpck_require__(5176); - const shardingPlugin = __nccwpck_require__(94); - - const defaultMongooseSymbol = Symbol.for("mongoose:default"); - - __nccwpck_require__(2312); - - /** - * Mongoose constructor. - * - * The exports object of the `mongoose` module is an instance of this class. - * Most apps will only use this one instance. - * - * ####Example: - * const mongoose = require('mongoose'); - * mongoose instanceof mongoose.Mongoose; // true - * - * // Create a new Mongoose instance with its own `connect()`, `set()`, `model()`, etc. - * const m = new mongoose.Mongoose(); - * - * @api public - * @param {Object} options see [`Mongoose#set()` docs](/docs/api/mongoose.html#mongoose_Mongoose-set) - */ - function Mongoose(options) { - this.connections = []; - this.models = {}; - this.modelSchemas = {}; - this.events = new EventEmitter(); - // default global options - this.options = Object.assign( - { - pluralization: true, - autoIndex: true, - useCreateIndex: false, - }, - options - ); - const conn = this.createConnection(); // default connection - conn.models = this.models; +Model.deleteOne = function deleteOne(conditions, options, callback) { + _checkContext(this, 'deleteOne'); - if (this.options.pluralization) { - this._pluralize = legacyPluralize; - } + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + options = null; + } + else if (typeof options === 'function') { + callback = options; + options = null; + } - // If a user creates their own Mongoose instance, give them a separate copy - // of the `Schema` constructor so they get separate custom types. (gh-6933) - if (!options || !options[defaultMongooseSymbol]) { - const _this = this; - this.Schema = function () { - this.base = _this; - return Schema.apply(this, arguments); - }; - this.Schema.prototype = Object.create(Schema.prototype); + const mq = new this.Query({}, {}, this, this.$__collection); + mq.setOptions(options); - Object.assign(this.Schema, Schema); - this.Schema.base = this; - this.Schema.Types = Object.assign({}, Schema.Types); - } else { - // Hack to work around babel's strange behavior with - // `import mongoose, { Schema } from 'mongoose'`. Because `Schema` is not - // an own property of a Mongoose global, Schema will be undefined. See gh-5648 - for (const key of ["Schema", "model"]) { - this[key] = Mongoose.prototype[key]; - } - } - this.Schema.prototype.base = this; - - Object.defineProperty(this, "plugins", { - configurable: false, - enumerable: true, - writable: false, - value: [ - [saveSubdocs, { deduplicate: true }], - [validateBeforeSave, { deduplicate: true }], - [shardingPlugin, { deduplicate: true }], - [removeSubdocs, { deduplicate: true }], - [trackTransaction, { deduplicate: true }], - ], - }); - } - Mongoose.prototype.cast = cast; - /** - * Expose connection states for user-land - * - * @memberOf Mongoose - * @property STATES - * @api public - */ - Mongoose.prototype.STATES = STATES; - - /** - * Object with `get()` and `set()` containing the underlying driver this Mongoose instance - * uses to communicate with the database. A driver is a Mongoose-specific interface that defines functions - * like `find()`. - * - * @memberOf Mongoose - * @property driver - * @api public - */ - - Mongoose.prototype.driver = driver; - - /** - * Sets mongoose options - * - * ####Example: - * - * mongoose.set('test', value) // sets the 'test' option to `value` - * - * mongoose.set('debug', true) // enable logging collection methods + arguments to the console/file - * - * mongoose.set('debug', function(collectionName, methodName, ...methodArgs) {}); // use custom function to log collection methods + arguments - * - * Currently supported options are: - * - 'debug': If `true`, prints the operations mongoose sends to MongoDB to the console. If a writable stream is passed, it will log to that stream, without colorization. If a callback function is passed, it will receive the collection name, the method name, then all arugments passed to the method. For example, if you wanted to replicate the default logging, you could output from the callback `Mongoose: ${collectionName}.${methodName}(${methodArgs.join(', ')})`. - * - 'returnOriginal': If `false`, changes the default `returnOriginal` option to `findOneAndUpdate()`, `findByIdAndUpdate`, and `findOneAndReplace()` to false. This is equivalent to setting the `new` option to `true` for `findOneAndX()` calls by default. Read our [`findOneAndUpdate()` tutorial](/docs/tutorials/findoneandupdate.html) for more information. - * - 'bufferCommands': enable/disable mongoose's buffering mechanism for all connections and models - * - 'useCreateIndex': false by default. Set to `true` to make Mongoose's default index build use `createIndex()` instead of `ensureIndex()` to avoid deprecation warnings from the MongoDB driver. - * - 'useFindAndModify': true by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`. - * - 'useNewUrlParser': false by default. Set to `true` to make all connections set the `useNewUrlParser` option by default - * - 'useUnifiedTopology': false by default. Set to `true` to make all connections set the `useUnifiedTopology` option by default - * - 'cloneSchemas': false by default. Set to `true` to `clone()` all schemas before compiling into a model. - * - 'applyPluginsToDiscriminators': false by default. Set to true to apply global plugins to discriminator schemas. This typically isn't necessary because plugins are applied to the base schema and discriminators copy all middleware, methods, statics, and properties from the base schema. - * - 'applyPluginsToChildSchemas': true by default. Set to false to skip applying global plugins to child schemas - * - 'objectIdGetter': true by default. Mongoose adds a getter to MongoDB ObjectId's called `_id` that returns `this` for convenience with populate. Set this to false to remove the getter. - * - 'runValidators': false by default. Set to true to enable [update validators](/docs/validation.html#update-validators) for all validators by default. - * - 'toObject': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toObject()`](/docs/api.html#document_Document-toObject) - * - 'toJSON': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toJSON()`](/docs/api.html#document_Document-toJSON), for determining how Mongoose documents get serialized by `JSON.stringify()` - * - 'strict': true by default, may be `false`, `true`, or `'throw'`. Sets the default strict mode for schemas. - * - 'strictQuery': false by default, may be `false`, `true`, or `'throw'`. Sets the default [strictQuery](/docs/guide.html#strictQuery) mode for schemas. - * - 'selectPopulatedPaths': true by default. Set to false to opt out of Mongoose adding all fields that you `populate()` to your `select()`. The schema-level option `selectPopulatedPaths` overwrites this one. - * - 'typePojoToMixed': true by default, may be `false` or `true`. Sets the default typePojoToMixed for schemas. - * - 'maxTimeMS': If set, attaches [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) to every query - * - 'autoIndex': true by default. Set to false to disable automatic index creation for all models associated with this Mongoose instance. - * - 'autoCreate': Set to `true` to make Mongoose call [`Model.createCollection()`](/docs/api/model.html#model_Model.createCollection) automatically when you create a model with `mongoose.model()` or `conn.model()`. This is useful for testing transactions, change streams, and other features that require the collection to exist. - * - 'overwriteModels': Set to `true` to default to overwriting models with the same name when calling `mongoose.model()`, as opposed to throwing an `OverwriteModelError`. - * - * @param {String} key - * @param {String|Function|Boolean} value - * @api public - */ - - Mongoose.prototype.set = function (key, value) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - if (VALID_OPTIONS.indexOf(key) === -1) - throw new Error(`\`${key}\` is an invalid option.`); - - if (arguments.length === 1) { - return _mongoose.options[key]; - } - - _mongoose.options[key] = value; - - if (key === "objectIdGetter") { - if (value) { - Object.defineProperty(mongoose.Types.ObjectId.prototype, "_id", { - enumerable: false, - configurable: true, - get: function () { - return this; - }, - }); - } else { - delete mongoose.Types.ObjectId.prototype._id; - } - } + callback = this.$handleCallbackError(callback); - return _mongoose; - }; + return mq.deleteOne(conditions, callback); +}; - /** - * Gets mongoose options - * - * ####Example: - * - * mongoose.get('test') // returns the 'test' value - * - * @param {String} key - * @method get - * @api public - */ - - Mongoose.prototype.get = Mongoose.prototype.set; - - /** - * Creates a Connection instance. - * - * Each `connection` instance maps to a single database. This method is helpful when managing multiple db connections. - * - * - * _Options passed take precedence over options included in connection strings._ - * - * ####Example: - * - * // with mongodb:// URI - * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); - * - * // and options - * const opts = { db: { native_parser: true }} - * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts); - * - * // replica sets - * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database'); - * - * // and options - * const opts = { replset: { strategy: 'ping', rs_name: 'testSet' }} - * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts); - * - * // and options - * const opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' } - * db = mongoose.createConnection('localhost', 'database', port, opts) - * - * // initialize now, connect later - * db = mongoose.createConnection(); - * db.openUri('localhost', 'database', port, [opts]); - * - * @param {String} [uri] a mongodb:// URI - * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below. - * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. - * @param {String} [options.dbName] The name of the database you want to use. If not provided, Mongoose uses the database name from connection string. - * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. - * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. - * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. - * @param {Boolean} [options.useNewUrlParser=false] False by default. Set to `true` to make all connections set the `useNewUrlParser` option by default. - * @param {Boolean} [options.useUnifiedTopology=false] False by default. Set to `true` to make all connections set the `useUnifiedTopology` option by default. - * @param {Boolean} [options.useCreateIndex=true] Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](/docs/deprecations.html#ensureindex) for automatic index builds via [`Model.init()`](/docs/api.html#model_Model.init). - * @param {Boolean} [options.useFindAndModify=true] True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`. - * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections. - * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above. - * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html). - * @param {Number} [options.poolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. By default, `poolSize` is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). - * @param {Number} [options.bufferMaxEntries] This option does nothing if `useUnifiedTopology` is set. The MongoDB driver also has its own buffering mechanism that kicks in when the driver is disconnected. Set this option to 0 and set `bufferCommands` to `false` on your schemas if you want your database operations to fail immediately when the driver is not connected, as opposed to waiting for reconnection. - * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback). - * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes. - * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0`, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both. - * @return {Connection} the created Connection object. Connections are thenable, so you can do `await mongoose.createConnection()` - * @api public - */ - - Mongoose.prototype.createConnection = function (uri, options, callback) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - const conn = new Connection(_mongoose); - if (typeof options === "function") { - callback = options; - options = null; - } - _mongoose.connections.push(conn); - _mongoose.events.emit("createConnection", conn); - - if (arguments.length > 0) { - return conn.openUri(uri, options, callback); - } - - return conn; - }; +/** + * Deletes all of the documents that match `conditions` from the collection. + * It returns an object with the property `deletedCount` containing the number of documents deleted. + * Behaves like `remove()`, but deletes all documents that match `conditions` + * regardless of the `single` option. + * + * ####Example: + * + * await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }); // returns {deletedCount: x} where x is the number of documents deleted. + * + * ####Note: + * + * This function triggers `deleteMany` query hooks. Read the + * [middleware docs](/docs/middleware.html#naming) to learn more. + * + * @param {Object} conditions + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] + * @return {Query} + * @api public + */ - /** - * Opens the default mongoose connection. - * - * ####Example: - * - * mongoose.connect('mongodb://user:pass@localhost:port/database'); - * - * // replica sets - * const uri = 'mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/mydatabase'; - * mongoose.connect(uri); - * - * // with options - * mongoose.connect(uri, options); - * - * // optional callback that gets fired when initial connection completed - * const uri = 'mongodb://nonexistent.domain:27000'; - * mongoose.connect(uri, function(error) { - * // if error is truthy, the initial connection failed. - * }) - * - * @param {String} uri(s) - * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below. - * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. - * @param {Number} [options.bufferTimeoutMS=10000] Mongoose specific option. If `bufferCommands` is true, Mongoose will throw an error after `bufferTimeoutMS` if the operation is still buffered. - * @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string. - * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. - * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. - * @param {Number} [options.poolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. By default, `poolSize` is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). - * @param {Boolean} [options.useUnifiedTopology=false] False by default. Set to `true` to opt in to the MongoDB driver's replica set and sharded cluster monitoring engine. - * @param {Number} [options.serverSelectionTimeoutMS] If `useUnifiedTopology = true`, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for `serverSelectionTimeoutMS` milliseconds before erroring out. If not set, the MongoDB driver defaults to using `30000` (30 seconds). - * @param {Number} [options.heartbeatFrequencyMS] If `useUnifiedTopology = true`, the MongoDB driver sends a heartbeat every `heartbeatFrequencyMS` to check on the status of the connection. A heartbeat is subject to `serverSelectionTimeoutMS`, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a `'disconnected'` event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits `'disconnected'`. We recommend you do **not** set this setting below 1000, too many heartbeats can lead to performance degradation. - * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. - * @param {Boolean} [options.useNewUrlParser=false] False by default. Set to `true` to opt in to the MongoDB driver's new URL parser logic. - * @param {Boolean} [options.useCreateIndex=true] Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](/docs/deprecations.html#ensureindex) for automatic index builds via [`Model.init()`](/docs/api.html#model_Model.init). - * @param {Boolean} [options.useFindAndModify=true] True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`. - * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections. - * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above. - * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html). - * @param {Number} [options.bufferMaxEntries] This option does nothing if `useUnifiedTopology` is set. The MongoDB driver also has its own buffering mechanism that kicks in when the driver is disconnected. Set this option to 0 and set `bufferCommands` to `false` on your schemas if you want your database operations to fail immediately when the driver is not connected, as opposed to waiting for reconnection. - * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback). - * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes. - * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0`, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both. - * @param {Boolean} [options.autoCreate=false] Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. - * @param {Function} [callback] - * @see Mongoose#createConnection #index_Mongoose-createConnection - * @api public - * @return {Promise} resolves to `this` if connection succeeded - */ - - Mongoose.prototype.connect = function (uri, options, callback) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - const conn = _mongoose.connection; - - return _mongoose._promiseOrCallback(callback, (cb) => { - conn.openUri(uri, options, (err) => { - if (err != null) { - return cb(err); - } - return cb(null, _mongoose); - }); - }); - }; +Model.deleteMany = function deleteMany(conditions, options, callback) { + _checkContext(this, 'deleteMany'); - /** - * Runs `.close()` on all connections in parallel. - * - * @param {Function} [callback] called after all connection close, or when first error occurred. - * @return {Promise} resolves when all connections are closed, or rejects with the first error that occurred. - * @api public - */ - - Mongoose.prototype.disconnect = function (callback) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - return _mongoose._promiseOrCallback(callback, (cb) => { - let remaining = _mongoose.connections.length; - if (remaining <= 0) { - return cb(null); - } - _mongoose.connections.forEach((conn) => { - conn.close(function (error) { - if (error) { - return cb(error); - } - if (!--remaining) { - cb(null); - } - }); - }); - }); - }; + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + options = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } - /** - * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) - * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), - * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). - * - * Calling `mongoose.startSession()` is equivalent to calling `mongoose.connection.startSession()`. - * Sessions are scoped to a connection, so calling `mongoose.startSession()` - * starts a session on the [default mongoose connection](/docs/api.html#mongoose_Mongoose-connection). - * - * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) - * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency - * @param {Function} [callback] - * @return {Promise} promise that resolves to a MongoDB driver `ClientSession` - * @api public - */ - - Mongoose.prototype.startSession = function () { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - return _mongoose.connection.startSession.apply( - _mongoose.connection, - arguments - ); - }; + const mq = new this.Query({}, {}, this, this.$__collection); + mq.setOptions(options); - /** - * Getter/setter around function for pluralizing collection names. - * - * @param {Function|null} [fn] overwrites the function used to pluralize collection names - * @return {Function|null} the current function used to pluralize collection names, defaults to the legacy function from `mongoose-legacy-pluralize`. - * @api public - */ + callback = this.$handleCallbackError(callback); - Mongoose.prototype.pluralize = function (fn) { - const _mongoose = this instanceof Mongoose ? this : mongoose; + return mq.deleteMany(conditions, callback); +}; - if (arguments.length > 0) { - _mongoose._pluralize = fn; - } - return _mongoose._pluralize; - }; +/** + * Finds documents. + * + * Mongoose casts the `filter` to match the model's schema before the command is sent. + * See our [query casting tutorial](/docs/tutorials/query_casting.html) for + * more information on how Mongoose casts `filter`. + * + * ####Examples: + * + * // find all documents + * await MyModel.find({}); + * + * // find all documents named john and at least 18 + * await MyModel.find({ name: 'john', age: { $gte: 18 } }).exec(); + * + * // executes, passing results to callback + * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {}); + * + * // executes, name LIKE john and only selecting the "name" and "friends" fields + * await MyModel.find({ name: /john/i }, 'name friends').exec(); + * + * // passing options + * await MyModel.find({ name: /john/i }, null, { skip: 10 }).exec(); + * + * @param {Object|ObjectId} filter + * @param {Object|String|Array} [projection] optional fields to return, see [`Query.prototype.select()`](http://mongoosejs.com/docs/api.html#query_Query-select) + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] + * @return {Query} + * @see field selection #query_Query-select + * @see query casting /docs/tutorials/query_casting.html + * @api public + */ - /** - * Defines a model or retrieves it. - * - * Models defined on the `mongoose` instance are available to all connection - * created by the same `mongoose` instance. - * - * If you call `mongoose.model()` with twice the same name but a different schema, - * you will get an `OverwriteModelError`. If you call `mongoose.model()` with - * the same name and same schema, you'll get the same schema back. - * - * ####Example: - * - * const mongoose = require('mongoose'); - * - * // define an Actor model with this mongoose instance - * const schema = new Schema({ name: String }); - * mongoose.model('Actor', schema); - * - * // create a new connection - * const conn = mongoose.createConnection(..); - * - * // create Actor model - * const Actor = conn.model('Actor', schema); - * conn.model('Actor') === Actor; // true - * conn.model('Actor', schema) === Actor; // true, same schema - * conn.model('Actor', schema, 'actors') === Actor; // true, same schema and collection name - * - * // This throws an `OverwriteModelError` because the schema is different. - * conn.model('Actor', new Schema({ name: String })); - * - * _When no `collection` argument is passed, Mongoose uses the model name. If you don't like this behavior, either pass a collection name, use `mongoose.pluralize()`, or set your schemas collection name option._ - * - * ####Example: - * - * const schema = new Schema({ name: String }, { collection: 'actor' }); - * - * // or - * - * schema.set('collection', 'actor'); - * - * // or - * - * const collectionName = 'actor' - * const M = mongoose.model('Actor', schema, collectionName) - * - * @param {String|Function} name model name or class extending Model - * @param {Schema} [schema] the schema to use. - * @param {String} [collection] name (optional, inferred from model name) - * @param {Boolean|Object} [skipInit] whether to skip initialization (defaults to false). If an object, treated as options. - * @return {Model} The model associated with `name`. Mongoose will create the model if it doesn't already exist. - * @api public - */ - - Mongoose.prototype.model = function (name, schema, collection, skipInit) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - let model; - if (typeof name === "function") { - model = name; - name = model.name; - if (!(model.prototype instanceof Model)) { - throw new _mongoose.Error( - "The provided class " + name + " must extend Model" - ); - } - } +Model.find = function find(conditions, projection, options, callback) { + _checkContext(this, 'find'); + + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + projection = null; + options = null; + } else if (typeof projection === 'function') { + callback = projection; + projection = null; + options = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } - if (typeof schema === "string") { - collection = schema; - schema = false; - } + const mq = new this.Query({}, {}, this, this.$__collection); + mq.select(projection); - if (utils.isObject(schema) && !(schema instanceof Schema)) { - schema = new Schema(schema); - } - if (schema && !(schema instanceof Schema)) { - throw new Error( - "The 2nd parameter to `mongoose.model()` should be a " + - "schema or a POJO" - ); - } + mq.setOptions(options); + if (this.schema.discriminatorMapping && + this.schema.discriminatorMapping.isRoot && + mq.selectedInclusively()) { + // Need to select discriminator key because original schema doesn't have it + mq.select(this.schema.options.discriminatorKey); + } - if (typeof collection === "boolean") { - skipInit = collection; - collection = null; - } + callback = this.$handleCallbackError(callback); - // handle internal options from connection.model() - let options; - if (skipInit && utils.isObject(skipInit)) { - options = skipInit; - skipInit = true; - } else { - options = {}; - } + return mq.find(conditions, callback); +}; - // look up schema for the collection. - if (!_mongoose.modelSchemas[name]) { - if (schema) { - // cache it so we only apply plugins once - _mongoose.modelSchemas[name] = schema; - } else { - throw new mongoose.Error.MissingSchemaError(name); - } - } +/** + * Finds a single document by its _id field. `findById(id)` is almost* + * equivalent to `findOne({ _id: id })`. If you want to query by a document's + * `_id`, use `findById()` instead of `findOne()`. + * + * The `id` is cast based on the Schema before sending the command. + * + * This function triggers the following middleware. + * + * - `findOne()` + * + * \* Except for how it treats `undefined`. If you use `findOne()`, you'll see + * that `findOne(undefined)` and `findOne({ _id: undefined })` are equivalent + * to `findOne({})` and return arbitrary documents. However, mongoose + * translates `findById(undefined)` into `findOne({ _id: null })`. + * + * ####Example: + * + * // Find the adventure with the given `id`, or `null` if not found + * await Adventure.findById(id).exec(); + * + * // using callback + * Adventure.findById(id, function (err, adventure) {}); + * + * // select only the adventures name and length + * await Adventure.findById(id, 'name length').exec(); + * + * @param {Any} id value of `_id` to query by + * @param {Object|String|Array} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] + * @return {Query} + * @see field selection #query_Query-select + * @see lean queries /docs/tutorials/lean.html + * @see findById in Mongoose https://masteringjs.io/tutorials/mongoose/find-by-id + * @api public + */ - const originalSchema = schema; - if (schema) { - if (_mongoose.get("cloneSchemas")) { - schema = schema.clone(); - } - _mongoose._applyPlugins(schema); - } +Model.findById = function findById(id, projection, options, callback) { + _checkContext(this, 'findById'); - let sub; + if (typeof id === 'undefined') { + id = null; + } - // connection.model() may be passing a different schema for - // an existing model name. in this case don't read from cache. - const overwriteModels = _mongoose.options.hasOwnProperty( - "overwriteModels" - ) - ? _mongoose.options.overwriteModels - : options.overwriteModels; - if ( - _mongoose.models[name] && - options.cache !== false && - overwriteModels !== true - ) { - if ( - originalSchema && - originalSchema.instanceOfSchema && - originalSchema !== _mongoose.models[name].schema - ) { - throw new _mongoose.Error.OverwriteModelError(name); - } + callback = this.$handleCallbackError(callback); - if ( - collection && - collection !== _mongoose.models[name].collection.name - ) { - // subclass current model with alternate collection - model = _mongoose.models[name]; - schema = model.prototype.schema; - sub = model.__subclass(_mongoose.connection, schema, collection); - // do not cache the sub model - return sub; - } + return this.findOne({ _id: id }, projection, options, callback); +}; - return _mongoose.models[name]; - } +/** + * Finds one document. + * + * The `conditions` are cast to their respective SchemaTypes before the command is sent. + * + * *Note:* `conditions` is optional, and if `conditions` is null or undefined, + * mongoose will send an empty `findOne` command to MongoDB, which will return + * an arbitrary document. If you're querying by `_id`, use `findById()` instead. + * + * ####Example: + * + * // Find one adventure whose `country` is 'Croatia', otherwise `null` + * await Adventure.findOne({ country: 'Croatia' }).exec(); + * + * // using callback + * Adventure.findOne({ country: 'Croatia' }, function (err, adventure) {}); + * + * // select only the adventures name and length + * await Adventure.findOne({ country: 'Croatia' }, 'name length').exec(); + * + * @param {Object} [conditions] + * @param {Object|String|Array} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] + * @return {Query} + * @see field selection #query_Query-select + * @see lean queries /docs/tutorials/lean.html + * @api public + */ - // ensure a schema exists - if (!schema) { - schema = this.modelSchemas[name]; - if (!schema) { - throw new mongoose.Error.MissingSchemaError(name); - } - } +Model.findOne = function findOne(conditions, projection, options, callback) { + _checkContext(this, 'findOne'); + if (typeof options === 'function') { + callback = options; + options = null; + } else if (typeof projection === 'function') { + callback = projection; + projection = null; + options = null; + } else if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + projection = null; + options = null; + } - // Apply relevant "global" options to the schema - if (!("pluralization" in schema.options)) { - schema.options.pluralization = _mongoose.options.pluralization; - } + const mq = new this.Query({}, {}, this, this.$__collection); + mq.select(projection); + mq.setOptions(options); + if (this.schema.discriminatorMapping && + this.schema.discriminatorMapping.isRoot && + mq.selectedInclusively()) { + mq.select(this.schema.options.discriminatorKey); + } - if (!collection) { - collection = - schema.get("collection") || - utils.toCollectionName(name, _mongoose.pluralize()); - } + callback = this.$handleCallbackError(callback); + return mq.findOne(conditions, callback); +}; - const connection = options.connection || _mongoose.connection; - model = _mongoose.Model.compile( - model || name, - schema, - collection, - connection, - _mongoose - ); +/** + * Estimates the number of documents in the MongoDB collection. Faster than + * using `countDocuments()` for large collections because + * `estimatedDocumentCount()` uses collection metadata rather than scanning + * the entire collection. + * + * ####Example: + * + * const numAdventures = await Adventure.estimatedDocumentCount(); + * + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} + * @api public + */ - if (!skipInit) { - // Errors handled internally, so safe to ignore error - model.init(function $modelInitNoop() {}); - } +Model.estimatedDocumentCount = function estimatedDocumentCount(options, callback) { + _checkContext(this, 'estimatedDocumentCount'); - connection.emit("model", model); + const mq = new this.Query({}, {}, this, this.$__collection); - if (options.cache === false) { - return model; - } + callback = this.$handleCallbackError(callback); - _mongoose.models[name] = model; - return _mongoose.models[name]; - }; + return mq.estimatedDocumentCount(options, callback); +}; - /** - * Removes the model named `name` from the default connection, if it exists. - * You can use this function to clean up any models you created in your tests to - * prevent OverwriteModelErrors. - * - * Equivalent to `mongoose.connection.deleteModel(name)`. - * - * ####Example: - * - * mongoose.model('User', new Schema({ name: String })); - * console.log(mongoose.model('User')); // Model object - * mongoose.deleteModel('User'); - * console.log(mongoose.model('User')); // undefined - * - * // Usually useful in a Mocha `afterEach()` hook - * afterEach(function() { - * mongoose.deleteModel(/.+/); // Delete every model - * }); - * - * @api public - * @param {String|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. - * @return {Mongoose} this - */ - - Mongoose.prototype.deleteModel = function (name) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - _mongoose.connection.deleteModel(name); - return _mongoose; - }; +/** + * Counts number of documents matching `filter` in a database collection. + * + * ####Example: + * + * Adventure.countDocuments({ type: 'jungle' }, function (err, count) { + * console.log('there are %d jungle adventures', count); + * }); + * + * If you want to count all documents in a large collection, + * use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount) + * instead. If you call `countDocuments({})`, MongoDB will always execute + * a full collection scan and **not** use any indexes. + * + * The `countDocuments()` function is similar to `count()`, but there are a + * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). + * Below are the operators that `count()` supports but `countDocuments()` does not, + * and the suggested replacement: + * + * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/) + * - `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center) + * - `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere) + * + * @param {Object} filter + * @param {Function} [callback] + * @return {Query} + * @api public + */ - /** - * Returns an array of model names created on this instance of Mongoose. - * - * ####Note: - * - * _Does not include names of models created using `connection.model()`._ - * - * @api public - * @return {Array} - */ - - Mongoose.prototype.modelNames = function () { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - const names = Object.keys(_mongoose.models); - return names; - }; +Model.countDocuments = function countDocuments(conditions, options, callback) { + _checkContext(this, 'countDocuments'); - /** - * Applies global plugins to `schema`. - * - * @param {Schema} schema - * @api private - */ + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } + if (typeof options === 'function') { + callback = options; + options = null; + } - Mongoose.prototype._applyPlugins = function (schema, options) { - const _mongoose = this instanceof Mongoose ? this : mongoose; + const mq = new this.Query({}, {}, this, this.$__collection); + if (options != null) { + mq.setOptions(options); + } - options = options || {}; - options.applyPluginsToDiscriminators = get( - _mongoose, - "options.applyPluginsToDiscriminators", - false - ); - options.applyPluginsToChildSchemas = get( - _mongoose, - "options.applyPluginsToChildSchemas", - true - ); - applyPlugins( - schema, - _mongoose.plugins, - options, - "$globalPluginsApplied" - ); - }; + callback = this.$handleCallbackError(callback); - /** - * Declares a global plugin executed on all Schemas. - * - * Equivalent to calling `.plugin(fn)` on each Schema you create. - * - * @param {Function} fn plugin callback - * @param {Object} [opts] optional options - * @return {Mongoose} this - * @see plugins ./plugins.html - * @api public - */ - - Mongoose.prototype.plugin = function (fn, opts) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - _mongoose.plugins.push([fn, opts]); - return _mongoose; - }; + return mq.countDocuments(conditions, callback); +}; - /** - * The Mongoose module's default connection. Equivalent to `mongoose.connections[0]`, see [`connections`](#mongoose_Mongoose-connections). - * - * ####Example: - * - * const mongoose = require('mongoose'); - * mongoose.connect(...); - * mongoose.connection.on('error', cb); - * - * This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model). - * - * To create a new connection, use [`createConnection()`](#mongoose_Mongoose-createConnection). - * - * @memberOf Mongoose - * @instance - * @property {Connection} connection - * @api public - */ - - Mongoose.prototype.__defineGetter__("connection", function () { - return this.connections[0]; - }); +/** + * Counts number of documents that match `filter` in a database collection. + * + * This method is deprecated. If you want to count the number of documents in + * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount) + * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#model_Model.countDocuments) function instead. + * + * ####Example: + * + * const count = await Adventure.count({ type: 'jungle' }); + * console.log('there are %d jungle adventures', count); + * + * @deprecated + * @param {Object} filter + * @param {Function} [callback] + * @return {Query} + * @api public + */ - Mongoose.prototype.__defineSetter__("connection", function (v) { - if (v instanceof Connection) { - this.connections[0] = v; - this.models = v.models; - } - }); +Model.count = function count(conditions, callback) { + _checkContext(this, 'count'); - /** - * An array containing all [connections](connections.html) associated with this - * Mongoose instance. By default, there is 1 connection. Calling - * [`createConnection()`](#mongoose_Mongoose-createConnection) adds a connection - * to this array. - * - * ####Example: - * - * const mongoose = require('mongoose'); - * mongoose.connections.length; // 1, just the default connection - * mongoose.connections[0] === mongoose.connection; // true - * - * mongoose.createConnection('mongodb://localhost:27017/test'); - * mongoose.connections.length; // 2 - * - * @memberOf Mongoose - * @instance - * @property {Array} connections - * @api public - */ - - Mongoose.prototype.connections; - - /*! - * Connection - */ - - const Connection = driver.get().getConnection(); - - /*! - * Collection - */ - - const Collection = driver.get().Collection; - - /** - * The Mongoose Aggregate constructor - * - * @method Aggregate - * @api public - */ - - Mongoose.prototype.Aggregate = Aggregate; - - /** - * The Mongoose Collection constructor - * - * @method Collection - * @api public - */ - - Mongoose.prototype.Collection = Collection; - - /** - * The Mongoose [Connection](#connection_Connection) constructor - * - * @memberOf Mongoose - * @instance - * @method Connection - * @api public - */ - - Mongoose.prototype.Connection = Connection; - - /** - * The Mongoose version - * - * #### Example - * - * console.log(mongoose.version); // '5.x.x' - * - * @property version - * @api public - */ - - Mongoose.prototype.version = pkg.version; - - /** - * The Mongoose constructor - * - * The exports of the mongoose module is an instance of this class. - * - * ####Example: - * - * const mongoose = require('mongoose'); - * const mongoose2 = new mongoose.Mongoose(); - * - * @method Mongoose - * @api public - */ - - Mongoose.prototype.Mongoose = Mongoose; - - /** - * The Mongoose [Schema](#schema_Schema) constructor - * - * ####Example: - * - * const mongoose = require('mongoose'); - * const Schema = mongoose.Schema; - * const CatSchema = new Schema(..); - * - * @method Schema - * @api public - */ - - Mongoose.prototype.Schema = Schema; - - /** - * The Mongoose [SchemaType](#schematype_SchemaType) constructor - * - * @method SchemaType - * @api public - */ - - Mongoose.prototype.SchemaType = SchemaType; - - /** - * The various Mongoose SchemaTypes. - * - * ####Note: - * - * _Alias of mongoose.Schema.Types for backwards compatibility._ - * - * @property SchemaTypes - * @see Schema.SchemaTypes #schema_Schema.Types - * @api public - */ - - Mongoose.prototype.SchemaTypes = Schema.Types; - - /** - * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor - * - * @method VirtualType - * @api public - */ - - Mongoose.prototype.VirtualType = VirtualType; - - /** - * The various Mongoose Types. - * - * ####Example: - * - * const mongoose = require('mongoose'); - * const array = mongoose.Types.Array; - * - * ####Types: - * - * - [Array](/docs/schematypes.html#arrays) - * - [Buffer](/docs/schematypes.html#buffers) - * - [Embedded](/docs/schematypes.html#schemas) - * - [DocumentArray](/docs/api/documentarraypath.html) - * - [Decimal128](/docs/api.html#mongoose_Mongoose-Decimal128) - * - [ObjectId](/docs/schematypes.html#objectids) - * - [Map](/docs/schematypes.html#maps) - * - [Subdocument](/docs/schematypes.html#schemas) - * - * Using this exposed access to the `ObjectId` type, we can construct ids on demand. - * - * const ObjectId = mongoose.Types.ObjectId; - * const id1 = new ObjectId; - * - * @property Types - * @api public - */ - - Mongoose.prototype.Types = Types; - - /** - * The Mongoose [Query](#query_Query) constructor. - * - * @method Query - * @api public - */ - - Mongoose.prototype.Query = Query; - - /** - * The Mongoose [Promise](#promise_Promise) constructor. - * - * @memberOf Mongoose - * @instance - * @property Promise - * @api public - */ - - Object.defineProperty(Mongoose.prototype, "Promise", { - get: function () { - return PromiseProvider.get(); - }, - set: function (lib) { - PromiseProvider.set(lib); - }, - }); + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } - /** - * Storage layer for mongoose promises - * - * @method PromiseProvider - * @api public - */ - - Mongoose.prototype.PromiseProvider = PromiseProvider; - - /** - * The Mongoose [Model](#model_Model) constructor. - * - * @method Model - * @api public - */ - - Mongoose.prototype.Model = Model; - - /** - * The Mongoose [Document](/api/document.html) constructor. - * - * @method Document - * @api public - */ - - Mongoose.prototype.Document = Document; - - /** - * The Mongoose DocumentProvider constructor. Mongoose users should not have to - * use this directly - * - * @method DocumentProvider - * @api public - */ - - Mongoose.prototype.DocumentProvider = __nccwpck_require__(1860); - - /** - * The Mongoose ObjectId [SchemaType](/docs/schematypes.html). Used for - * declaring paths in your schema that should be - * [MongoDB ObjectIds](https://docs.mongodb.com/manual/reference/method/ObjectId/). - * Do not use this to create a new ObjectId instance, use `mongoose.Types.ObjectId` - * instead. - * - * ####Example: - * - * const childSchema = new Schema({ parentId: mongoose.ObjectId }); - * - * @property ObjectId - * @api public - */ - - Mongoose.prototype.ObjectId = SchemaTypes.ObjectId; - - /** - * Returns true if Mongoose can cast the given value to an ObjectId, or - * false otherwise. - * - * ####Example: - * - * mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true - * mongoose.isValidObjectId('0123456789ab'); // true - * mongoose.isValidObjectId(6); // false - * - * @method isValidObjectId - * @api public - */ - - Mongoose.prototype.isValidObjectId = function (v) { - if (v == null) { - return true; - } - const base = this || mongoose; - const ObjectId = base.driver.get().ObjectId; - if (v instanceof ObjectId) { - return true; - } - - if (v._id != null) { - if (v._id instanceof ObjectId) { - return true; - } - if (v._id.toString instanceof Function) { - v = v._id.toString(); - if (typeof v === "string" && v.length === 12) { - return true; - } - if ( - typeof v === "string" && - v.length === 24 && - /^[a-f0-9]*$/.test(v) - ) { - return true; - } - return false; - } - } + const mq = new this.Query({}, {}, this, this.$__collection); - if (v.toString instanceof Function) { - v = v.toString(); - } + callback = this.$handleCallbackError(callback); - if (typeof v === "string" && v.length === 12) { - return true; - } - if (typeof v === "string" && v.length === 24 && /^[a-f0-9]*$/.test(v)) { - return true; - } + return mq.count(conditions, callback); +}; - return false; - }; +/** + * Creates a Query for a `distinct` operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) { + * if (err) return handleError(err); + * + * assert(Array.isArray(result)); + * console.log('unique urls with more than 100 clicks', result); + * }) + * + * const query = Link.distinct('url'); + * query.exec(callback); + * + * @param {String} field + * @param {Object} [conditions] optional + * @param {Function} [callback] + * @return {Query} + * @api public + */ - /** - * The Mongoose Decimal128 [SchemaType](/docs/schematypes.html). Used for - * declaring paths in your schema that should be - * [128-bit decimal floating points](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html). - * Do not use this to create a new Decimal128 instance, use `mongoose.Types.Decimal128` - * instead. - * - * ####Example: - * - * const vehicleSchema = new Schema({ fuelLevel: mongoose.Decimal128 }); - * - * @property Decimal128 - * @api public - */ - - Mongoose.prototype.Decimal128 = SchemaTypes.Decimal128; - - /** - * The Mongoose Mixed [SchemaType](/docs/schematypes.html). Used for - * declaring paths in your schema that Mongoose's change tracking, casting, - * and validation should ignore. - * - * ####Example: - * - * const schema = new Schema({ arbitrary: mongoose.Mixed }); - * - * @property Mixed - * @api public - */ - - Mongoose.prototype.Mixed = SchemaTypes.Mixed; - - /** - * The Mongoose Date [SchemaType](/docs/schematypes.html). - * - * ####Example: - * - * const schema = new Schema({ test: Date }); - * schema.path('test') instanceof mongoose.Date; // true - * - * @property Date - * @api public - */ - - Mongoose.prototype.Date = SchemaTypes.Date; - - /** - * The Mongoose Number [SchemaType](/docs/schematypes.html). Used for - * declaring paths in your schema that Mongoose should cast to numbers. - * - * ####Example: - * - * const schema = new Schema({ num: mongoose.Number }); - * // Equivalent to: - * const schema = new Schema({ num: 'number' }); - * - * @property Number - * @api public - */ - - Mongoose.prototype.Number = SchemaTypes.Number; - - /** - * The [MongooseError](#error_MongooseError) constructor. - * - * @method Error - * @api public - */ - - Mongoose.prototype.Error = __nccwpck_require__(4327); - - /** - * Mongoose uses this function to get the current time when setting - * [timestamps](/docs/guide.html#timestamps). You may stub out this function - * using a tool like [Sinon](https://www.npmjs.com/package/sinon) for testing. - * - * @method now - * @returns Date the current time - * @api public - */ - - Mongoose.prototype.now = function now() { - return new Date(); - }; +Model.distinct = function distinct(field, conditions, callback) { + _checkContext(this, 'distinct'); - /** - * The Mongoose CastError constructor - * - * @method CastError - * @param {String} type The name of the type - * @param {Any} value The value that failed to cast - * @param {String} path The path `a.b.c` in the doc where this cast error occurred - * @param {Error} [reason] The original error that was thrown - * @api public - */ - - Mongoose.prototype.CastError = __nccwpck_require__(2798); - - /** - * The constructor used for schematype options - * - * @method SchemaTypeOptions - * @api public - */ - - Mongoose.prototype.SchemaTypeOptions = __nccwpck_require__(7544); - - /** - * The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses. - * - * @property mongo - * @api public - */ - - Mongoose.prototype.mongo = __nccwpck_require__(5517); - - /** - * The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses. - * - * @property mquery - * @api public - */ - - Mongoose.prototype.mquery = __nccwpck_require__(3821); - - /*! - * ignore - */ - - Mongoose.prototype._promiseOrCallback = function (callback, fn, ee) { - return promiseOrCallback(callback, fn, ee, this.Promise); - }; + const mq = new this.Query({}, {}, this, this.$__collection); - /*! - * The exports object is an instance of Mongoose. - * - * @api public - */ - - const mongoose = - (module.exports = - exports = - new Mongoose({ - [defaultMongooseSymbol]: true, - })); + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } + callback = this.$handleCallbackError(callback); - /***/ - }, + return mq.distinct(field, conditions, callback); +}; - /***/ 5963: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; - /*! - * Dependencies - */ - - const StateMachine = __nccwpck_require__(3532); - const ActiveRoster = StateMachine.ctor( - "require", - "modify", - "init", - "default", - "ignore" - ); +/** + * Creates a Query, applies the passed conditions, and returns the Query. + * + * For example, instead of writing: + * + * User.find({age: {$gte: 21, $lte: 65}}, callback); + * + * we can instead write: + * + * User.where('age').gte(21).lte(65).exec(callback); + * + * Since the Query class also supports `where` you can continue chaining + * + * User + * .where('age').gte(21).lte(65) + * .where('name', /^b/i) + * ... etc + * + * @param {String} path + * @param {Object} [val] optional value + * @return {Query} + * @api public + */ - module.exports = exports = InternalCache; - - function InternalCache() { - this.strictMode = undefined; - this.selected = undefined; - this.shardval = undefined; - this.saveError = undefined; - this.validationError = undefined; - this.adhocPaths = undefined; - this.removing = undefined; - this.inserting = undefined; - this.saving = undefined; - this.version = undefined; - this.getters = {}; - this._id = undefined; - this.populate = undefined; // what we want to populate in this doc - this.populated = undefined; // the _ids that have been populated - this.wasPopulated = false; // if this doc was the result of a population - this.scope = undefined; - this.activePaths = new ActiveRoster(); - this.pathsToScopes = {}; - this.cachedRequired = {}; - this.session = null; - this.$setCalled = new Set(); - - // embedded docs - this.ownerDocument = undefined; - this.fullPath = undefined; - } - - /***/ - }, +Model.where = function where(path, val) { + _checkContext(this, 'where'); - /***/ 7688: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const Aggregate = __nccwpck_require__(4336); - const ChangeStream = __nccwpck_require__(1662); - const Document = __nccwpck_require__(6717); - const DocumentNotFoundError = __nccwpck_require__(5147); - const DivergentArrayError = __nccwpck_require__(8912); - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const MongooseBuffer = __nccwpck_require__(5505); - const MongooseError = __nccwpck_require__(4327); - const OverwriteModelError = __nccwpck_require__(970); - const PromiseProvider = __nccwpck_require__(5176); - const Query = __nccwpck_require__(1615); - const RemoveOptions = __nccwpck_require__(2258); - const SaveOptions = __nccwpck_require__(8792); - const Schema = __nccwpck_require__(7606); - const ServerSelectionError = __nccwpck_require__(3070); - const ValidationError = __nccwpck_require__(8460); - const VersionError = __nccwpck_require__(4305); - const ParallelSaveError = __nccwpck_require__(618); - const applyQueryMiddleware = __nccwpck_require__(7378); - const applyHooks = __nccwpck_require__(5373); - const applyMethods = __nccwpck_require__(3543); - const applyStaticHooks = __nccwpck_require__(3739); - const applyStatics = __nccwpck_require__(5220); - const applyWriteConcern = __nccwpck_require__(5661); - const assignVals = __nccwpck_require__(6414); - const castBulkWrite = __nccwpck_require__(4531); - const createPopulateQueryFilter = __nccwpck_require__(5138); - const getDefaultBulkwriteResult = __nccwpck_require__(3039); - const discriminator = __nccwpck_require__(1462); - const each = __nccwpck_require__(9965); - const get = __nccwpck_require__(8730); - const getConstructorName = __nccwpck_require__(7323); - const getDiscriminatorByValue = __nccwpck_require__(8689); - const getModelsMapForPopulate = __nccwpck_require__(1684); - const immediate = __nccwpck_require__(4830); - const internalToObjectOptions = - __nccwpck_require__(5684) /* .internalToObjectOptions */.h; - const isDefaultIdIndex = __nccwpck_require__(7720); - const isIndexEqual = __nccwpck_require__(4749); - const isPathSelectedInclusive = __nccwpck_require__(2000); - const leanPopulateMap = __nccwpck_require__(914); - const modifiedPaths = __nccwpck_require__(587); - const parallelLimit = __nccwpck_require__(7716); - const removeDeselectedForeignField = __nccwpck_require__(6962); - const util = __nccwpck_require__(1669); - const utils = __nccwpck_require__(9232); - - const VERSION_WHERE = 1; - const VERSION_INC = 2; - const VERSION_ALL = VERSION_WHERE | VERSION_INC; - - const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; - const modelCollectionSymbol = Symbol("mongoose#Model#collection"); - const modelDbSymbol = Symbol("mongoose#Model#db"); - const modelSymbol = __nccwpck_require__(3240).modelSymbol; - const subclassedSymbol = Symbol("mongoose#Model#subclassed"); - - const saveToObjectOptions = Object.assign({}, internalToObjectOptions, { - bson: true, - }); + void val; // eslint + const mq = new this.Query({}, {}, this, this.$__collection).find({}); + return mq.where.apply(mq, arguments); +}; - /** - * A Model is a class that's your primary tool for interacting with MongoDB. - * An instance of a Model is called a [Document](./api.html#Document). - * - * In Mongoose, the term "Model" refers to subclasses of the `mongoose.Model` - * class. You should not use the `mongoose.Model` class directly. The - * [`mongoose.model()`](./api.html#mongoose_Mongoose-model) and - * [`connection.model()`](./api.html#connection_Connection-model) functions - * create subclasses of `mongoose.Model` as shown below. - * - * ####Example: - * - * // `UserModel` is a "Model", a subclass of `mongoose.Model`. - * const UserModel = mongoose.model('User', new Schema({ name: String })); - * - * // You can use a Model to create new documents using `new`: - * const userDoc = new UserModel({ name: 'Foo' }); - * await userDoc.save(); - * - * // You also use a model to create queries: - * const userFromDb = await UserModel.findOne({ name: 'Foo' }); - * - * @param {Object} doc values for initial set - * @param [fields] optional object containing the fields that were selected in the query which returned this document. You do **not** need to set this parameter to ensure Mongoose handles your [query projection](./api.html#query_Query-select). - * @param {Boolean} [skipId=false] optional boolean. If true, mongoose doesn't add an `_id` field to the document. - * @inherits Document http://mongoosejs.com/docs/api/document.html - * @event `error`: If listening to this event, 'error' is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model. - * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event. - * @event `index-single-start`: Emitted when an individual index starts within `Model#ensureIndexes`. The fields and options being used to build the index are also passed with the event. - * @event `index-single-done`: Emitted when an individual index finishes within `Model#ensureIndexes`. If an error occurred it is passed with the event. The fields, options, and index name are also passed. - * @api public - */ - - function Model(doc, fields, skipId) { - if (fields instanceof Schema) { - throw new TypeError( - "2nd argument to `Model` must be a POJO or string, " + - "**not** a schema. Make sure you're calling `mongoose.model()`, not " + - "`mongoose.Model()`." - ); - } - Document.call(this, doc, fields, skipId); - } - - /*! - * Inherits from Document. - * - * All Model.prototype features are available on - * top level (non-sub) documents. - */ - - Model.prototype.__proto__ = Document.prototype; - Model.prototype.$isMongooseModelPrototype = true; - - /** - * Connection the model uses. - * - * @api public - * @property db - * @memberOf Model - * @instance - */ - - Model.prototype.db; - - /** - * Collection the model uses. - * - * This property is read-only. Modifying this property is a no-op. - * - * @api public - * @property collection - * @memberOf Model - * @instance - */ - - Model.prototype.collection; - - /** - * Internal collection the model uses. - * - * This property is read-only. Modifying this property is a no-op. - * - * @api private - * @property collection - * @memberOf Model - * @instance - */ - - Model.prototype.$__collection; - - /** - * The name of the model - * - * @api public - * @property modelName - * @memberOf Model - * @instance - */ - - Model.prototype.modelName; - - /** - * Additional properties to attach to the query when calling `save()` and - * `isNew` is false. - * - * @api public - * @property $where - * @memberOf Model - * @instance - */ - - Model.prototype.$where; - - /** - * If this is a discriminator model, `baseModelName` is the name of - * the base model. - * - * @api public - * @property baseModelName - * @memberOf Model - * @instance - */ - - Model.prototype.baseModelName; - - /** - * Event emitter that reports any errors that occurred. Useful for global error - * handling. - * - * ####Example: - * - * MyModel.events.on('error', err => console.log(err.message)); - * - * // Prints a 'CastError' because of the above handler - * await MyModel.findOne({ _id: 'notanid' }).catch(noop); - * - * @api public - * @fires error whenever any query or model function errors - * @memberOf Model - * @static events - */ - - Model.events; - - /*! - * Compiled middleware for this model. Set in `applyHooks()`. - * - * @api private - * @property _middleware - * @memberOf Model - * @static - */ - - Model._middleware; - - /*! - * ignore - */ - - function _applyCustomWhere(doc, where) { - if (doc.$where == null) { - return; - } - for (const key of Object.keys(doc.$where)) { - where[key] = doc.$where[key]; - } - } +/** + * Creates a `Query` and specifies a `$where` condition. + * + * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model. + * + * Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {}); + * + * @param {String|Function} argument is a javascript string or anonymous function + * @method $where + * @memberOf Model + * @return {Query} + * @see Query.$where #query_Query-%24where + * @api public + */ - /*! - * ignore - */ +Model.$where = function $where() { + _checkContext(this, '$where'); - Model.prototype.$__handleSave = function (options, callback) { - const _this = this; - let saveOptions = {}; + const mq = new this.Query({}, {}, this, this.$__collection).find({}); + return mq.$where.apply(mq, arguments); +}; - if ("safe" in options) { - _handleSafe(options); - } +/** + * Issues a mongodb findAndModify update command. + * + * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes if `callback` is passed else a Query object is returned. + * + * ####Options: + * + * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `overwrite`: bool - if true, replace the entire document. + * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()` + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. + * - `setDefaultsOnInsert`: `true` by default. If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. + * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update + * + * ####Examples: + * + * A.findOneAndUpdate(conditions, update, options, callback) // executes + * A.findOneAndUpdate(conditions, update, options) // returns Query + * A.findOneAndUpdate(conditions, update, callback) // executes + * A.findOneAndUpdate(conditions, update) // returns Query + * A.findOneAndUpdate() // returns Query + * + * ####Note: + * + * All top level update keys which are not `atomic` operation names are treated as set operations: + * + * ####Example: + * + * const query = { name: 'borne' }; + * Model.findOneAndUpdate(query, { name: 'jason bourne' }, options, callback) + * + * // is sent as + * Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback) + * + * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`. + * + * ####Note: + * + * `findOneAndX` and `findByIdAndX` functions support limited validation that + * you can enable by setting the `runValidators` option. + * + * If you need full-fledged validation, use the traditional approach of first + * retrieving the document. + * + * const doc = await Model.findById(id); + * doc.name = 'jason bourne'; + * await doc.save(); + * + * @param {Object} [conditions] + * @param {Object} [update] + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {String} [options.returnDocument='before'] Has two possible values, `'before'` and `'after'`. By default, it will return the document before the update was applied. + * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `update`, Mongoose will wrap `update` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. An alternative to this would be using [Model.findOneAndReplace(conditions, update, options, callback)](https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndReplace). + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object|String|Array} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) + * @param {Function} [callback] + * @return {Query} + * @see Tutorial /docs/tutorials/findoneandupdate.html + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ - applyWriteConcern(this.$__schema, options); - if (typeof options.writeConcern != "undefined") { - saveOptions.writeConcern = {}; - if ("w" in options.writeConcern) { - saveOptions.writeConcern.w = options.writeConcern.w; - } - if ("j" in options.writeConcern) { - saveOptions.writeConcern.j = options.writeConcern.j; - } - if ("wtimeout" in options.writeConcern) { - saveOptions.writeConcern.wtimeout = options.writeConcern.wtimeout; - } - } else { - if ("w" in options) { - saveOptions.w = options.w; - } - if ("j" in options) { - saveOptions.j = options.j; - } - if ("wtimeout" in options) { - saveOptions.wtimeout = options.wtimeout; - } - } - if ("checkKeys" in options) { - saveOptions.checkKeys = options.checkKeys; - } - const session = this.$session(); - if (!saveOptions.hasOwnProperty("session")) { - saveOptions.session = session; - } - - if (Object.keys(saveOptions).length === 0) { - saveOptions = null; - } - if (this.isNew) { - // send entire doc - const obj = this.toObject(saveToObjectOptions); - if ((obj || {})._id === void 0) { - // documents must have an _id else mongoose won't know - // what to update later if more changes are made. the user - // wouldn't know what _id was generated by mongodb either - // nor would the ObjectId generated by mongodb necessarily - // match the schema definition. - immediate(function () { - callback( - new MongooseError("document must have an _id before saving") - ); - }); - return; - } +Model.findOneAndUpdate = function(conditions, update, options, callback) { + _checkContext(this, 'findOneAndUpdate'); + + if (typeof options === 'function') { + callback = options; + options = null; + } else if (arguments.length === 1) { + if (typeof conditions === 'function') { + const msg = 'Model.findOneAndUpdate(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\n' + + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\n' + + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)\n' + + ' ' + this.modelName + '.findOneAndUpdate(update)\n' + + ' ' + this.modelName + '.findOneAndUpdate()\n'; + throw new TypeError(msg); + } + update = conditions; + conditions = undefined; + } + callback = this.$handleCallbackError(callback); - this.$__version(true, obj); - this[modelCollectionSymbol].insertOne( - obj, - saveOptions, - function (err, ret) { - if (err) { - _setIsNew(_this, true); + let fields; + if (options) { + fields = options.fields || options.projection; + } - callback(err, null); - return; - } + update = utils.clone(update, { + depopulate: true, + _isNested: true + }); - callback(null, ret); - } - ); - this.$__reset(); - _setIsNew(this, false); - // Make it possible to retry the insert - this.$__.inserting = true; - } else { - // Make sure we don't treat it as a new object on error, - // since it already exists - this.$__.inserting = false; - - const delta = this.$__delta(); - if (delta) { - if (delta instanceof MongooseError) { - callback(delta); - return; - } + _decorateUpdateWithVersionKey(update, options, this.schema.options.versionKey); - const where = this.$__where(delta[0]); - if (where instanceof MongooseError) { - callback(where); - return; - } + const mq = new this.Query({}, {}, this, this.$__collection); + mq.select(fields); - _applyCustomWhere(this, where); + return mq.findOneAndUpdate(conditions, update, options, callback); +}; - this[modelCollectionSymbol].updateOne( - where, - delta[1], - saveOptions, - (err, ret) => { - if (err) { - this.$__undoReset(); +/*! + * Decorate the update with a version key, if necessary + */ - callback(err); - return; - } - ret.$where = where; - callback(null, ret); - } - ); - } else { - const optionsWithCustomValues = Object.assign( - {}, - options, - saveOptions - ); - const where = this.$__where(); - if (this.$__schema.options.optimisticConcurrency) { - const key = this.$__schema.options.versionKey; - const val = this.$__getValue(key); - if (val != null) { - where[key] = val; - } - } - this.constructor - .exists(where, optionsWithCustomValues) - .then((documentExists) => { - if (!documentExists) { - throw new DocumentNotFoundError( - this.$__where(), - this.constructor.modelName - ); - } +function _decorateUpdateWithVersionKey(update, options, versionKey) { + if (!versionKey || !get(options, 'upsert', false)) { + return; + } - callback(); - }) - .catch(callback); - return; - } + const updatedPaths = modifiedPaths(update); + if (!updatedPaths[versionKey]) { + if (options.overwrite) { + update[versionKey] = 0; + } else { + if (!update.$setOnInsert) { + update.$setOnInsert = {}; + } + update.$setOnInsert[versionKey] = 0; + } + } +} - // store the modified paths before the document is reset - this.$__.modifiedPaths = this.modifiedPaths(); - this.$__reset(); +/** + * Issues a mongodb findAndModify update command by a document's _id field. + * `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`. + * + * Finds a matching document, updates it according to the `update` arg, + * passing any `options`, and returns the found document (if any) to the + * callback. The query executes if `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndUpdate()` + * + * ####Options: + * + * - `new`: bool - true to return the modified document rather than the original. defaults to false + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. + * - `setDefaultsOnInsert`: `true` by default. If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `select`: sets the document fields to return + * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update + * + * ####Examples: + * + * A.findByIdAndUpdate(id, update, options, callback) // executes + * A.findByIdAndUpdate(id, update, options) // returns Query + * A.findByIdAndUpdate(id, update, callback) // executes + * A.findByIdAndUpdate(id, update) // returns Query + * A.findByIdAndUpdate() // returns Query + * + * ####Note: + * + * If id is undefined and update is specified, an error will be thrown. + * + * ####Note: + * + * All top level update keys which are not `atomic` operation names are treated as set operations: + * + * ####Example: + * + * Model.findByIdAndUpdate(id, { name: 'jason bourne' }, options, callback) + * + * // is sent as + * Model.findByIdAndUpdate(id, { $set: { name: 'jason bourne' }}, options, callback) + * + * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`. + * + * ####Note: + * + * `findOneAndX` and `findByIdAndX` functions support limited validation. You can + * enable validation by setting the `runValidators` option. + * + * If you need full-fledged validation, use the traditional approach of first + * retrieving the document. + * + * Model.findById(id, function (err, doc) { + * if (err) .. + * doc.name = 'jason bourne'; + * doc.save(callback); + * }); + * + * @param {Object|Number|String} id value of `_id` to query by + * @param {Object} [update] + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {String} [options.returnDocument='before'] Has two possible values, `'before'` and `'after'`. By default, it will return the document before the update was applied. + * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `update`, Mongoose will wrap `update` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. An alternative to this would be using [Model.findOneAndReplace({ _id: id }, update, options, callback)](https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndReplace). + * @param {Function} [callback] + * @return {Query} + * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ - _setIsNew(this, false); - } - }; +Model.findByIdAndUpdate = function(id, update, options, callback) { + _checkContext(this, 'findByIdAndUpdate'); + + callback = this.$handleCallbackError(callback); + if (arguments.length === 1) { + if (typeof id === 'function') { + const msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\n' + + ' ' + this.modelName + '.findByIdAndUpdate(id)\n' + + ' ' + this.modelName + '.findByIdAndUpdate()\n'; + throw new TypeError(msg); + } + return this.findOneAndUpdate({ _id: id }, undefined); + } else if (arguments.length > 1 && id === undefined) { + const msg = 'Model.findByIdAndUpdate(): id cannot be undefined if update is specified.'; + throw new TypeError(msg); + } - /*! - * ignore - */ + // if a model is passed in instead of an id + if (id instanceof Document) { + id = id._id; + } - Model.prototype.$__save = function (options, callback) { - this.$__handleSave(options, (error, result) => { - const hooks = this.$__schema.s.hooks; - if (error) { - return hooks.execPost( - "save:error", - this, - [this], - { error: error }, - (error) => { - callback(error, this); - } - ); - } - let numAffected = 0; - if (get(options, "safe.w") !== 0 && get(options, "w") !== 0) { - // Skip checking if write succeeded if writeConcern is set to - // unacknowledged writes, because otherwise `numAffected` will always be 0 - if (result) { - if (Array.isArray(result)) { - numAffected = result.length; - } else if (result.result && result.result.n !== undefined) { - numAffected = result.result.n; - } else if ( - result.result && - result.result.nModified !== undefined - ) { - numAffected = result.result.nModified; - } else { - numAffected = result; - } - } - // was this an update that required a version bump? - if (this.$__.version && !this.$__.inserting) { - const doIncrement = - VERSION_INC === (VERSION_INC & this.$__.version); - this.$__.version = undefined; - const key = this.$__schema.options.versionKey; - const version = this.$__getValue(key) || 0; - if (numAffected <= 0) { - // the update failed. pass an error back - this.$__undoReset(); - const err = - this.$__.$versionError || - new VersionError(this, version, this.$__.modifiedPaths); - return callback(err); - } + return this.findOneAndUpdate.call(this, { _id: id }, update, options, callback); +}; - // increment version if was successful - if (doIncrement) { - this.$__setValue(key, version + 1); - } - } - if (result != null && numAffected <= 0) { - this.$__undoReset(); - error = new DocumentNotFoundError( - result.$where, - this.constructor.modelName, - numAffected, - result - ); - return hooks.execPost( - "save:error", - this, - [this], - { error: error }, - (error) => { - callback(error, this); - } - ); - } - } - this.$__.saving = undefined; - this.$__.savedState = {}; - this.emit("save", this, numAffected); - this.constructor.emit("save", this, numAffected); - callback(null, this); - }); - }; +/** + * Issue a MongoDB `findOneAndDelete()` command. + * + * Finds a matching document, removes it, and passes the found document + * (if any) to the callback. + * + * Executes the query if `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndDelete()` + * + * This function differs slightly from `Model.findOneAndRemove()` in that + * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/), + * as opposed to a `findOneAndDelete()` command. For most mongoose use cases, + * this distinction is purely pedantic. You should use `findOneAndDelete()` + * unless you have a good reason not to. + * + * ####Options: + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `select`: sets the document fields to return, ex. `{ projection: { _id: 0 } }` + * - `projection`: equivalent to `select` + * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update + * + * ####Examples: + * + * A.findOneAndDelete(conditions, options, callback) // executes + * A.findOneAndDelete(conditions, options) // return Query + * A.findOneAndDelete(conditions, callback) // executes + * A.findOneAndDelete(conditions) // returns Query + * A.findOneAndDelete() // returns Query + * + * `findOneAndX` and `findByIdAndX` functions support limited validation. You can + * enable validation by setting the `runValidators` option. + * + * If you need full-fledged validation, use the traditional approach of first + * retrieving the document. + * + * Model.findById(id, function (err, doc) { + * if (err) .. + * doc.name = 'jason bourne'; + * doc.save(callback); + * }); + * + * @param {Object} conditions + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Object|String|Array} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Function} [callback] + * @return {Query} + * @api public + */ - /*! - * ignore - */ - - function generateVersionError(doc, modifiedPaths) { - const key = doc.$__schema.options.versionKey; - if (!key) { - return null; - } - const version = doc.$__getValue(key) || 0; - return new VersionError(doc, version, modifiedPaths); - } - - /** - * Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`, - * or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation with just the modified paths if `isNew` is `false`. - * - * ####Example: - * - * product.sold = Date.now(); - * product = await product.save(); - * - * If save is successful, the returned promise will fulfill with the document - * saved. - * - * ####Example: - * - * const newProduct = await product.save(); - * newProduct === product; // true - * - * @param {Object} [options] options optional options - * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). - * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead. - * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. - * @param {Boolean} [options.validateModifiedOnly=false] if `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths. - * @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) - * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) - * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern). - * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names) - * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`. - * @param {Function} [fn] optional callback - * @throws {DocumentNotFoundError} if this [save updates an existing document](api.html#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating). - * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise. - * @api public - * @see middleware http://mongoosejs.com/docs/middleware.html - */ - - Model.prototype.save = function (options, fn) { - let parallelSave; - this.$op = "save"; - - if (this.$__.saving) { - parallelSave = new ParallelSaveError(this); - } else { - this.$__.saving = new ParallelSaveError(this); - } +Model.findOneAndDelete = function(conditions, options, callback) { + _checkContext(this, 'findOneAndDelete'); - if (typeof options === "function") { - fn = options; - options = undefined; - } + if (arguments.length === 1 && typeof conditions === 'function') { + const msg = 'Model.findOneAndDelete(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findOneAndDelete(conditions, callback)\n' + + ' ' + this.modelName + '.findOneAndDelete(conditions)\n' + + ' ' + this.modelName + '.findOneAndDelete()\n'; + throw new TypeError(msg); + } - options = new SaveOptions(options); - if (options.hasOwnProperty("session")) { - this.$session(options.session); - } - this.$__.$versionError = generateVersionError( - this, - this.modifiedPaths() - ); + if (typeof options === 'function') { + callback = options; + options = undefined; + } + callback = this.$handleCallbackError(callback); - fn = this.constructor.$handleCallbackError(fn); - return this.constructor.db.base._promiseOrCallback( - fn, - (cb) => { - cb = this.constructor.$wrapCallback(cb); + let fields; + if (options) { + fields = options.select; + options.select = undefined; + } - if (parallelSave) { - this.$__handleReject(parallelSave); - return cb(parallelSave); - } + const mq = new this.Query({}, {}, this, this.$__collection); + mq.select(fields); - this.$__.saveOptions = options; + return mq.findOneAndDelete(conditions, options, callback); +}; - this.$__save(options, (error) => { - this.$__.saving = undefined; - delete this.$__.saveOptions; - delete this.$__.$versionError; - this.$op = null; +/** + * Issue a MongoDB `findOneAndDelete()` command by a document's _id field. + * In other words, `findByIdAndDelete(id)` is a shorthand for + * `findOneAndDelete({ _id: id })`. + * + * This function triggers the following middleware. + * + * - `findOneAndDelete()` + * + * @param {Object|Number|String} id value of `_id` to query by + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Function} [callback] + * @return {Query} + * @see Model.findOneAndRemove #model_Model.findOneAndRemove + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + */ - if (error) { - this.$__handleReject(error); - return cb(error); - } - cb(null, this); - }); - }, - this.constructor.events - ); - }; +Model.findByIdAndDelete = function(id, options, callback) { + _checkContext(this, 'findByIdAndDelete'); - /*! - * Determines whether versioning should be skipped for the given path - * - * @param {Document} self - * @param {String} path - * @return {Boolean} true if versioning should be skipped for the given path - */ - function shouldSkipVersioning(self, path) { - const skipVersioning = self.$__schema.options.skipVersioning; - if (!skipVersioning) return false; - - // Remove any array indexes from the path - path = path.replace(/\.\d+\./, "."); - - return skipVersioning[path]; - } - - /*! - * Apply the operation to the delta (update) clause as - * well as track versioning for our where clause. - * - * @param {Document} self - * @param {Object} where - * @param {Object} delta - * @param {Object} data - * @param {Mixed} val - * @param {String} [operation] - */ - - function operand(self, where, delta, data, val, op) { - // delta - op || (op = "$set"); - if (!delta[op]) delta[op] = {}; - delta[op][data.path] = val; - // disabled versioning? - if (self.$__schema.options.versionKey === false) return; - - // path excluded from versioning? - if (shouldSkipVersioning(self, data.path)) return; - - // already marked for versioning? - if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return; - - if (self.$__schema.options.optimisticConcurrency) { - self.$__.version = VERSION_ALL; - return; - } + if (arguments.length === 1 && typeof id === 'function') { + const msg = 'Model.findByIdAndDelete(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findByIdAndDelete(id, callback)\n' + + ' ' + this.modelName + '.findByIdAndDelete(id)\n' + + ' ' + this.modelName + '.findByIdAndDelete()\n'; + throw new TypeError(msg); + } + callback = this.$handleCallbackError(callback); - switch (op) { - case "$set": - case "$unset": - case "$pop": - case "$pull": - case "$pullAll": - case "$push": - case "$addToSet": - break; - default: - // nothing to do - return; - } + return this.findOneAndDelete({ _id: id }, options, callback); +}; - // ensure updates sent with positional notation are - // editing the correct array element. - // only increment the version if an array position changes. - // modifying elements of an array is ok if position does not change. - if ( - op === "$push" || - op === "$addToSet" || - op === "$pullAll" || - op === "$pull" - ) { - self.$__.version = VERSION_INC; - } else if (/^\$p/.test(op)) { - // potentially changing array positions - increment.call(self); - } else if (Array.isArray(val)) { - // $set an array - increment.call(self); - } else if (/\.\d+\.|\.\d+$/.test(data.path)) { - // now handling $set, $unset - // subpath of array - self.$__.version = VERSION_WHERE; - } - } - - /*! - * Compiles an update and where clause for a `val` with _atomics. - * - * @param {Document} self - * @param {Object} where - * @param {Object} delta - * @param {Object} data - * @param {Array} value - */ - - function handleAtomics(self, where, delta, data, value) { - if (delta.$set && delta.$set[data.path]) { - // $set has precedence over other atomics - return; - } +/** + * Issue a MongoDB `findOneAndReplace()` command. + * + * Finds a matching document, replaces it with the provided doc, and passes the + * returned doc to the callback. + * + * Executes the query if `callback` is passed. + * + * This function triggers the following query middleware. + * + * - `findOneAndReplace()` + * + * ####Options: + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `select`: sets the document fields to return + * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }` + * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update + * + * ####Examples: + * + * A.findOneAndReplace(conditions, options, callback) // executes + * A.findOneAndReplace(conditions, options) // return Query + * A.findOneAndReplace(conditions, callback) // executes + * A.findOneAndReplace(conditions) // returns Query + * A.findOneAndReplace() // returns Query + * + * @param {Object} filter Replace the first document that matches this filter + * @param {Object} [replacement] Replace with this document + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {String} [options.returnDocument='before'] Has two possible values, `'before'` and `'after'`. By default, it will return the document before the update was applied. + * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Object|String|Array} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) + * @param {Function} [callback] + * @return {Query} + * @api public + */ - if (typeof value.$__getAtomics === "function") { - value.$__getAtomics().forEach(function (atomic) { - const op = atomic[0]; - const val = atomic[1]; - operand(self, where, delta, data, val, op); - }); - return; - } +Model.findOneAndReplace = function(filter, replacement, options, callback) { + _checkContext(this, 'findOneAndReplace'); - // legacy support for plugins + if (arguments.length === 1 && typeof filter === 'function') { + const msg = 'Model.findOneAndReplace(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findOneAndReplace(conditions, callback)\n' + + ' ' + this.modelName + '.findOneAndReplace(conditions)\n' + + ' ' + this.modelName + '.findOneAndReplace()\n'; + throw new TypeError(msg); + } - const atomics = value[arrayAtomicsSymbol]; - const ops = Object.keys(atomics); - let i = ops.length; - let val; - let op; + if (arguments.length === 3 && typeof options === 'function') { + callback = options; + options = replacement; + replacement = void 0; + } + if (arguments.length === 2 && typeof replacement === 'function') { + callback = replacement; + replacement = void 0; + options = void 0; + } + callback = this.$handleCallbackError(callback); - if (i === 0) { - // $set + let fields; + if (options) { + fields = options.select; + options.select = undefined; + } - if (utils.isMongooseObject(value)) { - value = value.toObject({ depopulate: 1, _isNested: true }); - } else if (value.valueOf) { - value = value.valueOf(); - } + const mq = new this.Query({}, {}, this, this.$__collection); + mq.select(fields); - return operand(self, where, delta, data, value); - } + return mq.findOneAndReplace(filter, replacement, options, callback); +}; - function iter(mem) { - return utils.isMongooseObject(mem) - ? mem.toObject({ depopulate: 1, _isNested: true }) - : mem; - } +/** + * Issue a mongodb findAndModify remove command. + * + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * + * Executes the query if `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndRemove()` + * + * ####Options: + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `select`: sets the document fields to return + * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }` + * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update + * + * ####Examples: + * + * A.findOneAndRemove(conditions, options, callback) // executes + * A.findOneAndRemove(conditions, options) // return Query + * A.findOneAndRemove(conditions, callback) // executes + * A.findOneAndRemove(conditions) // returns Query + * A.findOneAndRemove() // returns Query + * + * `findOneAndX` and `findByIdAndX` functions support limited validation. You can + * enable validation by setting the `runValidators` option. + * + * If you need full-fledged validation, use the traditional approach of first + * retrieving the document. + * + * Model.findById(id, function (err, doc) { + * if (err) .. + * doc.name = 'jason bourne'; + * doc.save(callback); + * }); + * + * @param {Object} conditions + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Object|String|Array} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) + * @param {Function} [callback] + * @return {Query} + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ - while (i--) { - op = ops[i]; - val = atomics[op]; +Model.findOneAndRemove = function(conditions, options, callback) { + _checkContext(this, 'findOneAndRemove'); - if (utils.isMongooseObject(val)) { - val = val.toObject({ - depopulate: true, - transform: false, - _isNested: true, - }); - } else if (Array.isArray(val)) { - val = val.map(iter); - } else if (val.valueOf) { - val = val.valueOf(); - } + if (arguments.length === 1 && typeof conditions === 'function') { + const msg = 'Model.findOneAndRemove(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\n' + + ' ' + this.modelName + '.findOneAndRemove(conditions)\n' + + ' ' + this.modelName + '.findOneAndRemove()\n'; + throw new TypeError(msg); + } - if (op === "$addToSet") { - val = { $each: val }; - } + if (typeof options === 'function') { + callback = options; + options = undefined; + } + callback = this.$handleCallbackError(callback); - operand(self, where, delta, data, val, op); - } - } + let fields; + if (options) { + fields = options.select; + options.select = undefined; + } - /** - * Produces a special query document of the modified properties used in updates. - * - * @api private - * @method $__delta - * @memberOf Model - * @instance - */ + const mq = new this.Query({}, {}, this, this.$__collection); + mq.select(fields); - Model.prototype.$__delta = function () { - const dirty = this.$__dirty(); - if (!dirty.length && VERSION_ALL !== this.$__.version) { - return; - } - const where = {}; - const delta = {}; - const len = dirty.length; - const divergent = []; - let d = 0; - - where._id = this._doc._id; - // If `_id` is an object, need to depopulate, but also need to be careful - // because `_id` can technically be null (see gh-6406) - if (get(where, "_id.$__", null) != null) { - where._id = where._id.toObject({ - transform: false, - depopulate: true, - }); - } - for (; d < len; ++d) { - const data = dirty[d]; - let value = data.value; + return mq.findOneAndRemove(conditions, options, callback); +}; - const match = checkDivergentArray(this, data.path, value); - if (match) { - divergent.push(match); - continue; - } +/** + * Issue a mongodb findAndModify remove command by a document's _id field. `findByIdAndRemove(id, ...)` is equivalent to `findOneAndRemove({ _id: id }, ...)`. + * + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * + * Executes the query if `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndRemove()` + * + * ####Options: + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `select`: sets the document fields to return + * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update + * + * ####Examples: + * + * A.findByIdAndRemove(id, options, callback) // executes + * A.findByIdAndRemove(id, options) // return Query + * A.findByIdAndRemove(id, callback) // executes + * A.findByIdAndRemove(id) // returns Query + * A.findByIdAndRemove() // returns Query + * + * @param {Object|Number|String} id value of `_id` to query by + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Object|String|Array} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) + * @param {Function} [callback] + * @return {Query} + * @see Model.findOneAndRemove #model_Model.findOneAndRemove + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + */ - const pop = this.populated(data.path, true); - if (!pop && this.$__.selected) { - // If any array was selected using an $elemMatch projection, we alter the path and where clause - // NOTE: MongoDB only supports projected $elemMatch on top level array. - const pathSplit = data.path.split("."); - const top = pathSplit[0]; - if (this.$__.selected[top] && this.$__.selected[top].$elemMatch) { - // If the selected array entry was modified - if ( - pathSplit.length > 1 && - pathSplit[1] == 0 && - typeof where[top] === "undefined" - ) { - where[top] = this.$__.selected[top]; - pathSplit[1] = "$"; - data.path = pathSplit.join("."); - } - // if the selected array was modified in any other way throw an error - else { - divergent.push(data.path); - continue; - } - } - } +Model.findByIdAndRemove = function(id, options, callback) { + _checkContext(this, 'findByIdAndRemove'); - if (divergent.length) continue; - if (value === undefined) { - operand(this, where, delta, data, 1, "$unset"); - } else if (value === null) { - operand(this, where, delta, data, null); - } else if ( - value.isMongooseArray && - value.$path() && - value[arrayAtomicsSymbol] - ) { - // arrays and other custom types (support plugins etc) - handleAtomics(this, where, delta, data, value); - } else if ( - value[MongooseBuffer.pathSymbol] && - Buffer.isBuffer(value) - ) { - // MongooseBuffer - value = value.toObject(); - operand(this, where, delta, data, value); - } else { - value = utils.clone(value, { - depopulate: true, - transform: false, - virtuals: false, - getters: false, - _isNested: true, - }); - operand(this, where, delta, data, value); - } - } + if (arguments.length === 1 && typeof id === 'function') { + const msg = 'Model.findByIdAndRemove(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\n' + + ' ' + this.modelName + '.findByIdAndRemove(id)\n' + + ' ' + this.modelName + '.findByIdAndRemove()\n'; + throw new TypeError(msg); + } + callback = this.$handleCallbackError(callback); - if (divergent.length) { - return new DivergentArrayError(divergent); - } + return this.findOneAndRemove({ _id: id }, options, callback); +}; - if (this.$__.version) { - this.$__version(where, delta); - } - return [where, delta]; - }; +/** + * Shortcut for saving one or more documents to the database. + * `MyModel.create(docs)` does `new MyModel(doc).save()` for every doc in + * docs. + * + * This function triggers the following middleware. + * + * - `save()` + * + * ####Example: + * + * // Insert one new `Character` document + * await Character.create({ name: 'Jean-Luc Picard' }); + * + * // Insert multiple new `Character` documents + * await Character.create([{ name: 'Will Riker' }, { name: 'Geordi LaForge' }]); + * + * // Create a new character within a transaction. Note that you **must** + * // pass an array as the first parameter to `create()` if you want to + * // specify options. + * await Character.create([{ name: 'Jean-Luc Picard' }], { session }); + * + * @param {Array|Object} docs Documents to insert, as a spread or array + * @param {Object} [options] Options passed down to `save()`. To specify `options`, `docs` **must** be an array, not a spread. + * @param {Function} [callback] callback + * @return {Promise} + * @api public + */ - /*! - * Determine if array was populated with some form of filter and is now - * being updated in a manner which could overwrite data unintentionally. - * - * @see https://github.com/Automattic/mongoose/issues/1334 - * @param {Document} doc - * @param {String} path - * @return {String|undefined} - */ - - function checkDivergentArray(doc, path, array) { - // see if we populated this path - const pop = doc.populated(path, true); - - if (!pop && doc.$__.selected) { - // If any array was selected using an $elemMatch projection, we deny the update. - // NOTE: MongoDB only supports projected $elemMatch on top level array. - const top = path.split(".")[0]; - if (doc.$__.selected[top + ".$"]) { - return top; - } - } +Model.create = function create(doc, options, callback) { + _checkContext(this, 'create'); + + let args; + let cb; + const discriminatorKey = this.schema.options.discriminatorKey; + + if (Array.isArray(doc)) { + args = doc; + cb = typeof options === 'function' ? options : callback; + options = options != null && typeof options === 'object' ? options : {}; + } else { + const last = arguments[arguments.length - 1]; + options = {}; + // Handle falsy callbacks re: #5061 + if (typeof last === 'function' || (arguments.length > 1 && !last)) { + cb = last; + args = utils.args(arguments, 0, arguments.length - 1); + } else { + args = utils.args(arguments); + } - if (!(pop && array && array.isMongooseArray)) return; - - // If the array was populated using options that prevented all - // documents from being returned (match, skip, limit) or they - // deselected the _id field, $pop and $set of the array are - // not safe operations. If _id was deselected, we do not know - // how to remove elements. $pop will pop off the _id from the end - // of the array in the db which is not guaranteed to be the - // same as the last element we have here. $set of the entire array - // would be similarily destructive as we never received all - // elements of the array and potentially would overwrite data. - const check = - pop.options.match || - (pop.options.options && - utils.object.hasOwnProperty(pop.options.options, "limit")) || // 0 is not permitted - (pop.options.options && pop.options.options.skip) || // 0 is permitted - (pop.options.select && // deselected _id? - (pop.options.select._id === 0 || - /\s?-_id\s?/.test(pop.options.select))); - - if (check) { - const atomics = array[arrayAtomicsSymbol]; - if ( - Object.keys(atomics).length === 0 || - atomics.$set || - atomics.$pop - ) { - return path; - } - } - } + if (args.length === 2 && + args[0] != null && + args[1] != null && + args[0].session == null && + getConstructorName(last.session) === 'ClientSession' && + !this.schema.path('session')) { + // Probably means the user is running into the common mistake of trying + // to use a spread to specify options, see gh-7535 + utils.warn('WARNING: to pass a `session` to `Model.create()` in ' + + 'Mongoose, you **must** pass an array as the first argument. See: ' + + 'https://mongoosejs.com/docs/api.html#model_Model.create'); + } + } - /** - * Appends versioning to the where and update clauses. - * - * @api private - * @method $__version - * @memberOf Model - * @instance - */ + return this.db.base._promiseOrCallback(cb, cb => { + cb = this.$wrapCallback(cb); - Model.prototype.$__version = function (where, delta) { - const key = this.$__schema.options.versionKey; + if (args.length === 0) { + if (Array.isArray(doc)) { + return cb(null, []); + } else { + return cb(null); + } + } - if (where === true) { - // this is an insert - if (key) { - this.$__setValue(key, (delta[key] = 0)); + const toExecute = []; + let firstError; + args.forEach(doc => { + toExecute.push(callback => { + const Model = this.discriminators && doc[discriminatorKey] != null ? + this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) : + this; + if (Model == null) { + throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` + + `found for model "${this.modelName}"`); + } + let toSave = doc; + const callbackWrapper = (error, doc) => { + if (error) { + if (!firstError) { + firstError = error; + } + return callback(null, { error: error }); } - return; - } - - // updates + callback(null, { doc: doc }); + }; - // only apply versioning if our versionKey was selected. else - // there is no way to select the correct version. we could fail - // fast here and force them to include the versionKey but - // thats a bit intrusive. can we do this automatically? - if (!this.$__isSelected(key)) { - return; + if (!(toSave instanceof Model)) { + try { + toSave = new Model(toSave); + } catch (error) { + return callbackWrapper(error); + } } - // $push $addToSet don't need the where clause set - if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) { - const value = this.$__getValue(key); - if (value != null) where[key] = value; - } + toSave.$save(options, callbackWrapper); + }); + }); - if (VERSION_INC === (VERSION_INC & this.$__.version)) { - if (get(delta.$set, key, null) != null) { - // Version key is getting set, means we'll increment the doc's version - // after a successful save, so we should set the incremented version so - // future saves don't fail (gh-5779) - ++delta.$set[key]; - } else { - delta.$inc = delta.$inc || {}; - delta.$inc[key] = 1; - } + let numFns = toExecute.length; + if (numFns === 0) { + return cb(null, []); + } + const _done = (error, res) => { + const savedDocs = []; + const len = res.length; + for (let i = 0; i < len; ++i) { + if (res[i].doc) { + savedDocs.push(res[i].doc); } - }; + } - /** - * Signal that we desire an increment of this documents version. - * - * ####Example: - * - * Model.findById(id, function (err, doc) { - * doc.increment(); - * doc.save(function (err) { .. }) - * }) - * - * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey - * @api public - */ - - function increment() { - this.$__.version = VERSION_ALL; - return this; + if (firstError) { + return cb(firstError, savedDocs); } - Model.prototype.increment = increment; + if (doc instanceof Array) { + cb(null, savedDocs); + } else { + cb.apply(this, [null].concat(savedDocs)); + } + }; - /** - * Returns a query object - * - * @api private - * @method $__where - * @memberOf Model - * @instance - */ + const _res = []; + toExecute.forEach((fn, i) => { + fn((err, res) => { + _res[i] = res; + if (--numFns <= 0) { + return _done(null, _res); + } + }); + }); + }, this.events); +}; - Model.prototype.$__where = function _where(where) { - where || (where = {}); +/** + * _Requires a replica set running MongoDB >= 3.6.0._ Watches the + * underlying collection for changes using + * [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/). + * + * This function does **not** trigger any middleware. In particular, it + * does **not** trigger aggregate middleware. + * + * The ChangeStream object is an event emitter that emits the following events: + * + * - 'change': A change occurred, see below example + * - 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow [this GitHub issue](https://github.com/Automattic/mongoose/issues/6799) for updates. + * - 'end': Emitted if the underlying stream is closed + * - 'close': Emitted if the underlying stream is closed + * + * ####Example: + * + * const doc = await Person.create({ name: 'Ned Stark' }); + * const changeStream = Person.watch().on('change', change => console.log(change)); + * // Will print from the above `console.log()`: + * // { _id: { _data: ... }, + * // operationType: 'delete', + * // ns: { db: 'mydb', coll: 'Person' }, + * // documentKey: { _id: 5a51b125c5500f5aa094c7bd } } + * await doc.remove(); + * + * @param {Array} [pipeline] + * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#watch) + * @return {ChangeStream} mongoose-specific change stream wrapper, inherits from EventEmitter + * @api public + */ - if (!where._id) { - where._id = this._doc._id; - } +Model.watch = function(pipeline, options) { + _checkContext(this, 'watch'); - if (this._doc._id === void 0) { - return new MongooseError("No _id found on document!"); + const changeStreamThunk = cb => { + pipeline = pipeline || []; + prepareDiscriminatorPipeline(pipeline, this.schema, 'fullDocument'); + if (this.$__collection.buffer) { + this.$__collection.addQueue(() => { + if (this.closed) { + return; } + const driverChangeStream = this.$__collection.watch(pipeline, options); + cb(null, driverChangeStream); + }); + } else { + const driverChangeStream = this.$__collection.watch(pipeline, options); + cb(null, driverChangeStream); + } + }; - return where; - }; - - /** - * Removes this document from the db. - * - * ####Example: - * product.remove(function (err, product) { - * if (err) return handleError(err); - * Product.findById(product._id, function (err, product) { - * console.log(product) // null - * }) - * }) - * - * - * As an extra measure of flow control, remove will return a Promise (bound to `fn` if passed) so it could be chained, or hooked to recieve errors - * - * ####Example: - * product.remove().then(function (product) { - * ... - * }).catch(function (err) { - * assert.ok(err) - * }) - * - * @param {Object} [options] - * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). - * @param {function(err,product)} [fn] optional callback - * @return {Promise} Promise - * @api public - */ - - Model.prototype.remove = function remove(options, fn) { - if (typeof options === "function") { - fn = options; - options = undefined; - } - - options = new RemoveOptions(options); - if (options.hasOwnProperty("session")) { - this.$session(options.session); - } - this.$op = "remove"; - - fn = this.constructor.$handleCallbackError(fn); - - return this.constructor.db.base._promiseOrCallback( - fn, - (cb) => { - cb = this.constructor.$wrapCallback(cb); - this.$__remove(options, (err, res) => { - this.$op = null; - cb(err, res); - }); - }, - this.constructor.events - ); - }; + return new ChangeStream(changeStreamThunk, pipeline, options); +}; - /** - * Alias for remove - */ +/** + * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) + * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), + * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). + * + * Calling `MyModel.startSession()` is equivalent to calling `MyModel.db.startSession()`. + * + * This function does not trigger any middleware. + * + * ####Example: + * + * const session = await Person.startSession(); + * let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session }); + * await doc.remove(); + * // `doc` will always be null, even if reading from a replica set + * // secondary. Without causal consistency, it is possible to + * // get a doc back from the below query if the query reads from a + * // secondary that is experiencing replication lag. + * doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' }); + * + * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) + * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency + * @param {Function} [callback] + * @return {Promise} promise that resolves to a MongoDB driver `ClientSession` + * @api public + */ - Model.prototype.delete = Model.prototype.remove; +Model.startSession = function() { + _checkContext(this, 'startSession'); - /** - * Removes this document from the db. Equivalent to `.remove()`. - * - * ####Example: - * product = await product.deleteOne(); - * await Product.findById(product._id); // null - * - * @param {function(err,product)} [fn] optional callback - * @return {Promise} Promise - * @api public - */ + return this.db.startSession.apply(this.db, arguments); +}; - Model.prototype.deleteOne = function deleteOne(options, fn) { - if (typeof options === "function") { - fn = options; - options = undefined; - } +/** + * Shortcut for validating an array of documents and inserting them into + * MongoDB if they're all valid. This function is faster than `.create()` + * because it only sends one operation to the server, rather than one for each + * document. + * + * Mongoose always validates each document **before** sending `insertMany` + * to MongoDB. So if one document has a validation error, no documents will + * be saved, unless you set + * [the `ordered` option to false](https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/#error-handling). + * + * This function does **not** trigger save middleware. + * + * This function triggers the following middleware. + * + * - `insertMany()` + * + * ####Example: + * + * const arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }]; + * Movies.insertMany(arr, function(error, docs) {}); + * + * @param {Array|Object|*} doc(s) + * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertMany) + * @param {Boolean} [options.ordered = true] if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An `insertMany()` with `ordered = false` is called an "unordered" `insertMany()`. + * @param {Boolean} [options.rawResult = false] if false, the returned promise resolves to the documents that passed mongoose document validation. If `true`, will return the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertWriteOpCallback) with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`. + * @param {Boolean} [options.lean = false] if `true`, skips hydrating and validating the documents. This option is useful if you need the extra performance, but Mongoose won't validate the documents before inserting. + * @param {Number} [options.limit = null] this limits the number of documents being processed (validation/casting) by mongoose in parallel, this does **NOT** send the documents in batches to MongoDB. Use this option if you're processing a large number of documents and your app is running out of memory. + * @param {String|Object|Array} [options.populate = null] populates the result documents. This option is a no-op if `rawResult` is set. + * @param {Function} [callback] callback + * @return {Promise} resolving to the raw result from the MongoDB driver if `options.rawResult` was `true`, or the documents that passed validation, otherwise + * @api public + */ - if (!options) { - options = {}; - } +Model.insertMany = function(arr, options, callback) { + _checkContext(this, 'insertMany'); - fn = this.constructor.$handleCallbackError(fn); + if (typeof options === 'function') { + callback = options; + options = null; + } + return this.db.base._promiseOrCallback(callback, cb => { + this.$__insertMany(arr, options, cb); + }, this.events); +}; - return this.constructor.db.base._promiseOrCallback( - fn, - (cb) => { - cb = this.constructor.$wrapCallback(cb); - this.$__deleteOne(options, cb); - }, - this.constructor.events - ); - }; +/*! + * ignore + */ - /*! - * ignore - */ +Model.$__insertMany = function(arr, options, callback) { + const _this = this; + if (typeof options === 'function') { + callback = options; + options = null; + } + if (callback) { + callback = this.$handleCallbackError(callback); + callback = this.$wrapCallback(callback); + } + callback = callback || utils.noop; + options = options || {}; + const limit = get(options, 'limit', 1000); + const rawResult = get(options, 'rawResult', false); + const ordered = get(options, 'ordered', true); + const lean = get(options, 'lean', false); + + if (!Array.isArray(arr)) { + arr = [arr]; + } - Model.prototype.$__remove = function $__remove(options, cb) { - if (this.$__.isDeleted) { - return immediate(() => cb(null, this)); + const validationErrors = []; + const toExecute = arr.map(doc => + callback => { + if (!(doc instanceof _this)) { + try { + doc = new _this(doc); + } catch (err) { + return callback(err); } - - const where = this.$__where(); - if (where instanceof MongooseError) { - return cb(where); + } + if (options.session != null) { + doc.$session(options.session); + } + // If option `lean` is set to true bypass validation + if (lean) { + // we have to execute callback at the nextTick to be compatible + // with parallelLimit, as `results` variable has TDZ issue if we + // execute the callback synchronously + return immediate(() => callback(null, doc)); + } + doc.$validate({ __noPromise: true }, function(error) { + if (error) { + // Option `ordered` signals that insert should be continued after reaching + // a failing insert. Therefore we delegate "null", meaning the validation + // failed. It's up to the next function to filter out all failed models + if (ordered === false) { + validationErrors.push(error); + return callback(null, null); + } + return callback(error); } + callback(null, doc); + }); + }); - _applyCustomWhere(this, where); + parallelLimit(toExecute, limit, function(error, docs) { + if (error) { + callback(error, null); + return; + } + // We filter all failed pre-validations by removing nulls + const docAttributes = docs.filter(function(doc) { + return doc != null; + }); + // Quickly escape while there aren't any valid docAttributes + if (docAttributes.length < 1) { + if (rawResult) { + const res = { + mongoose: { + validationErrors: validationErrors + } + }; + return callback(null, res); + } + callback(null, []); + return; + } + const docObjects = docAttributes.map(function(doc) { + if (doc.$__schema.options.versionKey) { + doc[doc.$__schema.options.versionKey] = 0; + } + if (doc.initializeTimestamps) { + return doc.initializeTimestamps().toObject(internalToObjectOptions); + } + return doc.toObject(internalToObjectOptions); + }); - const session = this.$session(); - if (!options.hasOwnProperty("session")) { - options.session = session; + _this.$__collection.insertMany(docObjects, options, function(error, res) { + if (error) { + // `writeErrors` is a property reported by the MongoDB driver, + // just not if there's only 1 error. + if (error.writeErrors == null && + get(error, 'result.result.writeErrors') != null) { + error.writeErrors = error.result.result.writeErrors; } - this[modelCollectionSymbol].deleteOne(where, options, (err) => { - if (!err) { - this.$__.isDeleted = true; - this.emit("remove", this); - this.constructor.emit("remove", this); - return cb(null, this); - } - this.$__.isDeleted = false; - cb(err); - }); - }; + // `insertedDocs` is a Mongoose-specific property + const erroredIndexes = new Set(get(error, 'writeErrors', []).map(err => err.index)); - /*! - * ignore - */ - - Model.prototype.$__deleteOne = Model.prototype.$__remove; - - /** - * Returns another Model instance. - * - * ####Example: - * - * const doc = new Tank; - * doc.model('User').findById(id, callback); - * - * @param {String} name model name - * @api public - */ - - Model.prototype.model = function model(name) { - return this[modelDbSymbol].model(name); - }; + let firstErroredIndex = -1; + error.insertedDocs = docAttributes. + filter((doc, i) => { + const isErrored = erroredIndexes.has(i); - /** - * Returns true if at least one document exists in the database that matches - * the given `filter`, and false otherwise. - * - * Under the hood, `MyModel.exists({ answer: 42 })` is equivalent to - * `MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean().then(doc => !!doc)` - * - * ####Example: - * await Character.deleteMany({}); - * await Character.create({ name: 'Jean-Luc Picard' }); - * - * await Character.exists({ name: /picard/i }); // true - * await Character.exists({ name: /riker/i }); // false - * - * This function triggers the following middleware. - * - * - `findOne()` - * - * @param {Object} filter - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] callback - * @return {Promise} - */ - - Model.exists = function exists(filter, options, callback) { - _checkContext(this, "exists"); - if (typeof options === "function") { - callback = options; - options = null; - } - - const query = this.findOne(filter) - .select({ _id: 1 }) - .lean() - .setOptions(options); - - if (typeof callback === "function") { - query.exec(function (err, doc) { - if (err != null) { - return callback(err); - } - callback(null, !!doc); - }); - return; - } - options = options || {}; - if (!options.explain) { - return query.then((doc) => !!doc); - } + if (ordered) { + if (firstErroredIndex > -1) { + return i < firstErroredIndex; + } - return query.exec(); - }; + if (isErrored) { + firstErroredIndex = i; + } + } - /** - * Adds a discriminator type. - * - * ####Example: - * - * function BaseSchema() { - * Schema.apply(this, arguments); - * - * this.add({ - * name: String, - * createdAt: Date - * }); - * } - * util.inherits(BaseSchema, Schema); - * - * const PersonSchema = new BaseSchema(); - * const BossSchema = new BaseSchema({ department: String }); - * - * const Person = mongoose.model('Person', PersonSchema); - * const Boss = Person.discriminator('Boss', BossSchema); - * new Boss().__t; // "Boss". `__t` is the default `discriminatorKey` - * - * const employeeSchema = new Schema({ boss: ObjectId }); - * const Employee = Person.discriminator('Employee', employeeSchema, 'staff'); - * new Employee().__t; // "staff" because of 3rd argument above - * - * @param {String} name discriminator model name - * @param {Schema} schema discriminator model schema - * @param {String} [value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. - * @return {Model} The newly created discriminator model - * @api public - */ - - Model.discriminator = function (name, schema, value) { - let model; - if (typeof name === "function") { - model = name; - name = utils.getFunctionName(model); - if (!(model.prototype instanceof Model)) { - throw new MongooseError( - "The provided class " + name + " must extend Model" - ); - } - } + return !isErrored; + }). + map(function setIsNewForInsertedDoc(doc) { + doc.$__reset(); + _setIsNew(doc, false); + return doc; + }); - _checkContext(this, "discriminator"); + callback(error, null); + return; + } - if (utils.isObject(schema) && !schema.instanceOfSchema) { - schema = new Schema(schema); - } + for (const attribute of docAttributes) { + attribute.$__reset(); + _setIsNew(attribute, false); + } - schema = discriminator(this, name, schema, value, true); - if (this.db.models[name]) { - throw new OverwriteModelError(name); + if (rawResult) { + if (ordered === false) { + // Decorate with mongoose validation errors in case of unordered, + // because then still do `insertMany()` + res.mongoose = { + validationErrors: validationErrors + }; } + return callback(null, res); + } - schema.$isRootDiscriminator = true; - schema.$globalPluginsApplied = true; + if (options.populate != null) { + return _this.populate(docAttributes, options.populate, err => { + if (err != null) { + error.insertedDocs = docAttributes; + return callback(err); + } - model = this.db.model(model || name, schema, this.$__collection.name); - this.discriminators[name] = model; - const d = this.discriminators[name]; - d.prototype.__proto__ = this.prototype; - Object.defineProperty(d, "baseModelName", { - value: this.modelName, - configurable: true, - writable: false, + callback(null, docs); }); + } - // apply methods and statics - applyMethods(d, schema); - applyStatics(d, schema); - - if (this[subclassedSymbol] != null) { - for (const submodel of this[subclassedSymbol]) { - submodel.discriminators = submodel.discriminators || {}; - submodel.discriminators[name] = model.__subclass( - model.db, - schema, - submodel.collection.name - ); - } - } + callback(null, docAttributes); + }); + }); +}; - return d; - }; +/*! + * ignore + */ - /*! - * Make sure `this` is a model - */ - - function _checkContext(ctx, fnName) { - // Check context, because it is easy to mistakenly type - // `new Model.discriminator()` and get an incomprehensible error - if (ctx == null || ctx === global) { - throw new MongooseError( - "`Model." + - fnName + - "()` cannot run without a " + - "model as `this`. Make sure you are calling `MyModel." + - fnName + - "()` " + - "where `MyModel` is a Mongoose model." - ); - } else if (ctx[modelSymbol] == null) { - throw new MongooseError( - "`Model." + - fnName + - "()` cannot run without a " + - "model as `this`. Make sure you are not calling " + - "`new Model." + - fnName + - "()`" - ); - } - } +function _setIsNew(doc, val) { + doc.$isNew = val; + doc.$emit('isNew', val); + doc.constructor.emit('isNew', val); - // Model (class) features - - /*! - * Give the constructor the ability to emit events. - */ - - for (const i in EventEmitter.prototype) { - Model[i] = EventEmitter.prototype[i]; - } - - /** - * This function is responsible for building [indexes](https://docs.mongodb.com/manual/indexes/), - * unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off. - * - * Mongoose calls this function automatically when a model is created using - * [`mongoose.model()`](/docs/api.html#mongoose_Mongoose-model) or - * [`connection.model()`](/docs/api.html#connection_Connection-model), so you - * don't need to call it. This function is also idempotent, so you may call it - * to get back a promise that will resolve when your indexes are finished - * building as an alternative to [`MyModel.on('index')`](/docs/guide.html#indexes) - * - * ####Example: - * - * const eventSchema = new Schema({ thing: { type: 'string', unique: true }}) - * // This calls `Event.init()` implicitly, so you don't need to call - * // `Event.init()` on your own. - * const Event = mongoose.model('Event', eventSchema); - * - * Event.init().then(function(Event) { - * // You can also use `Event.on('index')` if you prefer event emitters - * // over promises. - * console.log('Indexes are done building!'); - * }); - * - * @api public - * @param {Function} [callback] - * @returns {Promise} - */ - - Model.init = function init(callback) { - _checkContext(this, "init"); - - this.schema.emit("init", this); - - if (this.$init != null) { - if (callback) { - this.$init.then( - () => callback(), - (err) => callback(err) - ); - return null; - } - return this.$init; - } + const subdocs = doc.$getAllSubdocs(); + for (const subdoc of subdocs) { + subdoc.$isNew = val; + } +} + +/** + * Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`, + * `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one + * command. This is faster than sending multiple independent operations (e.g. + * if you use `create()`) because with `bulkWrite()` there is only one round + * trip to MongoDB. + * + * Mongoose will perform casting on all operations you provide. + * + * This function does **not** trigger any middleware, neither `save()`, nor `update()`. + * If you need to trigger + * `save()` middleware for every document use [`create()`](http://mongoosejs.com/docs/api.html#model_Model.create) instead. + * + * ####Example: + * + * Character.bulkWrite([ + * { + * insertOne: { + * document: { + * name: 'Eddard Stark', + * title: 'Warden of the North' + * } + * } + * }, + * { + * updateOne: { + * filter: { name: 'Eddard Stark' }, + * // If you were using the MongoDB driver directly, you'd need to do + * // `update: { $set: { title: ... } }` but mongoose adds $set for + * // you. + * update: { title: 'Hand of the King' } + * } + * }, + * { + * deleteOne: { + * { + * filter: { name: 'Eddard Stark' } + * } + * } + * } + * ]).then(res => { + * // Prints "1 1 1" + * console.log(res.insertedCount, res.modifiedCount, res.deletedCount); + * }); + * + * The [supported operations](https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/#db.collection.bulkWrite) are: + * + * - `insertOne` + * - `updateOne` + * - `updateMany` + * - `deleteOne` + * - `deleteMany` + * - `replaceOne` + * + * @param {Array} ops + * @param {Object} [ops.insertOne.document] The document to insert + * @param {Object} [opts.updateOne.filter] Update the first document that matches this filter + * @param {Object} [opts.updateOne.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/) + * @param {Boolean} [opts.updateOne.upsert=false] If true, insert a doc if none match + * @param {Boolean} [opts.updateOne.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation + * @param {Object} [opts.updateOne.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use + * @param {Array} [opts.updateOne.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update` + * @param {Object} [opts.updateMany.filter] Update all the documents that match this filter + * @param {Object} [opts.updateMany.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/) + * @param {Boolean} [opts.updateMany.upsert=false] If true, insert a doc if no documents match `filter` + * @param {Boolean} [opts.updateMany.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation + * @param {Object} [opts.updateMany.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use + * @param {Array} [opts.updateMany.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update` + * @param {Object} [opts.deleteOne.filter] Delete the first document that matches this filter + * @param {Object} [opts.deleteMany.filter] Delete all documents that match this filter + * @param {Object} [opts.replaceOne.filter] Replace the first document that matches this filter + * @param {Object} [opts.replaceOne.replacement] The replacement document + * @param {Boolean} [opts.replaceOne.upsert=false] If true, insert a doc if no documents match `filter` + * @param {Object} [options] + * @param {Boolean} [options.ordered=true] If true, execute writes in order and stop at the first error. If false, execute writes in parallel and continue until all writes have either succeeded or errored. + * @param {ClientSession} [options.session=null] The session associated with this bulk write. See [transactions docs](/docs/transactions.html). + * @param {String|number} [options.w=1] The [write concern](https://docs.mongodb.com/manual/reference/write-concern/). See [`Query#w()`](/docs/api.html#query_Query-w) for more information. + * @param {number} [options.wtimeout=null] The [write concern timeout](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). + * @param {Boolean} [options.j=true] If false, disable [journal acknowledgement](https://docs.mongodb.com/manual/reference/write-concern/#j-option) + * @param {Boolean} [options.bypassDocumentValidation=false] If true, disable [MongoDB server-side schema validation](https://docs.mongodb.com/manual/core/schema-validation/) for all writes in this bulk. + * @param {Boolean} [options.strict=null] Overwrites the [`strict` option](/docs/guide.html#strict) on schema. If false, allows filtering and writing fields not defined in the schema for all writes in this bulk. + * @param {Function} [callback] callback `function(error, bulkWriteOpResult) {}` + * @return {Promise} resolves to a [`BulkWriteOpResult`](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~BulkWriteOpResult) if the operation succeeds + * @api public + */ - const Promise = PromiseProvider.get(); - const autoIndex = utils.getOption( - "autoIndex", - this.schema.options, - this.db.config, - this.db.base.options - ); - const autoCreate = utils.getOption( - "autoCreate", - this.schema.options, - this.db.config, - this.db.base.options - ); +Model.bulkWrite = function(ops, options, callback) { + _checkContext(this, 'bulkWrite'); - const _ensureIndexes = autoIndex - ? (cb) => this.ensureIndexes({ _automatic: true }, cb) - : (cb) => cb(); - const _createCollection = autoCreate - ? (cb) => this.createCollection({}, cb) - : (cb) => cb(); + if (typeof options === 'function') { + callback = options; + options = null; + } + options = options || {}; - this.$init = new Promise((resolve, reject) => { - _createCollection((error) => { - if (error) { - return reject(error); - } - _ensureIndexes((error) => { - if (error) { - return reject(error); - } - resolve(this); - }); - }); - }); + const validations = ops.map(op => castBulkWrite(this, op, options)); - if (callback) { - this.$init.then( - () => callback(), - (err) => callback(err) - ); - this.$caught = true; - return null; - } else { - const _catch = this.$init.catch; - const _this = this; - this.$init.catch = function () { - this.$caught = true; - return _catch.apply(_this.$init, arguments); - }; - } + callback = this.$handleCallbackError(callback); + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); + each(validations, (fn, cb) => fn(cb), error => { + if (error) { + return cb(error); + } - return this.$init; - }; + if (ops.length === 0) { + return cb(null, getDefaultBulkwriteResult()); + } - /** - * Create the collection for this model. By default, if no indexes are specified, - * mongoose will not create the collection for the model until any documents are - * created. Use this method to create the collection explicitly. - * - * Note 1: You may need to call this before starting a transaction - * See https://docs.mongodb.com/manual/core/transactions/#transactions-and-operations - * - * Note 2: You don't have to call this if your schema contains index or unique field. - * In that case, just use `Model.init()` - * - * ####Example: - * - * const userSchema = new Schema({ name: String }) - * const User = mongoose.model('User', userSchema); - * - * User.createCollection().then(function(collection) { - * console.log('Collection is created!'); - * }); - * - * @api public - * @param {Object} [options] see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection) - * @param {Function} [callback] - * @returns {Promise} - */ - - Model.createCollection = function createCollection(options, callback) { - _checkContext(this, "createCollection"); - - if (typeof options === "string") { - throw new MongooseError( - "You can't specify a new collection name in Model.createCollection." + - "This is not like Connection.createCollection. Only options are accepted here." - ); - } else if (typeof options === "function") { - callback = options; - options = null; + this.$__collection.bulkWrite(ops, options, (error, res) => { + if (error) { + return cb(error); } - const schemaCollation = get(this, "schema.options.collation", null); - if (schemaCollation != null) { - options = Object.assign({ collation: schemaCollation }, options); - } + cb(null, res); + }); + }); + }, this.events); +}; - callback = this.$handleCallbackError(callback); +/** + * takes an array of documents, gets the changes and inserts/updates documents in the database + * according to whether or not the document is new, or whether it has changes or not. + * + * `bulkSave` uses `bulkWrite` under the hood, so it's mostly useful when dealing with many documents (10K+) + * + * @param {[Document]} documents + * + */ +Model.bulkSave = function(documents) { + const preSavePromises = documents.map(buildPreSavePromise); + + const writeOperations = this.buildBulkWriteOperations(documents, { skipValidation: true }); + + let bulkWriteResultPromise; + return Promise.all(preSavePromises) + .then(() => bulkWriteResultPromise = this.bulkWrite(writeOperations)) + .then(() => documents.map(buildSuccessfulWriteHandlerPromise)) + .then(() => bulkWriteResultPromise) + .catch((err) => { + if (!get(err, 'writeErrors.length')) { + throw err; + } + return Promise.all( + documents.map((document) => { + const documentError = err.writeErrors.find(writeError => { + const writeErrorDocumentId = writeError.err.op._id || writeError.err.op.q._id; + return writeErrorDocumentId.toString() === document._id.toString(); + }); - return this.db.base._promiseOrCallback( - callback, - (cb) => { - cb = this.$wrapCallback(cb); + if (documentError == null) { + return buildSuccessfulWriteHandlerPromise(document); + } + }) + ).then(() => { + throw err; + }); + }); +}; - this.db.createCollection( - this.$__collection.collectionName, - options, - utils.tick((err) => { - if ( - err != null && - (err.name !== "MongoError" || err.code !== 48) - ) { - return cb(err); - } - this.$__collection = this.db.collection( - this.$__collection.collectionName, - options - ); - cb(null, this.$__collection); - }) - ); - }, - this.events - ); - }; +function buildPreSavePromise(document) { + return new Promise((resolve, reject) => { + document.schema.s.hooks.execPre('save', document, (err) => { + if (err) { + reject(err); + return; + } + resolve(); + }); + }); +} + +function buildSuccessfulWriteHandlerPromise(document) { + return new Promise((resolve, reject) => { + handleSuccessfulWrite(document, resolve, reject); + }); +} + +function handleSuccessfulWrite(document, resolve, reject) { + if (document.$isNew) { + _setIsNew(document, false); + } - /** - * Makes the indexes in MongoDB match the indexes defined in this model's - * schema. This function will drop any indexes that are not defined in - * the model's schema except the `_id` index, and build any indexes that - * are in your schema but not in MongoDB. - * - * See the [introductory blog post](http://thecodebarbarian.com/whats-new-in-mongoose-5-2-syncindexes) - * for more information. - * - * ####Example: - * - * const schema = new Schema({ name: { type: String, unique: true } }); - * const Customer = mongoose.model('Customer', schema); - * await Customer.collection.createIndex({ age: 1 }); // Index is not in schema - * // Will drop the 'age' index and create an index on `name` - * await Customer.syncIndexes(); - * - * @param {Object} [options] options to pass to `ensureIndexes()` - * @param {Boolean} [options.background=null] if specified, overrides each index's `background` property - * @param {Function} [callback] optional callback - * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. - * @api public - */ - - Model.syncIndexes = function syncIndexes(options, callback) { - _checkContext(this, "syncIndexes"); - - callback = this.$handleCallbackError(callback); - - return this.db.base._promiseOrCallback( - callback, - (cb) => { - cb = this.$wrapCallback(cb); - - this.createCollection((err) => { - if ( - err != null && - (err.name !== "MongoError" || err.code !== 48) - ) { - return cb(err); - } - this.cleanIndexes((err, dropped) => { - if (err != null) { - return cb(err); - } - this.createIndexes(options, (err) => { - if (err != null) { - return cb(err); - } - cb(null, dropped); - }); - }); - }); - }, - this.events - ); - }; + document.$__reset(); + document.schema.s.hooks.execPost('save', document, {}, (err) => { + if (err) { + reject(err); + return; + } + resolve(); + }); +} - /** - * Does a dry-run of Model.syncIndexes(), meaning that - * the result of this function would be the result of - * Model.syncIndexes(). - * - * @param {Object} options not used at all. - * @param {Function} callback optional callback - * @returns {Promise} which containts an object, {toDrop, toCreate}, which - * are indexes that would be dropped in mongodb and indexes that would be created in mongodb. - */ - - Model.diffIndexes = function diffIndexes(options, callback) { - const toDrop = []; - const toCreate = []; - callback = this.$handleCallbackError(callback); - return this.db.base._promiseOrCallback(callback, (cb) => { - cb = this.$wrapCallback(cb); - this.listIndexes((err, indexes) => { - const schemaIndexes = this.schema.indexes(); - // Iterate through the indexes created in mongodb and - // compare against the indexes in the schema. - for (const index of indexes) { - let found = false; - // Never try to drop `_id` index, MongoDB server doesn't allow it - if (isDefaultIdIndex(index)) { - continue; - } +/** + * + * @param {[Document]} documents The array of documents to build write operations of + * @param {Object} options + * @param {Boolean} options.skipValidation defaults to `false`, when set to true, building the write operations will bypass validating the documents. + * @returns + */ +Model.buildBulkWriteOperations = function buildBulkWriteOperations(documents, options) { + if (!Array.isArray(documents)) { + throw new Error(`bulkSave expects an array of documents to be passed, received \`${documents}\` instead`); + } - for (const schemaIndex of schemaIndexes) { - const key = schemaIndex[0]; - const options = _decorateDiscriminatorIndexOptions( - this, - utils.clone(schemaIndex[1]) - ); - if (isIndexEqual(key, options, index)) { - found = true; - } - } + setDefaultOptions(); - if (!found) { - toDrop.push(index.name); - } - } - // Iterate through the indexes created on the schema and - // compare against the indexes in mongodb. - for (const schemaIndex of schemaIndexes) { - const key = schemaIndex[0]; - let found = false; - const options = _decorateDiscriminatorIndexOptions( - this, - utils.clone(schemaIndex[1]) - ); - for (const index of indexes) { - if (isDefaultIdIndex(index)) { - continue; - } - if (isIndexEqual(key, options, index)) { - found = true; - } - } - if (!found) { - toCreate.push(key); - } - } - cb(null, { toDrop, toCreate }); - }); - }); - }; + const writeOperations = documents.reduce((accumulator, document, i) => { + if (!options.skipValidation) { + if (!(document instanceof Document)) { + throw new Error(`documents.${i} was not a mongoose document, documents must be an array of mongoose documents (instanceof mongoose.Document).`); + } + const validationError = document.validateSync(); + if (validationError) { + throw validationError; + } + } - /** - * Deletes all indexes that aren't defined in this model's schema. Used by - * `syncIndexes()`. - * - * The returned promise resolves to a list of the dropped indexes' names as an array - * - * @param {Function} [callback] optional callback - * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. - * @api public - */ + const isANewDocument = document.isNew; + if (isANewDocument) { + accumulator.push({ + insertOne: { document } + }); - Model.cleanIndexes = function cleanIndexes(callback) { - _checkContext(this, "cleanIndexes"); + return accumulator; + } - callback = this.$handleCallbackError(callback); + const delta = document.$__delta(); + const isDocumentWithChanges = delta != null && !utils.isEmptyObject(delta[0]); - return this.db.base._promiseOrCallback(callback, (cb) => { - const collection = this.$__collection; + if (isDocumentWithChanges) { + const where = document.$__where(delta[0]); + const changes = delta[1]; - this.listIndexes((err, indexes) => { - if (err != null) { - return cb(err); - } + _applyCustomWhere(document, where); - const schemaIndexes = this.schema.indexes(); - const toDrop = []; + document.$__version(where, delta); - for (const index of indexes) { - let found = false; - // Never try to drop `_id` index, MongoDB server doesn't allow it - if (isDefaultIdIndex(index)) { - continue; - } + accumulator.push({ + updateOne: { + filter: where, + update: changes + } + }); - for (const schemaIndex of schemaIndexes) { - const key = schemaIndex[0]; - const options = _decorateDiscriminatorIndexOptions( - this, - utils.clone(schemaIndex[1]) - ); - if (isIndexEqual(key, options, index)) { - found = true; - } - } + return accumulator; + } - if (!found) { - toDrop.push(index.name); - } - } + return accumulator; + }, []); - if (toDrop.length === 0) { - return cb(null, []); - } + return writeOperations; - dropIndexes(toDrop, cb); - }); - function dropIndexes(toDrop, cb) { - let remaining = toDrop.length; - let error = false; - toDrop.forEach((indexName) => { - collection.dropIndex(indexName, (err) => { - if (err != null) { - error = true; - return cb(err); - } - if (!error) { - --remaining || cb(null, toDrop); - } - }); - }); - } - }); - }; + function setDefaultOptions() { + options = options || {}; + if (options.skipValidation == null) { + options.skipValidation = false; + } + } +}; - /** - * Lists the indexes currently defined in MongoDB. This may or may not be - * the same as the indexes defined in your schema depending on whether you - * use the [`autoIndex` option](/docs/guide.html#autoIndex) and if you - * build indexes manually. - * - * @param {Function} [cb] optional callback - * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. - * @api public - */ - - Model.listIndexes = function init(callback) { - _checkContext(this, "listIndexes"); - - const _listIndexes = (cb) => { - this.$__collection.listIndexes().toArray(cb); - }; +/** + * Shortcut for creating a new Document from existing raw data, pre-saved in the DB. + * The document returned has no paths marked as modified initially. + * + * ####Example: + * + * // hydrate previous data into a Mongoose document + * const mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' }); + * + * @param {Object} obj + * @param {Object|String|Array} [projection] optional projection containing which fields should be selected for this document + * @return {Document} document instance + * @api public + */ - callback = this.$handleCallbackError(callback); +Model.hydrate = function(obj, projection) { + _checkContext(this, 'hydrate'); - return this.db.base._promiseOrCallback( - callback, - (cb) => { - cb = this.$wrapCallback(cb); + const document = __nccwpck_require__(5299).createModel(this, obj, projection); + document.$init(obj); + return document; +}; - // Buffering - if (this.$__collection.buffer) { - this.$__collection.addQueue(_listIndexes, [cb]); - } else { - _listIndexes(cb); - } - }, - this.events - ); - }; +/** + * Updates one document in the database without returning it. + * + * This function triggers the following middleware. + * + * - `update()` + * + * This method is deprecated. See [Deprecation Warnings](../deprecations.html#update) for details. + * + * ####Examples: + * + * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn); + * + * const res = await MyModel.update({ name: 'Tobi' }, { ferret: true }); + * res.n; // Number of documents that matched `{ name: 'Tobi' }` + * // Number of documents that were changed. If every doc matched already + * // had `ferret` set to `true`, `nModified` will be 0. + * res.nModified; + * + * ####Valid options: + * + * - `strict` (boolean): overrides the [schema-level `strict` option](/docs/guide.html#strict) for this update + * - `upsert` (boolean): whether to create the doc if it doesn't match (false) + * - `writeConcern` (object): sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * - `multi` (boolean): whether multiple documents should be updated (false) + * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. + * - `setDefaultsOnInsert` (boolean): if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). + * - `timestamps` (boolean): If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. + * - `overwrite` (boolean): disables update-only mode, allowing you to overwrite the doc (false) + * + * All `update` values are cast to their appropriate SchemaTypes before being sent. + * + * The `callback` function receives `(err, rawResponse)`. + * + * - `err` is the error if any occurred + * - `rawResponse` is the full response from Mongo + * + * ####Note: + * + * All top level keys which are not `atomic` operation names are treated as set operations: + * + * ####Example: + * + * const query = { name: 'borne' }; + * Model.update(query, { name: 'jason bourne' }, options, callback); + * + * // is sent as + * Model.update(query, { $set: { name: 'jason bourne' }}, options, function(err, res)); + * // if overwrite option is false. If overwrite is true, sent without the $set wrapper. + * + * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason bourne' }`. + * + * ####Note: + * + * Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error. + * + * @deprecated + * @see strict http://mongoosejs.com/docs/guide.html#strict + * @see response http://docs.mongodb.org/v2.6/reference/command/update/#output + * @param {Object} filter + * @param {Object} doc + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](/docs/api.html#query_Query-setOptions) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.multi=false] whether multiple documents should be updated or just the first one that matches `filter`. + * @param {Boolean} [options.runValidators=false] if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. + * @param {Boolean} [options.setDefaultsOnInsert=false] `true` by default. If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. + * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `doc`, Mongoose will wrap `doc` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. + * @param {Function} [callback] params are (error, [updateWriteOpResult](https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#~updateWriteOpResult)) + * @param {Function} [callback] + * @return {Query} + * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output + * @see writeOpResult https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#~updateWriteOpResult + * @see Query docs https://mongoosejs.com/docs/queries.html + * @api public + */ - /** - * Sends `createIndex` commands to mongo for each index declared in the schema. - * The `createIndex` commands are sent in series. - * - * ####Example: - * - * Event.ensureIndexes(function (err) { - * if (err) return handleError(err); - * }); - * - * After completion, an `index` event is emitted on this `Model` passing an error if one occurred. - * - * ####Example: - * - * const eventSchema = new Schema({ thing: { type: 'string', unique: true }}) - * const Event = mongoose.model('Event', eventSchema); - * - * Event.on('index', function (err) { - * if (err) console.error(err); // error occurred during index creation - * }) - * - * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._ - * - * @param {Object} [options] internal options - * @param {Function} [cb] optional callback - * @return {Promise} - * @api public - */ - - Model.ensureIndexes = function ensureIndexes(options, callback) { - _checkContext(this, "ensureIndexes"); - - if (typeof options === "function") { - callback = options; - options = null; - } - - callback = this.$handleCallbackError(callback); - - return this.db.base._promiseOrCallback( - callback, - (cb) => { - cb = this.$wrapCallback(cb); - - _ensureIndexes(this, options || {}, (error) => { - if (error) { - return cb(error); - } - cb(null); - }); - }, - this.events - ); - }; +Model.update = function update(conditions, doc, options, callback) { + _checkContext(this, 'update'); - /** - * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex) - * function. - * - * @param {Object} [options] internal options - * @param {Function} [cb] optional callback - * @return {Promise} - * @api public - */ + return _update(this, 'update', conditions, doc, options, callback); +}; - Model.createIndexes = function createIndexes(options, callback) { - _checkContext(this, "createIndexes"); +/** + * Same as `update()`, except MongoDB will update _all_ documents that match + * `filter` (as opposed to just the first one) regardless of the value of + * the `multi` option. + * + * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')` + * and `post('updateMany')` instead. + * + * ####Example: + * const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true }); + * res.matchedCount; // Number of documents matched + * res.modifiedCount; // Number of documents modified + * res.acknowledged; // Boolean indicating everything went smoothly. + * res.upsertedId; // null or an id containing a document that had to be upserted. + * res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1. + * + * This function triggers the following middleware. + * + * - `updateMany()` + * + * @param {Object} filter + * @param {Object|Array} update + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. + * @param {Function} [callback] `function(error, res) {}` where `res` has 5 properties: `modifiedCount`, `matchedCount`, `acknowledged`, `upsertedId`, and `upsertedCount`. + * @return {Query} + * @see Query docs https://mongoosejs.com/docs/queries.html + * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @api public + */ - if (typeof options === "function") { - callback = options; - options = {}; - } - options = options || {}; - options.createIndex = true; - return this.ensureIndexes(options, callback); - }; +Model.updateMany = function updateMany(conditions, doc, options, callback) { + _checkContext(this, 'updateMany'); - /*! - * ignore - */ + return _update(this, 'updateMany', conditions, doc, options, callback); +}; - function _ensureIndexes(model, options, callback) { - const indexes = model.schema.indexes(); - let indexError; +/** + * Same as `update()`, except it does not support the `multi` or `overwrite` + * options. + * + * - MongoDB will update _only_ the first document that matches `filter` regardless of the value of the `multi` option. + * - Use `replaceOne()` if you want to overwrite an entire document rather than using atomic operators like `$set`. + * + * ####Example: + * const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' }); + * res.matchedCount; // Number of documents matched + * res.modifiedCount; // Number of documents modified + * res.acknowledged; // Boolean indicating everything went smoothly. + * res.upsertedId; // null or an id containing a document that had to be upserted. + * res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1. + * + * This function triggers the following middleware. + * + * - `updateOne()` + * + * @param {Object} filter + * @param {Object|Array} update + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Function} [callback] params are (error, writeOpResult) + * @return {Query} + * @see Query docs https://mongoosejs.com/docs/queries.html + * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @api public + */ - options = options || {}; - const done = function (err) { - if (err && !model.$caught) { - model.emit("error", err); - } - model.emit("index", err || indexError); - callback && callback(err || indexError); - }; +Model.updateOne = function updateOne(conditions, doc, options, callback) { + _checkContext(this, 'updateOne'); - for (const index of indexes) { - if (isDefaultIdIndex(index)) { - console.warn( - "mongoose: Cannot specify a custom index on `_id` for " + - 'model name "' + - model.modelName + - '", ' + - "MongoDB does not allow overwriting the default `_id` index. See " + - "http://bit.ly/mongodb-id-index" - ); - } - } + return _update(this, 'updateOne', conditions, doc, options, callback); +}; - if (!indexes.length) { - immediate(function () { - done(); - }); - return; - } - // Indexes are created one-by-one to support how MongoDB < 2.4 deals - // with background indexes. +/** + * Same as `update()`, except MongoDB replace the existing document with the + * given document (no atomic operators like `$set`). + * + * ####Example: + * const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' }); + * res.matchedCount; // Number of documents matched + * res.modifiedCount; // Number of documents modified + * res.acknowledged; // Boolean indicating everything went smoothly. + * res.upsertedId; // null or an id containing a document that had to be upserted. + * res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1. + * + * This function triggers the following middleware. + * + * - `replaceOne()` + * + * @param {Object} filter + * @param {Object} doc + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. + * @param {Function} [callback] `function(error, res) {}` where `res` has 3 properties: `n`, `nModified`, `ok`. + * @return {Query} + * @see Query docs https://mongoosejs.com/docs/queries.html + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @return {Query} + * @api public + */ - const indexSingleDone = function (err, fields, options, name) { - model.emit("index-single-done", err, fields, options, name); - }; - const indexSingleStart = function (fields, options) { - model.emit("index-single-start", fields, options); - }; +Model.replaceOne = function replaceOne(conditions, doc, options, callback) { + _checkContext(this, 'replaceOne'); - const baseSchema = model.schema._baseSchema; - const baseSchemaIndexes = baseSchema ? baseSchema.indexes() : []; + const versionKey = get(this, 'schema.options.versionKey', null); + if (versionKey && !doc[versionKey]) { + doc[versionKey] = 0; + } - const create = function () { - if (options._automatic) { - if ( - model.schema.options.autoIndex === false || - (model.schema.options.autoIndex == null && - model.db.config.autoIndex === false) - ) { - return done(); - } - } + return _update(this, 'replaceOne', conditions, doc, options, callback); +}; - const index = indexes.shift(); - if (!index) { - return done(); - } - if (options._automatic && index[1]._autoIndex === false) { - return create(); - } +/*! + * Common code for `updateOne()`, `updateMany()`, `replaceOne()`, and `update()` + * because they need to do the same thing + */ - if (baseSchemaIndexes.find((i) => utils.deepEqual(i, index))) { - return create(); - } +function _update(model, op, conditions, doc, options, callback) { + const mq = new model.Query({}, {}, model, model.collection); + callback = model.$handleCallbackError(callback); + // gh-2406 + // make local deep copy of conditions + if (conditions instanceof Document) { + conditions = conditions.toObject(); + } else { + conditions = utils.clone(conditions); + } + options = typeof options === 'function' ? options : utils.clone(options); - const indexFields = utils.clone(index[0]); - const indexOptions = utils.clone(index[1]); - let isTextIndex = false; - for (const key of Object.keys(indexFields)) { - if (indexFields[key] === "text") { - isTextIndex = true; - } - } - delete indexOptions._autoIndex; - _decorateDiscriminatorIndexOptions(model, indexOptions); - if ("safe" in options) { - _handleSafe(options); - } - applyWriteConcern(model.schema, indexOptions); + const versionKey = get(model, 'schema.options.versionKey', null); + _decorateUpdateWithVersionKey(doc, options, versionKey); - indexSingleStart(indexFields, options); - let useCreateIndex = !!model.base.options.useCreateIndex; - if ("useCreateIndex" in model.db.config) { - useCreateIndex = !!model.db.config.useCreateIndex; - } - if ("createIndex" in options) { - useCreateIndex = !!options.createIndex; - } - if ("background" in options) { - indexOptions.background = options.background; - } - if ( - model.schema.options.hasOwnProperty("collation") && - !indexOptions.hasOwnProperty("collation") && - !isTextIndex - ) { - indexOptions.collation = model.schema.options.collation; - } + return mq[op](conditions, doc, options, callback); +} - const methodName = useCreateIndex ? "createIndex" : "ensureIndex"; - model.collection[methodName]( - indexFields, - indexOptions, - utils.tick(function (err, name) { - indexSingleDone(err, indexFields, indexOptions, name); - if (err) { - if (!indexError) { - indexError = err; - } - if (!model.$caught) { - model.emit("error", err); - } - } - create(); - }) - ); - }; +/** + * Executes a mapReduce command. + * + * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See [node-mongodb-native mapReduce() documentation](http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#mapreduce) for more detail about options. + * + * This function does not trigger any middleware. + * + * ####Example: + * + * const o = {}; + * // `map()` and `reduce()` are run on the MongoDB server, not Node.js, + * // these functions are converted to strings + * o.map = function () { emit(this.name, 1) }; + * o.reduce = function (k, vals) { return vals.length }; + * User.mapReduce(o, function (err, results) { + * console.log(results) + * }) + * + * ####Other options: + * + * - `query` {Object} query filter object. + * - `sort` {Object} sort input objects using this key + * - `limit` {Number} max number of documents + * - `keeptemp` {Boolean, default:false} keep temporary data + * - `finalize` {Function} finalize function + * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution + * - `jsMode` {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X + * - `verbose` {Boolean, default:false} provide statistics on job execution time. + * - `readPreference` {String} + * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job. + * + * ####* out options: + * + * - `{inline:1}` the results are returned in an array + * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection + * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions + * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old + * + * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the [`lean` option](/docs/tutorials/lean.html); meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc). + * + * ####Example: + * + * const o = {}; + * // You can also define `map()` and `reduce()` as strings if your + * // linter complains about `emit()` not being defined + * o.map = 'function () { emit(this.name, 1) }'; + * o.reduce = 'function (k, vals) { return vals.length }'; + * o.out = { replace: 'createdCollectionNameForResults' } + * o.verbose = true; + * + * User.mapReduce(o, function (err, model, stats) { + * console.log('map reduce took %d ms', stats.processtime) + * model.find().where('value').gt(10).exec(function (err, docs) { + * console.log(docs); + * }); + * }) + * + * // `mapReduce()` returns a promise. However, ES6 promises can only + * // resolve to exactly one value, + * o.resolveToObject = true; + * const promise = User.mapReduce(o); + * promise.then(function (res) { + * const model = res.model; + * const stats = res.stats; + * console.log('map reduce took %d ms', stats.processtime) + * return model.find().where('value').gt(10).exec(); + * }).then(function (docs) { + * console.log(docs); + * }).then(null, handleError).end() + * + * @param {Object} o an object specifying map-reduce options + * @param {Function} [callback] optional callback + * @see http://www.mongodb.org/display/DOCS/MapReduce + * @return {Promise} + * @api public + */ - immediate(function () { - // If buffering is off, do this manually. - if (options._automatic && !model.collection.collection) { - model.collection.addQueue(create, []); - } else { - create(); - } - }); - } +Model.mapReduce = function mapReduce(o, callback) { + _checkContext(this, 'mapReduce'); - function _decorateDiscriminatorIndexOptions(model, indexOptions) { - // If the model is a discriminator and it has a unique index, add a - // partialFilterExpression by default so the unique index will only apply - // to that discriminator. - if ( - model.baseModelName != null && - !("partialFilterExpression" in indexOptions) && - !("sparse" in indexOptions) - ) { - const value = - (model.schema.discriminatorMapping && - model.schema.discriminatorMapping.value) || - model.modelName; - const discriminatorKey = model.schema.options.discriminatorKey; + callback = this.$handleCallbackError(callback); - indexOptions.partialFilterExpression = { [discriminatorKey]: value }; - } - return indexOptions; - } + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); - const safeDeprecationWarning = - "Mongoose: the `safe` option for `save()` is " + - "deprecated. Use the `w` option instead: http://bit.ly/mongoose-save"; + if (!Model.mapReduce.schema) { + const opts = { _id: false, id: false, strict: false }; + Model.mapReduce.schema = new Schema({}, opts); + } - const _handleSafe = util.deprecate(function _handleSafe(options) { - if (options.safe) { - if (typeof options.safe === "boolean") { - options.w = options.safe; - delete options.safe; - } - if (typeof options.safe === "object") { - options.w = options.safe.w; - options.j = options.safe.j; - options.wtimeout = options.safe.wtimeout; - delete options.safe; - } - } - }, safeDeprecationWarning); - - /** - * Schema the model uses. - * - * @property schema - * @receiver Model - * @api public - * @memberOf Model - */ - - Model.schema; - - /*! - * Connection instance the model uses. - * - * @property db - * @api public - * @memberOf Model - */ - - Model.db; - - /*! - * Collection the model uses. - * - * @property collection - * @api public - * @memberOf Model - */ - - Model.collection; - - /** - * Internal collection the model uses. - * - * @property collection - * @api private - * @memberOf Model - */ - Model.$__collection; - - /** - * Base Mongoose instance the model uses. - * - * @property base - * @api public - * @memberOf Model - */ - - Model.base; - - /** - * Registered discriminators for this model. - * - * @property discriminators - * @api public - * @memberOf Model - */ - - Model.discriminators; - - /** - * Translate any aliases fields/conditions so the final query or document object is pure - * - * ####Example: - * - * Character - * .find(Character.translateAliases({ - * '名': 'Eddard Stark' // Alias for 'name' - * }) - * .exec(function(err, characters) {}) - * - * ####Note: - * Only translate arguments of object type anything else is returned raw - * - * @param {Object} raw fields/conditions that may contain aliased keys - * @return {Object} the translated 'pure' fields/conditions - */ - Model.translateAliases = function translateAliases(fields) { - _checkContext(this, "translateAliases"); - - const translate = (key, value) => { - let alias; - const translated = []; - const fieldKeys = key.split("."); - let currentSchema = this.schema; - for (const i in fieldKeys) { - const name = fieldKeys[i]; - if (currentSchema && currentSchema.aliases[name]) { - alias = currentSchema.aliases[name]; - // Alias found, - translated.push(alias); - } else { - // Alias not found, so treat as un-aliased key - translated.push(name); - } + if (!o.out) o.out = { inline: 1 }; + if (o.verbose !== false) o.verbose = true; - // Check if aliased path is a schema - if (currentSchema && currentSchema.paths[alias]) { - currentSchema = currentSchema.paths[alias].schema; - } else currentSchema = null; - } + o.map = String(o.map); + o.reduce = String(o.reduce); - const translatedKey = translated.join("."); - if (fields instanceof Map) fields.set(translatedKey, value); - else fields[translatedKey] = value; + if (o.query) { + let q = new this.Query(o.query); + q.cast(this); + o.query = q._conditions; + q = undefined; + } - if (translatedKey !== key) { - // We'll be using the translated key instead - if (fields instanceof Map) { - // Delete from map - fields.delete(key); - } else { - // Delete from object - delete fields[key]; // We'll be using the translated key instead - } - } - return fields; - }; + this.$__collection.mapReduce(null, null, o, (err, res) => { + if (err) { + return cb(err); + } + if (res.collection) { + // returned a collection, convert to Model + const model = Model.compile('_mapreduce_' + res.collection.collectionName, + Model.mapReduce.schema, res.collection.collectionName, this.db, + this.base); - if (typeof fields === "object") { - // Fields is an object (query conditions or document fields) - if (fields instanceof Map) { - // A Map was supplied - for (const field of new Map(fields)) { - fields = translate(field[0], field[1]); - } - } else { - // Infer a regular object was supplied - for (const key of Object.keys(fields)) { - fields = translate(key, fields[key]); - if (key[0] === "$") { - if (Array.isArray(fields[key])) { - for (const i in fields[key]) { - // Recursively translate nested queries - fields[key][i] = this.translateAliases(fields[key][i]); - } - } - } - } - } + model._mapreduce = true; + res.model = model; - return fields; - } else { - // Don't know typeof fields - return fields; - } - }; + return cb(null, res); + } - /** - * Removes all documents that match `conditions` from the collection. - * To remove just the first document that matches `conditions`, set the `single` - * option to true. - * - * ####Example: - * - * const res = await Character.remove({ name: 'Eddard Stark' }); - * res.deletedCount; // Number of documents removed - * - * ####Note: - * - * This method sends a remove command directly to MongoDB, no Mongoose documents - * are involved. Because no Mongoose documents are involved, Mongoose does - * not execute [document middleware](/docs/middleware.html#types-of-middleware). - * - * @param {Object} conditions - * @param {Object} [options] - * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this operation. - * @param {Function} [callback] - * @return {Query} - * @api public - */ - - Model.remove = function remove(conditions, options, callback) { - _checkContext(this, "remove"); - - if (typeof conditions === "function") { - callback = conditions; - conditions = {}; - options = null; - } else if (typeof options === "function") { - callback = options; - options = null; - } - - // get the mongodb collection object - const mq = new this.Query({}, {}, this, this.$__collection); - mq.setOptions(options); - - callback = this.$handleCallbackError(callback); - - return mq.remove(conditions, callback); - }; + cb(null, res); + }); + }, this.events); +}; - /** - * Deletes the first document that matches `conditions` from the collection. - * Behaves like `remove()`, but deletes at most one document regardless of the - * `single` option. - * - * ####Example: - * - * await Character.deleteOne({ name: 'Eddard Stark' }); - * - * ####Note: - * - * This function triggers `deleteOne` query hooks. Read the - * [middleware docs](/docs/middleware.html#naming) to learn more. - * - * @param {Object} conditions - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @api public - */ - - Model.deleteOne = function deleteOne(conditions, options, callback) { - _checkContext(this, "deleteOne"); - - if (typeof conditions === "function") { - callback = conditions; - conditions = {}; - options = null; - } else if (typeof options === "function") { - callback = options; - options = null; - } - - const mq = new this.Query({}, {}, this, this.$__collection); - mq.setOptions(options); - - callback = this.$handleCallbackError(callback); - - return mq.deleteOne(conditions, callback); - }; +/** + * Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection. + * + * If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned. + * + * This function triggers the following middleware. + * + * - `aggregate()` + * + * ####Example: + * + * // Find the max balance of all accounts + * const res = await Users.aggregate([ + * { $group: { _id: null, maxBalance: { $max: '$balance' }}}, + * { $project: { _id: 0, maxBalance: 1 }} + * ]); + * + * console.log(res); // [ { maxBalance: 98000 } ] + * + * // Or use the aggregation pipeline builder. + * const res = await Users.aggregate(). + * group({ _id: null, maxBalance: { $max: '$balance' } }). + * project('-id maxBalance'). + * exec(); + * console.log(res); // [ { maxBalance: 98 } ] + * + * ####NOTE: + * + * - Mongoose does **not** cast aggregation pipelines to the model's schema because `$project` and `$group` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format. You can use the [mongoose-cast-aggregation plugin](https://github.com/AbdelrahmanHafez/mongoose-cast-aggregation) to enable minimal casting for aggregation pipelines. + * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). + * + * #### More About Aggregations: + * + * - [Mongoose `Aggregate`](/docs/api/aggregate.html) + * - [An Introduction to Mongoose Aggregate](https://masteringjs.io/tutorials/mongoose/aggregate) + * - [MongoDB Aggregation docs](http://docs.mongodb.org/manual/applications/aggregation/) + * + * @see Aggregate #aggregate_Aggregate + * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ + * @param {Array} [pipeline] aggregation pipeline as an array of objects + * @param {Object} [options] aggregation options + * @param {Function} [callback] + * @return {Aggregate} + * @api public + */ - /** - * Deletes all of the documents that match `conditions` from the collection. - * Behaves like `remove()`, but deletes all documents that match `conditions` - * regardless of the `single` option. - * - * ####Example: - * - * await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }); - * - * ####Note: - * - * This function triggers `deleteMany` query hooks. Read the - * [middleware docs](/docs/middleware.html#naming) to learn more. - * - * @param {Object} conditions - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @api public - */ - - Model.deleteMany = function deleteMany(conditions, options, callback) { - _checkContext(this, "deleteMany"); - - if (typeof conditions === "function") { - callback = conditions; - conditions = {}; - options = null; - } else if (typeof options === "function") { - callback = options; - options = null; - } - - const mq = new this.Query({}, {}, this, this.$__collection); - mq.setOptions(options); - - callback = this.$handleCallbackError(callback); - - return mq.deleteMany(conditions, callback); - }; +Model.aggregate = function aggregate(pipeline, options, callback) { + _checkContext(this, 'aggregate'); - /** - * Finds documents. - * - * Mongoose casts the `filter` to match the model's schema before the command is sent. - * See our [query casting tutorial](/docs/tutorials/query_casting.html) for - * more information on how Mongoose casts `filter`. - * - * ####Examples: - * - * // find all documents - * await MyModel.find({}); - * - * // find all documents named john and at least 18 - * await MyModel.find({ name: 'john', age: { $gte: 18 } }).exec(); - * - * // executes, passing results to callback - * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {}); - * - * // executes, name LIKE john and only selecting the "name" and "friends" fields - * await MyModel.find({ name: /john/i }, 'name friends').exec(); - * - * // passing options - * await MyModel.find({ name: /john/i }, null, { skip: 10 }).exec(); - * - * @param {Object|ObjectId} filter - * @param {Object|String|Array} [projection] optional fields to return, see [`Query.prototype.select()`](http://mongoosejs.com/docs/api.html#query_Query-select) - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @see field selection #query_Query-select - * @see query casting /docs/tutorials/query_casting.html - * @api public - */ - - Model.find = function find(conditions, projection, options, callback) { - _checkContext(this, "find"); - - if (typeof conditions === "function") { - callback = conditions; - conditions = {}; - projection = null; - options = null; - } else if (typeof projection === "function") { - callback = projection; - projection = null; - options = null; - } else if (typeof options === "function") { - callback = options; - options = null; - } - - const mq = new this.Query({}, {}, this, this.$__collection); - mq.select(projection); - - mq.setOptions(options); - if ( - this.schema.discriminatorMapping && - this.schema.discriminatorMapping.isRoot && - mq.selectedInclusively() - ) { - // Need to select discriminator key because original schema doesn't have it - mq.select(this.schema.options.discriminatorKey); - } + if (arguments.length > 3 || get(pipeline, 'constructor.name') === 'Object') { + throw new MongooseError('Mongoose 5.x disallows passing a spread of operators ' + + 'to `Model.aggregate()`. Instead of ' + + '`Model.aggregate({ $match }, { $skip })`, do ' + + '`Model.aggregate([{ $match }, { $skip }])`'); + } - callback = this.$handleCallbackError(callback); + if (typeof pipeline === 'function') { + callback = pipeline; + pipeline = []; + } - return mq.find(conditions, callback); - }; + if (typeof options === 'function') { + callback = options; + options = null; + } - /** - * Finds a single document by its _id field. `findById(id)` is almost* - * equivalent to `findOne({ _id: id })`. If you want to query by a document's - * `_id`, use `findById()` instead of `findOne()`. - * - * The `id` is cast based on the Schema before sending the command. - * - * This function triggers the following middleware. - * - * - `findOne()` - * - * \* Except for how it treats `undefined`. If you use `findOne()`, you'll see - * that `findOne(undefined)` and `findOne({ _id: undefined })` are equivalent - * to `findOne({})` and return arbitrary documents. However, mongoose - * translates `findById(undefined)` into `findOne({ _id: null })`. - * - * ####Example: - * - * // Find the adventure with the given `id`, or `null` if not found - * await Adventure.findById(id).exec(); - * - * // using callback - * Adventure.findById(id, function (err, adventure) {}); - * - * // select only the adventures name and length - * await Adventure.findById(id, 'name length').exec(); - * - * @param {Any} id value of `_id` to query by - * @param {Object|String|Array} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @see field selection #query_Query-select - * @see lean queries /docs/tutorials/lean.html - * @see findById in Mongoose https://masteringjs.io/tutorials/mongoose/find-by-id - * @api public - */ - - Model.findById = function findById(id, projection, options, callback) { - _checkContext(this, "findById"); - - if (typeof id === "undefined") { - id = null; - } - - callback = this.$handleCallbackError(callback); - - return this.findOne({ _id: id }, projection, options, callback); - }; + const aggregate = new Aggregate(pipeline || []); + aggregate.model(this); - /** - * Finds one document. - * - * The `conditions` are cast to their respective SchemaTypes before the command is sent. - * - * *Note:* `conditions` is optional, and if `conditions` is null or undefined, - * mongoose will send an empty `findOne` command to MongoDB, which will return - * an arbitrary document. If you're querying by `_id`, use `findById()` instead. - * - * ####Example: - * - * // Find one adventure whose `country` is 'Croatia', otherwise `null` - * await Adventure.findOne({ country: 'Croatia' }).exec(); - * - * // using callback - * Adventure.findOne({ country: 'Croatia' }, function (err, adventure) {}); - * - * // select only the adventures name and length - * await Adventure.findOne({ country: 'Croatia' }, 'name length').exec(); - * - * @param {Object} [conditions] - * @param {Object|String|Array} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @see field selection #query_Query-select - * @see lean queries /docs/tutorials/lean.html - * @api public - */ - - Model.findOne = function findOne( - conditions, - projection, - options, - callback - ) { - _checkContext(this, "findOne"); - if (typeof options === "function") { - callback = options; - options = null; - } else if (typeof projection === "function") { - callback = projection; - projection = null; - options = null; - } else if (typeof conditions === "function") { - callback = conditions; - conditions = {}; - projection = null; - options = null; - } - - const mq = new this.Query({}, {}, this, this.$__collection); - mq.select(projection); - - mq.setOptions(options); - if ( - this.schema.discriminatorMapping && - this.schema.discriminatorMapping.isRoot && - mq.selectedInclusively() - ) { - mq.select(this.schema.options.discriminatorKey); - } + if (options != null) { + aggregate.option(options); + } - callback = this.$handleCallbackError(callback); - return mq.findOne(conditions, callback); - }; + if (typeof callback === 'undefined') { + return aggregate; + } - /** - * Estimates the number of documents in the MongoDB collection. Faster than - * using `countDocuments()` for large collections because - * `estimatedDocumentCount()` uses collection metadata rather than scanning - * the entire collection. - * - * ####Example: - * - * const numAdventures = Adventure.estimatedDocumentCount(); - * - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} - * @api public - */ - - Model.estimatedDocumentCount = function estimatedDocumentCount( - options, - callback - ) { - _checkContext(this, "estimatedDocumentCount"); - - const mq = new this.Query({}, {}, this, this.$__collection); - - callback = this.$handleCallbackError(callback); - - return mq.estimatedDocumentCount(options, callback); - }; + callback = this.$handleCallbackError(callback); + callback = this.$wrapCallback(callback); - /** - * Counts number of documents matching `filter` in a database collection. - * - * ####Example: - * - * Adventure.countDocuments({ type: 'jungle' }, function (err, count) { - * console.log('there are %d jungle adventures', count); - * }); - * - * If you want to count all documents in a large collection, - * use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount) - * instead. If you call `countDocuments({})`, MongoDB will always execute - * a full collection scan and **not** use any indexes. - * - * The `countDocuments()` function is similar to `count()`, but there are a - * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). - * Below are the operators that `count()` supports but `countDocuments()` does not, - * and the suggested replacement: - * - * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/) - * - `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center) - * - `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere) - * - * @param {Object} filter - * @param {Function} [callback] - * @return {Query} - * @api public - */ - - Model.countDocuments = function countDocuments(conditions, callback) { - _checkContext(this, "countDocuments"); - - if (typeof conditions === "function") { - callback = conditions; - conditions = {}; - } - - const mq = new this.Query({}, {}, this, this.$__collection); - - callback = this.$handleCallbackError(callback); - - return mq.countDocuments(conditions, callback); - }; + aggregate.exec(callback); + return aggregate; +}; - /** - * Counts number of documents that match `filter` in a database collection. - * - * This method is deprecated. If you want to count the number of documents in - * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount) - * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#model_Model.countDocuments) function instead. - * - * ####Example: - * - * Adventure.count({ type: 'jungle' }, function (err, count) { - * if (err) .. - * console.log('there are %d jungle adventures', count); - * }); - * - * @deprecated - * @param {Object} filter - * @param {Function} [callback] - * @return {Query} - * @api public - */ - - Model.count = function count(conditions, callback) { - _checkContext(this, "count"); - - if (typeof conditions === "function") { - callback = conditions; - conditions = {}; - } - - const mq = new this.Query({}, {}, this, this.$__collection); - - callback = this.$handleCallbackError(callback); - - return mq.count(conditions, callback); - }; +/** + * Casts and validates the given object against this model's schema, passing the + * given `context` to custom validators. + * + * ####Example: + * + * const Model = mongoose.model('Test', Schema({ + * name: { type: String, required: true }, + * age: { type: Number, required: true } + * }); + * + * try { + * await Model.validate({ name: null }, ['name']) + * } catch (err) { + * err instanceof mongoose.Error.ValidationError; // true + * Object.keys(err.errors); // ['name'] + * } + * + * @param {Object} obj + * @param {Array} pathsToValidate + * @param {Object} [context] + * @param {Function} [callback] + * @return {Promise|undefined} + * @api public + */ - /** - * Creates a Query for a `distinct` operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) { - * if (err) return handleError(err); - * - * assert(Array.isArray(result)); - * console.log('unique urls with more than 100 clicks', result); - * }) - * - * const query = Link.distinct('url'); - * query.exec(callback); - * - * @param {String} field - * @param {Object} [conditions] optional - * @param {Function} [callback] - * @return {Query} - * @api public - */ - - Model.distinct = function distinct(field, conditions, callback) { - _checkContext(this, "distinct"); - - const mq = new this.Query({}, {}, this, this.$__collection); - - if (typeof conditions === "function") { - callback = conditions; - conditions = {}; - } - callback = this.$handleCallbackError(callback); - - return mq.distinct(field, conditions, callback); - }; +Model.validate = function validate(obj, pathsToValidate, context, callback) { + if ((arguments.length < 3) || (arguments.length === 3 && typeof arguments[2] === 'function')) { + // For convenience, if we're validating a document or an object, make `context` default to + // the model so users don't have to always pass `context`, re: gh-10132, gh-10346 + context = obj; + } - /** - * Creates a Query, applies the passed conditions, and returns the Query. - * - * For example, instead of writing: - * - * User.find({age: {$gte: 21, $lte: 65}}, callback); - * - * we can instead write: - * - * User.where('age').gte(21).lte(65).exec(callback); - * - * Since the Query class also supports `where` you can continue chaining - * - * User - * .where('age').gte(21).lte(65) - * .where('name', /^b/i) - * ... etc - * - * @param {String} path - * @param {Object} [val] optional value - * @return {Query} - * @api public - */ - - Model.where = function where(path, val) { - _checkContext(this, "where"); - - void val; // eslint - const mq = new this.Query({}, {}, this, this.$__collection).find({}); - return mq.where.apply(mq, arguments); - }; + return this.db.base._promiseOrCallback(callback, cb => { + const schema = this.schema; + let paths = Object.keys(schema.paths); - /** - * Creates a `Query` and specifies a `$where` condition. - * - * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model. - * - * Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {}); - * - * @param {String|Function} argument is a javascript string or anonymous function - * @method $where - * @memberOf Model - * @return {Query} - * @see Query.$where #query_Query-%24where - * @api public - */ - - Model.$where = function $where() { - _checkContext(this, "$where"); - - const mq = new this.Query({}, {}, this, this.$__collection).find({}); - return mq.$where.apply(mq, arguments); - }; + if (pathsToValidate != null) { + const _pathsToValidate = new Set(pathsToValidate); + paths = paths.filter(p => { + const pieces = p.split('.'); + let cur = pieces[0]; - /** - * Issues a mongodb findAndModify update command. - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes if `callback` is passed else a Query object is returned. - * - * ####Options: - * - * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `overwrite`: bool - if true, replace the entire document. - * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()` - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findOneAndUpdate(conditions, update, options, callback) // executes - * A.findOneAndUpdate(conditions, update, options) // returns Query - * A.findOneAndUpdate(conditions, update, callback) // executes - * A.findOneAndUpdate(conditions, update) // returns Query - * A.findOneAndUpdate() // returns Query - * - * ####Note: - * - * All top level update keys which are not `atomic` operation names are treated as set operations: - * - * ####Example: - * - * const query = { name: 'borne' }; - * Model.findOneAndUpdate(query, { name: 'jason bourne' }, options, callback) - * - * // is sent as - * Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback) - * - * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`. - * - * ####Note: - * - * Values are cast to their appropriate types when using the findAndModify helpers. - * However, the below are not executed by default. - * - * - defaults. Use the `setDefaultsOnInsert` option to override. - * - * `findAndModify` helpers support limited validation. You can - * enable these by setting the `runValidators` options, - * respectively. - * - * If you need full-fledged validation, use the traditional approach of first - * retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.name = 'jason bourne'; - * doc.save(callback); - * }); - * - * @param {Object} [conditions] - * @param {Object} [update] - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. To change the default to `true`, use `mongoose.set('returnOriginal', false);`. - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. - * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `update`, Mongoose will wrap `update` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. An alternative to this would be using [Model.findOneAndReplace(conditions, update, options, callback)](https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndReplace). - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object|String|Array} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) - * @param {Function} [callback] - * @return {Query} - * @see Tutorial /docs/tutorials/findoneandupdate.html - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - - Model.findOneAndUpdate = function ( - conditions, - update, - options, - callback - ) { - _checkContext(this, "findOneAndUpdate"); - - if (typeof options === "function") { - callback = options; - options = null; - } else if (arguments.length === 1) { - if (typeof conditions === "function") { - const msg = - "Model.findOneAndUpdate(): First argument must not be a function.\n\n" + - " " + - this.modelName + - ".findOneAndUpdate(conditions, update, options, callback)\n" + - " " + - this.modelName + - ".findOneAndUpdate(conditions, update, options)\n" + - " " + - this.modelName + - ".findOneAndUpdate(conditions, update)\n" + - " " + - this.modelName + - ".findOneAndUpdate(update)\n" + - " " + - this.modelName + - ".findOneAndUpdate()\n"; - throw new TypeError(msg); + for (const piece of pieces) { + if (_pathsToValidate.has(cur)) { + return true; } - update = conditions; - conditions = undefined; + cur += '.' + piece; } - callback = this.$handleCallbackError(callback); - let fields; - if (options) { - fields = options.fields || options.projection; - } + return _pathsToValidate.has(p); + }); + } - update = utils.clone(update, { - depopulate: true, - _isNested: true, - }); + for (const path of paths) { + const schemaType = schema.path(path); + if (!schemaType || !schemaType.$isMongooseArray) { + continue; + } - _decorateUpdateWithVersionKey( - update, - options, - this.schema.options.versionKey - ); + const val = get(obj, path); + pushNestedArrayPaths(val, path); + } - const mq = new this.Query({}, {}, this, this.$__collection); - mq.select(fields); + let remaining = paths.length; + let error = null; - return mq.findOneAndUpdate(conditions, update, options, callback); - }; + for (const path of paths) { + const schemaType = schema.path(path); + if (schemaType == null) { + _checkDone(); + continue; + } - /*! - * Decorate the update with a version key, if necessary - */ + const pieces = path.split('.'); + let cur = obj; + for (let i = 0; i < pieces.length - 1; ++i) { + cur = cur[pieces[i]]; + } - function _decorateUpdateWithVersionKey(update, options, versionKey) { - if (!versionKey || !get(options, "upsert", false)) { - return; - } + let val = get(obj, path, void 0); - const updatedPaths = modifiedPaths(update); - if (!updatedPaths[versionKey]) { - if (options.overwrite) { - update[versionKey] = 0; - } else { - if (!update.$setOnInsert) { - update.$setOnInsert = {}; - } - update.$setOnInsert[versionKey] = 0; - } + if (val != null) { + try { + val = schemaType.cast(val); + cur[pieces[pieces.length - 1]] = val; + } catch (err) { + error = error || new ValidationError(); + error.addError(path, err); + + _checkDone(); + continue; } } - /** - * Issues a mongodb findAndModify update command by a document's _id field. - * `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`. - * - * Finds a matching document, updates it according to the `update` arg, - * passing any `options`, and returns the found document (if any) to the - * callback. The query executes if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndUpdate()` - * - * ####Options: - * - * - `new`: bool - true to return the modified document rather than the original. defaults to false - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `select`: sets the document fields to return - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findByIdAndUpdate(id, update, options, callback) // executes - * A.findByIdAndUpdate(id, update, options) // returns Query - * A.findByIdAndUpdate(id, update, callback) // executes - * A.findByIdAndUpdate(id, update) // returns Query - * A.findByIdAndUpdate() // returns Query - * - * ####Note: - * - * All top level update keys which are not `atomic` operation names are treated as set operations: - * - * ####Example: - * - * Model.findByIdAndUpdate(id, { name: 'jason bourne' }, options, callback) - * - * // is sent as - * Model.findByIdAndUpdate(id, { $set: { name: 'jason bourne' }}, options, callback) - * - * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`. - * - * ####Note: - * - * Values are cast to their appropriate types when using the findAndModify helpers. - * However, the below are not executed by default. - * - * - defaults. Use the `setDefaultsOnInsert` option to override. - * - * `findAndModify` helpers support limited validation. You can - * enable these by setting the `runValidators` options, - * respectively. - * - * If you need full-fledged validation, use the traditional approach of first - * retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.name = 'jason bourne'; - * doc.save(callback); - * }); - * - * @param {Object|Number|String} id value of `_id` to query by - * @param {Object} [update] - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean} [options.new=false] By default, `findByIdAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. To change the default to `true`, use `mongoose.set('returnOriginal', false);`. - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. - * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `update`, Mongoose will wrap `update` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. An alternative to this would be using [Model.findOneAndReplace({ _id: id }, update, options, callback)](https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndReplace). - * @param {Function} [callback] - * @return {Query} - * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - - Model.findByIdAndUpdate = function (id, update, options, callback) { - _checkContext(this, "findByIdAndUpdate"); - - callback = this.$handleCallbackError(callback); - if (arguments.length === 1) { - if (typeof id === "function") { - const msg = - "Model.findByIdAndUpdate(): First argument must not be a function.\n\n" + - " " + - this.modelName + - ".findByIdAndUpdate(id, callback)\n" + - " " + - this.modelName + - ".findByIdAndUpdate(id)\n" + - " " + - this.modelName + - ".findByIdAndUpdate()\n"; - throw new TypeError(msg); + schemaType.doValidate(val, err => { + if (err) { + error = error || new ValidationError(); + if (err instanceof ValidationError) { + for (const _err of Object.keys(err.errors)) { + error.addError(`${path}.${err.errors[_err].path}`, _err); + } + } else { + error.addError(err.path, err); } - return this.findOneAndUpdate({ _id: id }, undefined); - } - - // if a model is passed in instead of an id - if (id instanceof Document) { - id = id._id; } + _checkDone(); + }, context, { path: path }); + } - return this.findOneAndUpdate.call( - this, - { _id: id }, - update, - options, - callback - ); - }; - - /** - * Issue a MongoDB `findOneAndDelete()` command. - * - * Finds a matching document, removes it, and passes the found document - * (if any) to the callback. - * - * Executes the query if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndDelete()` - * - * This function differs slightly from `Model.findOneAndRemove()` in that - * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/), - * as opposed to a `findOneAndDelete()` command. For most mongoose use cases, - * this distinction is purely pedantic. You should use `findOneAndDelete()` - * unless you have a good reason not to. - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `select`: sets the document fields to return, ex. `{ projection: { _id: 0 } }` - * - `projection`: equivalent to `select` - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findOneAndDelete(conditions, options, callback) // executes - * A.findOneAndDelete(conditions, options) // return Query - * A.findOneAndDelete(conditions, callback) // executes - * A.findOneAndDelete(conditions) // returns Query - * A.findOneAndDelete() // returns Query - * - * Values are cast to their appropriate types when using the findAndModify helpers. - * However, the below are not executed by default. - * - * - defaults. Use the `setDefaultsOnInsert` option to override. - * - * `findAndModify` helpers support limited validation. You can - * enable these by setting the `runValidators` options, - * respectively. - * - * If you need full-fledged validation, use the traditional approach of first - * retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.name = 'jason bourne'; - * doc.save(callback); - * }); - * - * @param {Object} conditions - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Object|String|Array} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Function} [callback] - * @return {Query} - * @api public - */ - - Model.findOneAndDelete = function (conditions, options, callback) { - _checkContext(this, "findOneAndDelete"); - - if (arguments.length === 1 && typeof conditions === "function") { - const msg = - "Model.findOneAndDelete(): First argument must not be a function.\n\n" + - " " + - this.modelName + - ".findOneAndDelete(conditions, callback)\n" + - " " + - this.modelName + - ".findOneAndDelete(conditions)\n" + - " " + - this.modelName + - ".findOneAndDelete()\n"; - throw new TypeError(msg); - } - - if (typeof options === "function") { - callback = options; - options = undefined; - } - callback = this.$handleCallbackError(callback); - - let fields; - if (options) { - fields = options.select; - options.select = undefined; - } - - const mq = new this.Query({}, {}, this, this.$__collection); - mq.select(fields); - - return mq.findOneAndDelete(conditions, options, callback); - }; - - /** - * Issue a MongoDB `findOneAndDelete()` command by a document's _id field. - * In other words, `findByIdAndDelete(id)` is a shorthand for - * `findOneAndDelete({ _id: id })`. - * - * This function triggers the following middleware. - * - * - `findOneAndDelete()` - * - * @param {Object|Number|String} id value of `_id` to query by - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Function} [callback] - * @return {Query} - * @see Model.findOneAndRemove #model_Model.findOneAndRemove - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - */ - - Model.findByIdAndDelete = function (id, options, callback) { - _checkContext(this, "findByIdAndDelete"); - - if (arguments.length === 1 && typeof id === "function") { - const msg = - "Model.findByIdAndDelete(): First argument must not be a function.\n\n" + - " " + - this.modelName + - ".findByIdAndDelete(id, callback)\n" + - " " + - this.modelName + - ".findByIdAndDelete(id)\n" + - " " + - this.modelName + - ".findByIdAndDelete()\n"; - throw new TypeError(msg); - } - callback = this.$handleCallbackError(callback); - - return this.findOneAndDelete({ _id: id }, options, callback); - }; - - /** - * Issue a MongoDB `findOneAndReplace()` command. - * - * Finds a matching document, replaces it with the provided doc, and passes the - * returned doc to the callback. - * - * Executes the query if `callback` is passed. - * - * This function triggers the following query middleware. - * - * - `findOneAndReplace()` - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `select`: sets the document fields to return - * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }` - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findOneAndReplace(conditions, options, callback) // executes - * A.findOneAndReplace(conditions, options) // return Query - * A.findOneAndReplace(conditions, callback) // executes - * A.findOneAndReplace(conditions) // returns Query - * A.findOneAndReplace() // returns Query - * - * Values are cast to their appropriate types when using the findAndModify helpers. - * However, the below are not executed by default. - * - * - defaults. Use the `setDefaultsOnInsert` option to override. - * - * @param {Object} filter Replace the first document that matches this filter - * @param {Object} [replacement] Replace with this document - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean} [options.new=false] By default, `findOneAndReplace()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndReplace()` will instead give you the object after `update` was applied. To change the default to `true`, use `mongoose.set('returnOriginal', false);`. - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. - * @param {Object|String|Array} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) - * @param {Function} [callback] - * @return {Query} - * @api public - */ - - Model.findOneAndReplace = function ( - filter, - replacement, - options, - callback - ) { - _checkContext(this, "findOneAndReplace"); - - if (arguments.length === 1 && typeof filter === "function") { - const msg = - "Model.findOneAndReplace(): First argument must not be a function.\n\n" + - " " + - this.modelName + - ".findOneAndReplace(conditions, callback)\n" + - " " + - this.modelName + - ".findOneAndReplace(conditions)\n" + - " " + - this.modelName + - ".findOneAndReplace()\n"; - throw new TypeError(msg); - } - - if (arguments.length === 3 && typeof options === "function") { - callback = options; - options = replacement; - replacement = void 0; - } - if (arguments.length === 2 && typeof replacement === "function") { - callback = replacement; - replacement = void 0; - options = void 0; - } - callback = this.$handleCallbackError(callback); - - let fields; - if (options) { - fields = options.select; - options.select = undefined; - } - - const mq = new this.Query({}, {}, this, this.$__collection); - mq.select(fields); - - return mq.findOneAndReplace(filter, replacement, options, callback); - }; + function pushNestedArrayPaths(nestedArray, path) { + if (nestedArray == null) { + return; + } - /** - * Issue a mongodb findAndModify remove command. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. - * - * Executes the query if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndRemove()` - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `select`: sets the document fields to return - * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }` - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findOneAndRemove(conditions, options, callback) // executes - * A.findOneAndRemove(conditions, options) // return Query - * A.findOneAndRemove(conditions, callback) // executes - * A.findOneAndRemove(conditions) // returns Query - * A.findOneAndRemove() // returns Query - * - * Values are cast to their appropriate types when using the findAndModify helpers. - * However, the below are not executed by default. - * - * - defaults. Use the `setDefaultsOnInsert` option to override. - * - * `findAndModify` helpers support limited validation. You can - * enable these by setting the `runValidators` options, - * respectively. - * - * If you need full-fledged validation, use the traditional approach of first - * retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.name = 'jason bourne'; - * doc.save(callback); - * }); - * - * @param {Object} conditions - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Object|String|Array} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) - * @param {Function} [callback] - * @return {Query} - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - - Model.findOneAndRemove = function (conditions, options, callback) { - _checkContext(this, "findOneAndRemove"); - - if (arguments.length === 1 && typeof conditions === "function") { - const msg = - "Model.findOneAndRemove(): First argument must not be a function.\n\n" + - " " + - this.modelName + - ".findOneAndRemove(conditions, callback)\n" + - " " + - this.modelName + - ".findOneAndRemove(conditions)\n" + - " " + - this.modelName + - ".findOneAndRemove()\n"; - throw new TypeError(msg); - } - - if (typeof options === "function") { - callback = options; - options = undefined; - } - callback = this.$handleCallbackError(callback); - - let fields; - if (options) { - fields = options.select; - options.select = undefined; - } - - const mq = new this.Query({}, {}, this, this.$__collection); - mq.select(fields); - - return mq.findOneAndRemove(conditions, options, callback); - }; + for (let i = 0; i < nestedArray.length; ++i) { + if (Array.isArray(nestedArray[i])) { + pushNestedArrayPaths(nestedArray[i], path + '.' + i); + } else { + paths.push(path + '.' + i); + } + } + } - /** - * Issue a mongodb findAndModify remove command by a document's _id field. `findByIdAndRemove(id, ...)` is equivalent to `findOneAndRemove({ _id: id }, ...)`. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. - * - * Executes the query if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndRemove()` - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `select`: sets the document fields to return - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findByIdAndRemove(id, options, callback) // executes - * A.findByIdAndRemove(id, options) // return Query - * A.findByIdAndRemove(id, callback) // executes - * A.findByIdAndRemove(id) // returns Query - * A.findByIdAndRemove() // returns Query - * - * @param {Object|Number|String} id value of `_id` to query by - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Object|String|Array} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) - * @param {Function} [callback] - * @return {Query} - * @see Model.findOneAndRemove #model_Model.findOneAndRemove - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - */ - - Model.findByIdAndRemove = function (id, options, callback) { - _checkContext(this, "findByIdAndRemove"); - - if (arguments.length === 1 && typeof id === "function") { - const msg = - "Model.findByIdAndRemove(): First argument must not be a function.\n\n" + - " " + - this.modelName + - ".findByIdAndRemove(id, callback)\n" + - " " + - this.modelName + - ".findByIdAndRemove(id)\n" + - " " + - this.modelName + - ".findByIdAndRemove()\n"; - throw new TypeError(msg); - } - callback = this.$handleCallbackError(callback); - - return this.findOneAndRemove({ _id: id }, options, callback); - }; + function _checkDone() { + if (--remaining <= 0) { + return cb(error); + } + } + }); +}; - /** - * Shortcut for saving one or more documents to the database. - * `MyModel.create(docs)` does `new MyModel(doc).save()` for every doc in - * docs. - * - * This function triggers the following middleware. - * - * - `save()` - * - * ####Example: - * - * // Insert one new `Character` document - * await Character.create({ name: 'Jean-Luc Picard' }); - * - * // Insert multiple new `Character` documents - * await Character.create([{ name: 'Will Riker' }, { name: 'Geordi LaForge' }]); - * - * // Create a new character within a transaction. Note that you **must** - * // pass an array as the first parameter to `create()` if you want to - * // specify options. - * await Character.create([{ name: 'Jean-Luc Picard' }], { session }); - * - * @param {Array|Object} docs Documents to insert, as a spread or array - * @param {Object} [options] Options passed down to `save()`. To specify `options`, `docs` **must** be an array, not a spread. - * @param {Function} [callback] callback - * @return {Promise} - * @api public - */ - - Model.create = function create(doc, options, callback) { - _checkContext(this, "create"); - - let args; - let cb; - const discriminatorKey = this.schema.options.discriminatorKey; - - if (Array.isArray(doc)) { - args = doc; - cb = typeof options === "function" ? options : callback; - options = - options != null && typeof options === "object" ? options : {}; - } else { - const last = arguments[arguments.length - 1]; - options = {}; - // Handle falsy callbacks re: #5061 - if (typeof last === "function" || (arguments.length > 1 && !last)) { - cb = last; - args = utils.args(arguments, 0, arguments.length - 1); - } else { - args = utils.args(arguments); - } +/** + * Populates document references. + * + * Changed in Mongoose 6: the model you call `populate()` on should be the + * "local field" model, **not** the "foreign field" model. + * + * ####Available top-level options: + * + * - path: space delimited path(s) to populate + * - select: optional fields to select + * - match: optional query conditions to match + * - model: optional name of the model to use for population + * - options: optional query options like sort, limit, etc + * - justOne: optional boolean, if true Mongoose will always set `path` to an array. Inferred from schema by default. + * - strictPopulate: optional boolean, set to `false` to allow populating paths that aren't in the schema. + * + * ####Examples: + * + * const Dog = mongoose.model('Dog', new Schema({ name: String, breed: String })); + * const Person = mongoose.model('Person', new Schema({ + * name: String, + * pet: { type: mongoose.ObjectId, ref: 'Dog' } + * })); + * + * const pets = await Pet.create([ + * { name: 'Daisy', breed: 'Beagle' }, + * { name: 'Einstein', breed: 'Catalan Sheepdog' } + * ]); + * + * // populate many plain objects + * const users = [ + * { name: 'John Wick', dog: pets[0]._id }, + * { name: 'Doc Brown', dog: pets[1]._id } + * ]; + * await User.populate(users, { path: 'dog', select: 'name' }); + * users[0].dog.name; // 'Daisy' + * users[0].dog.breed; // undefined because of `select` + * + * @param {Document|Array} docs Either a single document or array of documents to populate. + * @param {Object|String} options Either the paths to populate or an object specifying all parameters + * @param {string} [options.path=null] The path to populate. + * @param {boolean} [options.retainNullValues=false] By default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries. + * @param {boolean} [options.getters=false] If true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options). + * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them. + * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object. + * @param {Boolean} [options.skipInvalidIds=false] By default, Mongoose throws a cast error if `localField` and `foreignField` schemas don't line up. If you enable this option, Mongoose will instead filter out any `localField` properties that cannot be casted to `foreignField`'s schema type. + * @param {Number} [options.perDocumentLimit=null] For legacy reasons, `limit` with `populate()` may give incorrect results because it only executes a single query for every document being populated. If you set `perDocumentLimit`, Mongoose will ensure correct `limit` per document by executing a separate query for each document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })` will execute 2 additional queries if `.find()` returns 2 documents. + * @param {Boolean} [options.strictPopulate=true] Set to false to allow populating paths that aren't defined in the given model's schema. + * @param {Object} [options.options=null] Additional options like `limit` and `lean`. + * @param {Function} [options.transform=null] Function that Mongoose will call on every populated document that allows you to transform the populated document. + * @param {Function} [callback(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. + * @return {Promise} + * @api public + */ - if ( - args.length === 2 && - args[0] != null && - args[1] != null && - args[0].session == null && - getConstructorName(last.session) === "ClientSession" && - !this.schema.path("session") - ) { - // Probably means the user is running into the common mistake of trying - // to use a spread to specify options, see gh-7535 - console.warn( - "WARNING: to pass a `session` to `Model.create()` in " + - "Mongoose, you **must** pass an array as the first argument. See: " + - "https://mongoosejs.com/docs/api.html#model_Model.create" - ); - } - } +Model.populate = function(docs, paths, callback) { + _checkContext(this, 'populate'); - return this.db.base._promiseOrCallback( - cb, - (cb) => { - cb = this.$wrapCallback(cb); - if (args.length === 0) { - return cb(null); - } - - const toExecute = []; - let firstError; - args.forEach((doc) => { - toExecute.push((callback) => { - const Model = - this.discriminators && doc[discriminatorKey] != null - ? this.discriminators[doc[discriminatorKey]] || - getDiscriminatorByValue( - this.discriminators, - doc[discriminatorKey] - ) - : this; - if (Model == null) { - throw new MongooseError( - `Discriminator "${doc[discriminatorKey]}" not ` + - `found for model "${this.modelName}"` - ); - } - let toSave = doc; - const callbackWrapper = (error, doc) => { - if (error) { - if (!firstError) { - firstError = error; - } - return callback(null, { error: error }); - } - callback(null, { doc: doc }); - }; + const _this = this; - if (!(toSave instanceof Model)) { - try { - toSave = new Model(toSave); - } catch (error) { - return callbackWrapper(error); - } - } + // normalized paths + paths = utils.populate(paths); - toSave.save(options, callbackWrapper); - }); - }); + // data that should persist across subPopulate calls + const cache = {}; - let numFns = toExecute.length; - if (numFns === 0) { - return cb(null, []); - } - const _done = (error, res) => { - const savedDocs = []; - const len = res.length; - for (let i = 0; i < len; ++i) { - if (res[i].doc) { - savedDocs.push(res[i].doc); - } - } + callback = this.$handleCallbackError(callback); + return this.db.base._promiseOrCallback(callback, cb => { + cb = this.$wrapCallback(cb); + _populate(_this, docs, paths, cache, cb); + }, this.events); +}; - if (firstError) { - return cb(firstError, savedDocs); - } +/*! + * Populate helper + * + * @param {Model} model the model to use + * @param {Document|Array} docs Either a single document or array of documents to populate. + * @param {Object} paths + * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. + * @return {Function} + * @api private + */ - if (doc instanceof Array) { - cb(null, savedDocs); - } else { - cb.apply(this, [null].concat(savedDocs)); - } - }; +function _populate(model, docs, paths, cache, callback) { + let pending = paths.length; + if (paths.length === 0) { + return callback(null, docs); + } + // each path has its own query options and must be executed separately + for (const path of paths) { + populate(model, docs, path, next); + } - const _res = []; - toExecute.forEach((fn, i) => { - fn((err, res) => { - _res[i] = res; - if (--numFns <= 0) { - return _done(null, _res); - } - }); - }); - }, - this.events - ); - }; + function next(err) { + if (err) { + return callback(err, null); + } + if (--pending) { + return; + } + callback(null, docs); + } +} - /** - * _Requires a replica set running MongoDB >= 3.6.0._ Watches the - * underlying collection for changes using - * [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/). - * - * This function does **not** trigger any middleware. In particular, it - * does **not** trigger aggregate middleware. - * - * The ChangeStream object is an event emitter that emits the following events: - * - * - 'change': A change occurred, see below example - * - 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow [this GitHub issue](https://github.com/Automattic/mongoose/issues/6799) for updates. - * - 'end': Emitted if the underlying stream is closed - * - 'close': Emitted if the underlying stream is closed - * - * ####Example: - * - * const doc = await Person.create({ name: 'Ned Stark' }); - * const changeStream = Person.watch().on('change', change => console.log(change)); - * // Will print from the above `console.log()`: - * // { _id: { _data: ... }, - * // operationType: 'delete', - * // ns: { db: 'mydb', coll: 'Person' }, - * // documentKey: { _id: 5a51b125c5500f5aa094c7bd } } - * await doc.remove(); - * - * @param {Array} [pipeline] - * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#watch) - * @return {ChangeStream} mongoose-specific change stream wrapper, inherits from EventEmitter - * @api public - */ - - Model.watch = function (pipeline, options) { - _checkContext(this, "watch"); - - const changeStreamThunk = (cb) => { - if (this.$__collection.buffer) { - this.$__collection.addQueue(() => { - if (this.closed) { - return; - } - const driverChangeStream = this.$__collection.watch( - pipeline, - options - ); - cb(null, driverChangeStream); - }); - } else { - const driverChangeStream = this.$__collection.watch( - pipeline, - options - ); - cb(null, driverChangeStream); - } - }; +/*! + * Populates `docs` + */ +const excludeIdReg = /\s?-_id\s?/; +const excludeIdRegGlobal = /\s?-_id\s?/g; - return new ChangeStream(changeStreamThunk, pipeline, options); - }; +function populate(model, docs, options, callback) { + const populateOptions = { ...options }; + if (model.base.options.strictPopulate != null && options.strictPopulate == null) { + populateOptions.strictPopulate = model.base.options.strictPopulate; + } + // normalize single / multiple docs passed + if (!Array.isArray(docs)) { + docs = [docs]; + } + if (docs.length === 0 || docs.every(utils.isNullOrUndefined)) { + return callback(); + } - /** - * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) - * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), - * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). - * - * Calling `MyModel.startSession()` is equivalent to calling `MyModel.db.startSession()`. - * - * This function does not trigger any middleware. - * - * ####Example: - * - * const session = await Person.startSession(); - * let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session }); - * await doc.remove(); - * // `doc` will always be null, even if reading from a replica set - * // secondary. Without causal consistency, it is possible to - * // get a doc back from the below query if the query reads from a - * // secondary that is experiencing replication lag. - * doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' }); - * - * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) - * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency - * @param {Function} [callback] - * @return {Promise} promise that resolves to a MongoDB driver `ClientSession` - * @api public - */ - - Model.startSession = function () { - _checkContext(this, "startSession"); - - return this.db.startSession.apply(this.db, arguments); - }; + const modelsMap = getModelsMapForPopulate(model, docs, populateOptions); + if (modelsMap instanceof MongooseError) { + return immediate(function() { + callback(modelsMap); + }); + } - /** - * Shortcut for validating an array of documents and inserting them into - * MongoDB if they're all valid. This function is faster than `.create()` - * because it only sends one operation to the server, rather than one for each - * document. - * - * Mongoose always validates each document **before** sending `insertMany` - * to MongoDB. So if one document has a validation error, no documents will - * be saved, unless you set - * [the `ordered` option to false](https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/#error-handling). - * - * This function does **not** trigger save middleware. - * - * This function triggers the following middleware. - * - * - `insertMany()` - * - * ####Example: - * - * const arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }]; - * Movies.insertMany(arr, function(error, docs) {}); - * - * @param {Array|Object|*} doc(s) - * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertMany) - * @param {Boolean} [options.ordered = true] if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An `insertMany()` with `ordered = false` is called an "unordered" `insertMany()`. - * @param {Boolean} [options.rawResult = false] if false, the returned promise resolves to the documents that passed mongoose document validation. If `true`, will return the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertWriteOpCallback) with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`. - * @param {Boolean} [options.lean = false] if `true`, skips hydrating and validating the documents. This option is useful if you need the extra performance, but Mongoose won't validate the documents before inserting. - * @param {Number} [options.limit = null] this limits the number of documents being processed (validation/casting) by mongoose in parallel, this does **NOT** send the documents in batches to MongoDB. Use this option if you're processing a large number of documents and your app is running out of memory. - * @param {String|Object|Array} [options.populate = null] populates the result documents. This option is a no-op if `rawResult` is set. - * @param {Function} [callback] callback - * @return {Promise} resolving to the raw result from the MongoDB driver if `options.rawResult` was `true`, or the documents that passed validation, otherwise - * @api public - */ - - Model.insertMany = function (arr, options, callback) { - _checkContext(this, "insertMany"); - - if (typeof options === "function") { - callback = options; - options = null; - } - return this.db.base._promiseOrCallback( - callback, - (cb) => { - this.$__insertMany(arr, options, cb); - }, - this.events - ); - }; + const len = modelsMap.length; + let vals = []; - /*! - * ignore - */ + function flatten(item) { + // no need to include undefined values in our query + return undefined !== item; + } - Model.$__insertMany = function (arr, options, callback) { - const _this = this; - if (typeof options === "function") { - callback = options; - options = null; - } - if (callback) { - callback = this.$handleCallbackError(callback); - callback = this.$wrapCallback(callback); - } - callback = callback || utils.noop; - options = options || {}; - const limit = get(options, "limit", 1000); - const rawResult = get(options, "rawResult", false); - const ordered = get(options, "ordered", true); - const lean = get(options, "lean", false); + let _remaining = len; + let hasOne = false; + const params = []; + for (let i = 0; i < len; ++i) { + const mod = modelsMap[i]; + let select = mod.options.select; + let ids = utils.array.flatten(mod.ids, flatten); + ids = utils.array.unique(ids); + + const assignmentOpts = {}; + assignmentOpts.sort = get(mod, 'options.options.sort', void 0); + assignmentOpts.excludeId = excludeIdReg.test(select) || (select && select._id === 0); + + if (ids.length === 0 || ids.every(utils.isNullOrUndefined)) { + // Ensure that we set to 0 or empty array even + // if we don't actually execute a query to make sure there's a value + // and we know this path was populated for future sets. See gh-7731, gh-8230 + --_remaining; + _assign(model, [], mod, assignmentOpts); + continue; + } - if (!Array.isArray(arr)) { - arr = [arr]; - } + hasOne = true; + const match = createPopulateQueryFilter(ids, mod.match, mod.foreignField, mod.model, mod.options.skipInvalidIds); - const validationErrors = []; - const toExecute = arr.map((doc) => (callback) => { - if (!(doc instanceof _this)) { - try { - doc = new _this(doc); - } catch (err) { - return callback(err); - } - } - if (options.session != null) { - doc.$session(options.session); - } - // If option `lean` is set to true bypass validation - if (lean) { - // we have to execute callback at the nextTick to be compatible - // with parallelLimit, as `results` variable has TDZ issue if we - // execute the callback synchronously - return immediate(() => callback(null, doc)); - } - doc.validate({ __noPromise: true }, function (error) { - if (error) { - // Option `ordered` signals that insert should be continued after reaching - // a failing insert. Therefore we delegate "null", meaning the validation - // failed. It's up to the next function to filter out all failed models - if (ordered === false) { - validationErrors.push(error); - return callback(null, null); - } - return callback(error); - } - callback(null, doc); - }); - }); + if (assignmentOpts.excludeId) { + // override the exclusion from the query so we can use the _id + // for document matching during assignment. we'll delete the + // _id back off before returning the result. + if (typeof select === 'string') { + select = select.replace(excludeIdRegGlobal, ' '); + } else { + // preserve original select conditions by copying + select = utils.object.shallowCopy(select); + delete select._id; + } + } - parallelLimit(toExecute, limit, function (error, docs) { - if (error) { - callback(error, null); - return; - } - // We filter all failed pre-validations by removing nulls - const docAttributes = docs.filter(function (doc) { - return doc != null; - }); - // Quickly escape while there aren't any valid docAttributes - if (docAttributes.length < 1) { - if (rawResult) { - const res = { - mongoose: { - validationErrors: validationErrors, - }, - }; - return callback(null, res); - } - callback(null, []); - return; - } - const docObjects = docAttributes.map(function (doc) { - if (doc.$__schema.options.versionKey) { - doc[doc.$__schema.options.versionKey] = 0; - } - if (doc.initializeTimestamps) { - return doc - .initializeTimestamps() - .toObject(internalToObjectOptions); - } - return doc.toObject(internalToObjectOptions); - }); + if (mod.options.options && mod.options.options.limit != null) { + assignmentOpts.originalLimit = mod.options.options.limit; + } else if (mod.options.limit != null) { + assignmentOpts.originalLimit = mod.options.limit; + } + params.push([mod, match, select, assignmentOpts, _next]); + } + if (!hasOne) { + // If models but no docs, skip further deep populate. + if (modelsMap.length > 0) { + return callback(); + } + // If no models to populate but we have a nested populate, + // keep trying, re: gh-8946 + if (options.populate != null) { + const opts = utils.populate(options.populate).map(pop => Object.assign({}, pop, { + path: options.path + '.' + pop.path + })); + return model.populate(docs, opts, callback); + } + return callback(); + } - _this.$__collection.insertMany( - docObjects, - options, - function (error, res) { - if (error) { - // `writeErrors` is a property reported by the MongoDB driver, - // just not if there's only 1 error. - if ( - error.writeErrors == null && - get(error, "result.result.writeErrors") != null - ) { - error.writeErrors = error.result.result.writeErrors; - } + for (const arr of params) { + _execPopulateQuery.apply(null, arr); + } + function _next(err, valsFromDb) { + if (err != null) { + return callback(err, null); + } + vals = vals.concat(valsFromDb); + if (--_remaining === 0) { + _done(); + } + } - // `insertedDocs` is a Mongoose-specific property - const erroredIndexes = new Set( - get(error, "writeErrors", []).map((err) => err.index) - ); + function _done() { + for (const arr of params) { + const mod = arr[0]; + const assignmentOpts = arr[3]; + for (const val of vals) { + mod.options._childDocs.push(val); + } + _assign(model, vals, mod, assignmentOpts); + } - let firstErroredIndex = -1; - error.insertedDocs = docAttributes - .filter((doc, i) => { - const isErrored = erroredIndexes.has(i); + for (const arr of params) { + removeDeselectedForeignField(arr[0].foreignField, arr[0].options, vals); + } + callback(); + } +} - if (ordered) { - if (firstErroredIndex > -1) { - return i < firstErroredIndex; - } +/*! + * ignore + */ - if (isErrored) { - firstErroredIndex = i; - } - } +function _execPopulateQuery(mod, match, select, assignmentOpts, callback) { + const subPopulate = utils.clone(mod.options.populate); + const queryOptions = Object.assign({ + skip: mod.options.skip, + limit: mod.options.limit, + perDocumentLimit: mod.options.perDocumentLimit + }, mod.options.options); - return !isErrored; - }) - .map(function setIsNewForInsertedDoc(doc) { - doc.$__reset(); - _setIsNew(doc, false); - return doc; - }); + if (mod.count) { + delete queryOptions.skip; + } - callback(error, null); - return; - } + if (queryOptions.perDocumentLimit != null) { + queryOptions.limit = queryOptions.perDocumentLimit; + delete queryOptions.perDocumentLimit; + } else if (queryOptions.limit != null) { + queryOptions.limit = queryOptions.limit * mod.ids.length; + } - for (const attribute of docAttributes) { - attribute.$__reset(); - _setIsNew(attribute, false); - } + const query = mod.model.find(match, select, queryOptions); + // If we're doing virtual populate and projection is inclusive and foreign + // field is not selected, automatically select it because mongoose needs it. + // If projection is exclusive and client explicitly unselected the foreign + // field, that's the client's fault. + for (const foreignField of mod.foreignField) { + if (foreignField !== '_id' && query.selectedInclusively() && + !isPathSelectedInclusive(query._fields, foreignField)) { + query.select(foreignField); + } + } - if (rawResult) { - if (ordered === false) { - // Decorate with mongoose validation errors in case of unordered, - // because then still do `insertMany()` - res.mongoose = { - validationErrors: validationErrors, - }; - } - return callback(null, res); - } + // If using count, still need the `foreignField` so we can match counts + // to documents, otherwise we would need a separate `count()` for every doc. + if (mod.count) { + for (const foreignField of mod.foreignField) { + query.select(foreignField); + } + } - if (options.populate != null) { - return _this.populate( - docAttributes, - options.populate, - (err) => { - if (err != null) { - error.insertedDocs = docAttributes; - return callback(err); - } + // If we need to sub-populate, call populate recursively + if (subPopulate) { + // If subpopulating on a discriminator, skip check for non-existent + // paths. Because the discriminator may not have the path defined. + if (mod.model.baseModelName != null) { + if (Array.isArray(subPopulate)) { + subPopulate.forEach(pop => { pop.strictPopulate = false; }); + } else { + subPopulate.strictPopulate = false; + } + } + const basePath = mod.options._fullPath || mod.options.path; - callback(null, docs); - } - ); - } + if (Array.isArray(subPopulate)) { + for (const pop of subPopulate) { + pop._fullPath = basePath + '.' + pop.path; + } + } else if (subPopulate != null) { + subPopulate._fullPath = basePath + '.' + subPopulate.path; + } + query.populate(subPopulate); + } - callback(null, docAttributes); - } - ); - }); - }; + query.exec((err, docs) => { + if (err != null) { + return callback(err); + } - /*! - * ignore - */ - - function _setIsNew(doc, val) { - doc.isNew = val; - doc.emit("isNew", val); - doc.constructor.emit("isNew", val); - - const subdocs = doc.$getAllSubdocs(); - for (const subdoc of subdocs) { - subdoc.isNew = val; - } - } - - /** - * Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`, - * `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one - * command. This is faster than sending multiple independent operations (e.g. - * if you use `create()`) because with `bulkWrite()` there is only one round - * trip to MongoDB. - * - * Mongoose will perform casting on all operations you provide. - * - * This function does **not** trigger any middleware, neither `save()`, nor `update()`. - * If you need to trigger - * `save()` middleware for every document use [`create()`](http://mongoosejs.com/docs/api.html#model_Model.create) instead. - * - * ####Example: - * - * Character.bulkWrite([ - * { - * insertOne: { - * document: { - * name: 'Eddard Stark', - * title: 'Warden of the North' - * } - * } - * }, - * { - * updateOne: { - * filter: { name: 'Eddard Stark' }, - * // If you were using the MongoDB driver directly, you'd need to do - * // `update: { $set: { title: ... } }` but mongoose adds $set for - * // you. - * update: { title: 'Hand of the King' } - * } - * }, - * { - * deleteOne: { - * { - * filter: { name: 'Eddard Stark' } - * } - * } - * } - * ]).then(res => { - * // Prints "1 1 1" - * console.log(res.insertedCount, res.modifiedCount, res.deletedCount); - * }); - * - * The [supported operations](https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/#db.collection.bulkWrite) are: - * - * - `insertOne` - * - `updateOne` - * - `updateMany` - * - `deleteOne` - * - `deleteMany` - * - `replaceOne` - * - * @param {Array} ops - * @param {Object} [ops.insertOne.document] The document to insert - * @param {Object} [opts.updateOne.filter] Update the first document that matches this filter - * @param {Object} [opts.updateOne.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/) - * @param {Boolean} [opts.updateOne.upsert=false] If true, insert a doc if none match - * @param {Boolean} [opts.updateOne.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation - * @param {Object} [opts.updateOne.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use - * @param {Array} [opts.updateOne.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update` - * @param {Object} [opts.updateMany.filter] Update all the documents that match this filter - * @param {Object} [opts.updateMany.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/) - * @param {Boolean} [opts.updateMany.upsert=false] If true, insert a doc if no documents match `filter` - * @param {Boolean} [opts.updateMany.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation - * @param {Object} [opts.updateMany.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use - * @param {Array} [opts.updateMany.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update` - * @param {Object} [opts.deleteOne.filter] Delete the first document that matches this filter - * @param {Object} [opts.deleteMany.filter] Delete all documents that match this filter - * @param {Object} [opts.replaceOne.filter] Replace the first document that matches this filter - * @param {Object} [opts.replaceOne.replacement] The replacement document - * @param {Boolean} [opts.replaceOne.upsert=false] If true, insert a doc if no documents match `filter` - * @param {Object} [options] - * @param {Boolean} [options.ordered=true] If true, execute writes in order and stop at the first error. If false, execute writes in parallel and continue until all writes have either succeeded or errored. - * @param {ClientSession} [options.session=null] The session associated with this bulk write. See [transactions docs](/docs/transactions.html). - * @param {String|number} [options.w=1] The [write concern](https://docs.mongodb.com/manual/reference/write-concern/). See [`Query#w()`](/docs/api.html#query_Query-w) for more information. - * @param {number} [options.wtimeout=null] The [write concern timeout](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). - * @param {Boolean} [options.j=true] If false, disable [journal acknowledgement](https://docs.mongodb.com/manual/reference/write-concern/#j-option) - * @param {Boolean} [options.bypassDocumentValidation=false] If true, disable [MongoDB server-side schema validation](https://docs.mongodb.com/manual/core/schema-validation/) for all writes in this bulk. - * @param {Boolean} [options.strict=null] Overwrites the [`strict` option](/docs/guide.html#strict) on schema. If false, allows filtering and writing fields not defined in the schema for all writes in this bulk. - * @param {Function} [callback] callback `function(error, bulkWriteOpResult) {}` - * @return {Promise} resolves to a [`BulkWriteOpResult`](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~BulkWriteOpResult) if the operation succeeds - * @api public - */ - - Model.bulkWrite = function (ops, options, callback) { - _checkContext(this, "bulkWrite"); - - if (typeof options === "function") { - callback = options; - options = null; - } - options = options || {}; + for (const val of docs) { + leanPopulateMap.set(val, mod.model); + } + callback(null, docs); + }); +} - const validations = ops.map((op) => castBulkWrite(this, op, options)); - - callback = this.$handleCallbackError(callback); - return this.db.base._promiseOrCallback( - callback, - (cb) => { - cb = this.$wrapCallback(cb); - each( - validations, - (fn, cb) => fn(cb), - (error) => { - if (error) { - return cb(error); - } +/*! + * ignore + */ - if (ops.length === 0) { - return cb(null, getDefaultBulkwriteResult()); - } +function _assign(model, vals, mod, assignmentOpts) { + const options = mod.options; + const isVirtual = mod.isVirtual; + const justOne = mod.justOne; + let _val; + const lean = get(options, 'options.lean', false); + const len = vals.length; + const rawOrder = {}; + const rawDocs = {}; + let key; + let val; + + // Clone because `assignRawDocsToIdStructure` will mutate the array + const allIds = utils.clone(mod.allIds); + // optimization: + // record the document positions as returned by + // the query result. + for (let i = 0; i < len; i++) { + val = vals[i]; + if (val == null) { + continue; + } - this.$__collection.bulkWrite(ops, options, (error, res) => { - if (error) { - return cb(error); - } + for (const foreignField of mod.foreignField) { + _val = utils.getValue(foreignField, val); + if (Array.isArray(_val)) { + _val = utils.array.unique(utils.array.flatten(_val)); - cb(null, res); - }); - } - ); - }, - this.events - ); - }; + for (let __val of _val) { + if (__val instanceof Document) { + __val = __val._id; + } + key = String(__val); + if (rawDocs[key]) { + if (Array.isArray(rawDocs[key])) { + rawDocs[key].push(val); + rawOrder[key].push(i); + } else { + rawDocs[key] = [rawDocs[key], val]; + rawOrder[key] = [rawOrder[key], i]; + } + } else { + if (isVirtual && !justOne) { + rawDocs[key] = [val]; + rawOrder[key] = [i]; + } else { + rawDocs[key] = val; + rawOrder[key] = i; + } + } + } + } else { + if (_val instanceof Document) { + _val = _val._id; + } + key = String(_val); + if (rawDocs[key]) { + if (Array.isArray(rawDocs[key])) { + rawDocs[key].push(val); + rawOrder[key].push(i); + } else if (isVirtual || + rawDocs[key].constructor !== val.constructor || + String(rawDocs[key]._id) !== String(val._id)) { + // May need to store multiple docs with the same id if there's multiple models + // if we have discriminators or a ref function. But avoid converting to an array + // if we have multiple queries on the same model because of `perDocumentLimit` re: gh-9906 + rawDocs[key] = [rawDocs[key], val]; + rawOrder[key] = [rawOrder[key], i]; + } + } else { + rawDocs[key] = val; + rawOrder[key] = i; + } + } + // flag each as result of population + if (!lean) { + val.$__.wasPopulated = true; + } + } + } - /** - * takes an array of documents, gets the changes and inserts/updates documents in the database - * according to whether or not the document is new, or whether it has changes or not. - * - * `bulkSave` uses `bulkWrite` under the hood, so it's mostly useful when dealing with many documents (10K+) - * - * @param {[Document]} documents - * - */ - Model.bulkSave = function (documents) { - const preSavePromises = documents.map(buildPreSavePromise); - - const writeOperations = this.buildBulkWriteOperations(documents, { - skipValidation: true, - }); + assignVals({ + originalModel: model, + // If virtual, make sure to not mutate original field + rawIds: mod.isVirtual ? allIds : mod.allIds, + allIds: allIds, + unpopulatedValues: mod.unpopulatedValues, + foreignField: mod.foreignField, + rawDocs: rawDocs, + rawOrder: rawOrder, + docs: mod.docs, + path: options.path, + options: assignmentOpts, + justOne: mod.justOne, + isVirtual: mod.isVirtual, + allOptions: mod, + populatedModel: mod.model, + lean: lean, + virtual: mod.virtual, + count: mod.count, + match: mod.match + }); +} + +/*! + * Compiler utility. + * + * @param {String|Function} name model name or class extending Model + * @param {Schema} schema + * @param {String} collectionName + * @param {Connection} connection + * @param {Mongoose} base mongoose instance + */ - let bulkWriteResultPromise; - return Promise.all(preSavePromises) - .then( - () => (bulkWriteResultPromise = this.bulkWrite(writeOperations)) - ) - .then(() => documents.map(buildSuccessfulWriteHandlerPromise)) - .then(() => bulkWriteResultPromise) - .catch((err) => { - if (!get(err, "writeErrors.length")) { - throw err; - } - return Promise.all( - documents.map((document) => { - const documentError = err.writeErrors.find((writeError) => { - const writeErrorDocumentId = - writeError.err.op._id || writeError.err.op.q._id; - return ( - writeErrorDocumentId.toString() === document._id.toString() - ); - }); +Model.compile = function compile(name, schema, collectionName, connection, base) { + const versioningEnabled = schema.options.versionKey !== false; - if (documentError == null) { - return buildSuccessfulWriteHandlerPromise(document); - } - }) - ).then(() => { - throw err; - }); - }); - }; + if (versioningEnabled && !schema.paths[schema.options.versionKey]) { + // add versioning to top level documents only + const o = {}; + o[schema.options.versionKey] = Number; + schema.add(o); + } - function buildPreSavePromise(document) { - return new Promise((resolve, reject) => { - document.schema.s.hooks.execPre("save", document, (err) => { - if (err) { - reject(err); - return; - } - resolve(); - }); - }); + let model; + if (typeof name === 'function' && name.prototype instanceof Model) { + model = name; + name = model.name; + schema.loadClass(model, false); + model.prototype.$isMongooseModelPrototype = true; + } else { + // generate new class + model = function model(doc, fields, skipId) { + model.hooks.execPreSync('createModel', doc); + if (!(this instanceof model)) { + return new model(doc, fields, skipId); } + const discriminatorKey = model.schema.options.discriminatorKey; - function buildSuccessfulWriteHandlerPromise(document) { - return new Promise((resolve, reject) => { - handleSuccessfulWrite(document, resolve, reject); - }); + if (model.discriminators == null || doc == null || doc[discriminatorKey] == null) { + Model.call(this, doc, fields, skipId); + return; } - function handleSuccessfulWrite(document, resolve, reject) { - if (document.isNew) { - _setIsNew(document, false); - } - - document.$__reset(); - document.schema.s.hooks.execPost("save", document, {}, (err) => { - if (err) { - reject(err); - return; - } - resolve(); - }); + // If discriminator key is set, use the discriminator instead (gh-7586) + const Discriminator = model.discriminators[doc[discriminatorKey]] || + getDiscriminatorByValue(model.discriminators, doc[discriminatorKey]); + if (Discriminator != null) { + return new Discriminator(doc, fields, skipId); } - /** - * - * @param {[Document]} documents The array of documents to build write operations of - * @param {Object} options - * @param {Boolean} options.skipValidation defaults to `false`, when set to true, building the write operations will bypass validating the documents. - * @returns - */ - Model.buildBulkWriteOperations = function buildBulkWriteOperations( - documents, - options - ) { - if (!Array.isArray(documents)) { - throw new Error( - `bulkSave expects an array of documents to be passed, received \`${documents}\` instead` - ); - } + // Otherwise, just use the top-level model + Model.call(this, doc, fields, skipId); + }; + } - setDefaultOptions(); + model.hooks = schema.s.hooks.clone(); + model.base = base; + model.modelName = name; - const writeOperations = documents.reduce((accumulator, document, i) => { - if (!options.skipValidation) { - if (!(document instanceof Document)) { - throw new Error( - `documents.${i} was not a mongoose document, documents must be an array of mongoose documents (instanceof mongoose.Document).` - ); - } - const validationError = document.validateSync(); - if (validationError) { - throw validationError; - } - } + if (!(model.prototype instanceof Model)) { + model.__proto__ = Model; + model.prototype.__proto__ = Model.prototype; + } + model.model = function model(name) { + return this.db.model(name); + }; + model.db = connection; + model.prototype.db = connection; + model.prototype[modelDbSymbol] = connection; + model.discriminators = model.prototype.discriminators = undefined; + model[modelSymbol] = true; + model.events = new EventEmitter(); - const isANewDocument = document.isNew; - if (isANewDocument) { - accumulator.push({ - insertOne: { document }, - }); + schema._preCompile(); - return accumulator; - } + model.prototype.$__setSchema(schema); - const delta = document.$__delta(); - const isDocumentWithChanges = - delta != null && !utils.isEmptyObject(delta[0]); + const _userProvidedOptions = schema._userProvidedOptions || {}; - if (isDocumentWithChanges) { - const where = document.$__where(delta[0]); - const changes = delta[1]; + const collectionOptions = { + schemaUserProvidedOptions: _userProvidedOptions, + capped: schema.options.capped, + Promise: model.base.Promise, + modelName: name + }; + if (schema.options.autoCreate !== void 0) { + collectionOptions.autoCreate = schema.options.autoCreate; + } - _applyCustomWhere(document, where); + model.prototype.collection = connection.collection( + collectionName, + collectionOptions + ); - document.$__version(where, delta); + model.prototype.$collection = model.prototype.collection; + model.prototype[modelCollectionSymbol] = model.prototype.collection; - accumulator.push({ - updateOne: { - filter: where, - update: changes, - }, - }); + // apply methods and statics + applyMethods(model, schema); + applyStatics(model, schema); + applyHooks(model, schema); + applyStaticHooks(model, schema.s.hooks, schema.statics); - return accumulator; - } + model.schema = model.prototype.$__schema; + model.collection = model.prototype.collection; + model.$__collection = model.collection; - return accumulator; - }, []); + // Create custom query constructor + model.Query = function() { + Query.apply(this, arguments); + }; + model.Query.prototype = Object.create(Query.prototype); + model.Query.base = Query.base; + applyQueryMiddleware(model.Query, model); + applyQueryMethods(model, schema.query); - return writeOperations; + return model; +}; - function setDefaultOptions() { - options = options || {}; - if (options.skipValidation == null) { - options.skipValidation = false; - } - } - }; +/*! + * Register custom query methods for this model + * + * @param {Model} model + * @param {Schema} schema + */ - /** - * Shortcut for creating a new Document from existing raw data, pre-saved in the DB. - * The document returned has no paths marked as modified initially. - * - * ####Example: - * - * // hydrate previous data into a Mongoose document - * const mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' }); - * - * @param {Object} obj - * @param {Object|String|Array} [projection] optional projection containing which fields should be selected for this document - * @return {Document} document instance - * @api public - */ - - Model.hydrate = function (obj, projection) { - _checkContext(this, "hydrate"); - - const model = __nccwpck_require__(5299).createModel( - this, - obj, - projection - ); - model.init(obj); - return model; - }; +function applyQueryMethods(model, methods) { + for (const i in methods) { + model.Query.prototype[i] = methods[i]; + } +} - /** - * Updates one document in the database without returning it. - * - * This function triggers the following middleware. - * - * - `update()` - * - * ####Examples: - * - * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn); - * - * const res = await MyModel.update({ name: 'Tobi' }, { ferret: true }); - * res.n; // Number of documents that matched `{ name: 'Tobi' }` - * // Number of documents that were changed. If every doc matched already - * // had `ferret` set to `true`, `nModified` will be 0. - * res.nModified; - * - * ####Valid options: - * - * - `strict` (boolean): overrides the [schema-level `strict` option](/docs/guide.html#strict) for this update - * - `upsert` (boolean): whether to create the doc if it doesn't match (false) - * - `writeConcern` (object): sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * - `omitUndefined` (boolean): If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * - `multi` (boolean): whether multiple documents should be updated (false) - * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * - `setDefaultsOnInsert` (boolean): if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * - `timestamps` (boolean): If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. - * - `overwrite` (boolean): disables update-only mode, allowing you to overwrite the doc (false) - * - * All `update` values are cast to their appropriate SchemaTypes before being sent. - * - * The `callback` function receives `(err, rawResponse)`. - * - * - `err` is the error if any occurred - * - `rawResponse` is the full response from Mongo - * - * ####Note: - * - * All top level keys which are not `atomic` operation names are treated as set operations: - * - * ####Example: - * - * const query = { name: 'borne' }; - * Model.update(query, { name: 'jason bourne' }, options, callback); - * - * // is sent as - * Model.update(query, { $set: { name: 'jason bourne' }}, options, function(err, res)); - * // if overwrite option is false. If overwrite is true, sent without the $set wrapper. - * - * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason bourne' }`. - * - * ####Note: - * - * Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error. - * - * ####Note: - * - * Mongoose casts values and runs setters when using update. The following - * features are **not** applied by default. - * - * - [defaults](/docs/defaults.html#the-setdefaultsoninsert-option) - * - [validators](/docs/validation.html#update-validators) - * - middleware - * - * If you need document middleware and fully-featured validation, load the - * document first and then use [`save()`](/docs/api.html#model_Model-save). - * - * Model.findOne({ name: 'borne' }, function (err, doc) { - * if (err) .. - * doc.name = 'jason bourne'; - * doc.save(callback); - * }) - * - * @see strict http://mongoosejs.com/docs/guide.html#strict - * @see response http://docs.mongodb.org/v2.6/reference/command/update/#output - * @param {Object} filter - * @param {Object} doc - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](/docs/api.html#query_Query-setOptions) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.multi=false] whether multiple documents should be updated or just the first one that matches `filter`. - * @param {Boolean} [options.runValidators=false] if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * @param {Boolean} [options.setDefaultsOnInsert=false] if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. - * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `doc`, Mongoose will wrap `doc` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. - * @param {Function} [callback] params are (error, [updateWriteOpResult](https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#~updateWriteOpResult)) - * @param {Function} [callback] - * @return {Query} - * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output - * @see writeOpResult https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#~updateWriteOpResult - * @see Query docs https://mongoosejs.com/docs/queries.html - * @api public - */ - - Model.update = function update(conditions, doc, options, callback) { - _checkContext(this, "update"); - - return _update(this, "update", conditions, doc, options, callback); - }; +/*! + * Subclass this model with `conn`, `schema`, and `collection` settings. + * + * @param {Connection} conn + * @param {Schema} [schema] + * @param {String} [collection] + * @return {Model} + */ - /** - * Same as `update()`, except MongoDB will update _all_ documents that match - * `filter` (as opposed to just the first one) regardless of the value of - * the `multi` option. - * - * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')` - * and `post('updateMany')` instead. - * - * ####Example: - * const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true }); - * res.n; // Number of documents matched - * res.nModified; // Number of documents modified - * - * This function triggers the following middleware. - * - * - `updateMany()` - * - * @param {Object} filter - * @param {Object|Array} update - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. - * @param {Function} [callback] `function(error, res) {}` where `res` has 3 properties: `n`, `nModified`, `ok`. - * @return {Query} - * @see Query docs https://mongoosejs.com/docs/queries.html - * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @api public - */ - - Model.updateMany = function updateMany( - conditions, - doc, - options, - callback - ) { - _checkContext(this, "updateMany"); - - return _update(this, "updateMany", conditions, doc, options, callback); - }; +Model.__subclass = function subclass(conn, schema, collection) { + // subclass model using this connection and collection name + const _this = this; - /** - * Same as `update()`, except it does not support the `multi` or `overwrite` - * options. - * - * - MongoDB will update _only_ the first document that matches `filter` regardless of the value of the `multi` option. - * - Use `replaceOne()` if you want to overwrite an entire document rather than using atomic operators like `$set`. - * - * ####Example: - * const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' }); - * res.n; // Number of documents matched - * res.nModified; // Number of documents modified - * - * This function triggers the following middleware. - * - * - `updateOne()` - * - * @param {Object} filter - * @param {Object|Array} update - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Function} [callback] params are (error, writeOpResult) - * @return {Query} - * @see Query docs https://mongoosejs.com/docs/queries.html - * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @api public - */ - - Model.updateOne = function updateOne(conditions, doc, options, callback) { - _checkContext(this, "updateOne"); - - return _update(this, "updateOne", conditions, doc, options, callback); - }; + const Model = function Model(doc, fields, skipId) { + if (!(this instanceof Model)) { + return new Model(doc, fields, skipId); + } + _this.call(this, doc, fields, skipId); + }; - /** - * Same as `update()`, except MongoDB replace the existing document with the - * given document (no atomic operators like `$set`). - * - * ####Example: - * const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' }); - * res.n; // Number of documents matched - * res.nModified; // Number of documents modified - * - * This function triggers the following middleware. - * - * - `replaceOne()` - * - * @param {Object} filter - * @param {Object} doc - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. - * @param {Function} [callback] `function(error, res) {}` where `res` has 3 properties: `n`, `nModified`, `ok`. - * @return {Query} - * @see Query docs https://mongoosejs.com/docs/queries.html - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @return {Query} - * @api public - */ - - Model.replaceOne = function replaceOne( - conditions, - doc, - options, - callback - ) { - _checkContext(this, "replaceOne"); - - const versionKey = get(this, "schema.options.versionKey", null); - if (versionKey && !doc[versionKey]) { - doc[versionKey] = 0; - } - - return _update(this, "replaceOne", conditions, doc, options, callback); - }; + Model.__proto__ = _this; + Model.prototype.__proto__ = _this.prototype; + Model.db = conn; + Model.prototype.db = conn; + Model.prototype[modelDbSymbol] = conn; + + _this[subclassedSymbol] = _this[subclassedSymbol] || []; + _this[subclassedSymbol].push(Model); + if (_this.discriminators != null) { + Model.discriminators = {}; + for (const key of Object.keys(_this.discriminators)) { + Model.discriminators[key] = _this.discriminators[key]. + __subclass(_this.db, _this.discriminators[key].schema, collection); + } + } - /*! - * Common code for `updateOne()`, `updateMany()`, `replaceOne()`, and `update()` - * because they need to do the same thing - */ + const s = schema && typeof schema !== 'string' + ? schema + : _this.prototype.$__schema; - function _update(model, op, conditions, doc, options, callback) { - const mq = new model.Query({}, {}, model, model.collection); + const options = s.options || {}; + const _userProvidedOptions = s._userProvidedOptions || {}; - callback = model.$handleCallbackError(callback); - // gh-2406 - // make local deep copy of conditions - if (conditions instanceof Document) { - conditions = conditions.toObject(); - } else { - conditions = utils.clone(conditions); - } - options = - typeof options === "function" ? options : utils.clone(options); - - const versionKey = get(model, "schema.options.versionKey", null); - _decorateUpdateWithVersionKey(doc, options, versionKey); - - return mq[op](conditions, doc, options, callback); - } - - /** - * Executes a mapReduce command. - * - * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See [node-mongodb-native mapReduce() documentation](http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#mapreduce) for more detail about options. - * - * This function does not trigger any middleware. - * - * ####Example: - * - * const o = {}; - * // `map()` and `reduce()` are run on the MongoDB server, not Node.js, - * // these functions are converted to strings - * o.map = function () { emit(this.name, 1) }; - * o.reduce = function (k, vals) { return vals.length }; - * User.mapReduce(o, function (err, results) { - * console.log(results) - * }) - * - * ####Other options: - * - * - `query` {Object} query filter object. - * - `sort` {Object} sort input objects using this key - * - `limit` {Number} max number of documents - * - `keeptemp` {Boolean, default:false} keep temporary data - * - `finalize` {Function} finalize function - * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution - * - `jsMode` {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X - * - `verbose` {Boolean, default:false} provide statistics on job execution time. - * - `readPreference` {String} - * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job. - * - * ####* out options: - * - * - `{inline:1}` the results are returned in an array - * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection - * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions - * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old - * - * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the [`lean` option](/docs/tutorials/lean.html); meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc). - * - * ####Example: - * - * const o = {}; - * // You can also define `map()` and `reduce()` as strings if your - * // linter complains about `emit()` not being defined - * o.map = 'function () { emit(this.name, 1) }'; - * o.reduce = 'function (k, vals) { return vals.length }'; - * o.out = { replace: 'createdCollectionNameForResults' } - * o.verbose = true; - * - * User.mapReduce(o, function (err, model, stats) { - * console.log('map reduce took %d ms', stats.processtime) - * model.find().where('value').gt(10).exec(function (err, docs) { - * console.log(docs); - * }); - * }) - * - * // `mapReduce()` returns a promise. However, ES6 promises can only - * // resolve to exactly one value, - * o.resolveToObject = true; - * const promise = User.mapReduce(o); - * promise.then(function (res) { - * const model = res.model; - * const stats = res.stats; - * console.log('map reduce took %d ms', stats.processtime) - * return model.find().where('value').gt(10).exec(); - * }).then(function (docs) { - * console.log(docs); - * }).then(null, handleError).end() - * - * @param {Object} o an object specifying map-reduce options - * @param {Function} [callback] optional callback - * @see http://www.mongodb.org/display/DOCS/MapReduce - * @return {Promise} - * @api public - */ - - Model.mapReduce = function mapReduce(o, callback) { - _checkContext(this, "mapReduce"); - - callback = this.$handleCallbackError(callback); - - return this.db.base._promiseOrCallback( - callback, - (cb) => { - cb = this.$wrapCallback(cb); - - if (!Model.mapReduce.schema) { - const opts = { noId: true, noVirtualId: true, strict: false }; - Model.mapReduce.schema = new Schema({}, opts); - } - - if (!o.out) o.out = { inline: 1 }; - if (o.verbose !== false) o.verbose = true; - - o.map = String(o.map); - o.reduce = String(o.reduce); - - if (o.query) { - let q = new this.Query(o.query); - q.cast(this); - o.query = q._conditions; - q = undefined; - } - - this.$__collection.mapReduce(null, null, o, (err, res) => { - if (err) { - return cb(err); - } - if (res.collection) { - // returned a collection, convert to Model - const model = Model.compile( - "_mapreduce_" + res.collection.collectionName, - Model.mapReduce.schema, - res.collection.collectionName, - this.db, - this.base - ); + if (!collection) { + collection = _this.prototype.$__schema.get('collection') || + utils.toCollectionName(_this.modelName, this.base.pluralize()); + } - model._mapreduce = true; - res.model = model; + const collectionOptions = { + schemaUserProvidedOptions: _userProvidedOptions, + capped: s && options.capped + }; - return cb(null, res); - } + Model.prototype.collection = conn.collection(collection, collectionOptions); + Model.prototype.$collection = Model.prototype.collection; + Model.prototype[modelCollectionSymbol] = Model.prototype.collection; + Model.collection = Model.prototype.collection; + Model.$__collection = Model.collection; + // Errors handled internally, so ignore + Model.init(() => {}); + return Model; +}; + +Model.$handleCallbackError = function(callback) { + if (callback == null) { + return callback; + } + if (typeof callback !== 'function') { + throw new MongooseError('Callback must be a function, got ' + callback); + } - cb(null, res); - }); - }, - this.events - ); - }; + const _this = this; + return function() { + immediate(() => { + try { + callback.apply(null, arguments); + } catch (error) { + _this.emit('error', error); + } + }); + }; +}; - /** - * Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection. - * - * If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned. - * - * This function triggers the following middleware. - * - * - `aggregate()` - * - * ####Example: - * - * // Find the max balance of all accounts - * Users.aggregate([ - * { $group: { _id: null, maxBalance: { $max: '$balance' }}}, - * { $project: { _id: 0, maxBalance: 1 }} - * ]). - * then(function (res) { - * console.log(res); // [ { maxBalance: 98000 } ] - * }); - * - * // Or use the aggregation pipeline builder. - * Users.aggregate(). - * group({ _id: null, maxBalance: { $max: '$balance' } }). - * project('-id maxBalance'). - * exec(function (err, res) { - * if (err) return handleError(err); - * console.log(res); // [ { maxBalance: 98 } ] - * }); - * - * ####NOTE: - * - * - Mongoose does **not** cast aggregation pipelines to the model's schema because `$project` and `$group` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format. You can use the [mongoose-cast-aggregation plugin](https://github.com/AbdelrahmanHafez/mongoose-cast-aggregation) to enable minimal casting for aggregation pipelines. - * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). - * - * #### More About Aggregations: - * - * - [Mongoose `Aggregate`](/docs/api/aggregate.html) - * - [An Introduction to Mongoose Aggregate](https://masteringjs.io/tutorials/mongoose/aggregate) - * - [MongoDB Aggregation docs](http://docs.mongodb.org/manual/applications/aggregation/) - * - * @see Aggregate #aggregate_Aggregate - * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ - * @param {Array} [pipeline] aggregation pipeline as an array of objects - * @param {Function} [callback] - * @return {Aggregate} - * @api public - */ - - Model.aggregate = function aggregate(pipeline, callback) { - _checkContext(this, "aggregate"); +/*! + * ignore + */ - if ( - arguments.length > 2 || - get(pipeline, "constructor.name") === "Object" - ) { - throw new MongooseError( - "Mongoose 5.x disallows passing a spread of operators " + - "to `Model.aggregate()`. Instead of " + - "`Model.aggregate({ $match }, { $skip })`, do " + - "`Model.aggregate([{ $match }, { $skip }])`" - ); - } +Model.$wrapCallback = function(callback) { + const serverSelectionError = new ServerSelectionError(); + const _this = this; - if (typeof pipeline === "function") { - callback = pipeline; - pipeline = []; - } + return function(err) { + if (err != null && err.name === 'MongoServerSelectionError') { + arguments[0] = serverSelectionError.assimilateError(err); + } + if (err != null && err.name === 'MongoNetworkTimeoutError' && err.message.endsWith('timed out')) { + _this.db.emit('timeout'); + } - const aggregate = new Aggregate(pipeline || []); - aggregate.model(this); + return callback.apply(null, arguments); + }; +}; - if (typeof callback === "undefined") { - return aggregate; - } +/** + * Helper for console.log. Given a model named 'MyModel', returns the string + * `'Model { MyModel }'`. + * + * ####Example: + * + * const MyModel = mongoose.model('Test', Schema({ name: String })); + * MyModel.inspect(); // 'Model { Test }' + * console.log(MyModel); // Prints 'Model { Test }' + * + * @api public + */ - callback = this.$handleCallbackError(callback); - callback = this.$wrapCallback(callback); +Model.inspect = function() { + return `Model { ${this.modelName} }`; +}; - aggregate.exec(callback); - return aggregate; - }; +if (util.inspect.custom) { + /*! + * Avoid Node deprecation warning DEP0079 + */ - /** - * Casts and validates the given object against this model's schema, passing the - * given `context` to custom validators. - * - * ####Example: - * - * const Model = mongoose.model('Test', Schema({ - * name: { type: String, required: true }, - * age: { type: Number, required: true } - * }); - * - * try { - * await Model.validate({ name: null }, ['name']) - * } catch (err) { - * err instanceof mongoose.Error.ValidationError; // true - * Object.keys(err.errors); // ['name'] - * } - * - * @param {Object} obj - * @param {Array} pathsToValidate - * @param {Object} [context] - * @param {Function} [callback] - * @return {Promise|undefined} - * @api public - */ - - Model.validate = function validate( - obj, - pathsToValidate, - context, - callback - ) { - if ( - arguments.length < 3 || - (arguments.length === 3 && typeof arguments[2] === "function") - ) { - // For convenience, if we're validating a document or an object, make `context` default to - // the model so users don't have to always pass `context`, re: gh-10132, gh-10346 - context = obj; - } + Model[util.inspect.custom] = Model.inspect; +} - return this.db.base._promiseOrCallback(callback, (cb) => { - const schema = this.schema; - let paths = Object.keys(schema.paths); +/*! + * Module exports. + */ - if (pathsToValidate != null) { - const _pathsToValidate = new Set(pathsToValidate); - paths = paths.filter((p) => { - const pieces = p.split("."); - let cur = pieces[0]; +module.exports = exports = Model; - for (const piece of pieces) { - if (_pathsToValidate.has(cur)) { - return true; - } - cur += "." + piece; - } - return _pathsToValidate.has(p); - }); - } +/***/ }), - for (const path of paths) { - const schemaType = schema.path(path); - if (!schemaType || !schemaType.$isMongooseArray) { - continue; - } +/***/ 5684: +/***/ ((__unused_webpack_module, exports) => { - const val = get(obj, path); - pushNestedArrayPaths(val, path); - } +"use strict"; - let remaining = paths.length; - let error = null; - for (const path of paths) { - const schemaType = schema.path(path); - if (schemaType == null) { - _checkDone(); - continue; - } +/*! + * ignore + */ - const pieces = path.split("."); - let cur = obj; - for (let i = 0; i < pieces.length - 1; ++i) { - cur = cur[pieces[i]]; - } +exports.h = { + transform: false, + virtuals: false, + getters: false, + _skipDepopulateTopLevel: true, + depopulate: true, + flattenDecimals: false, + useProjection: false +}; - let val = get(obj, path, void 0); - if (val != null) { - try { - val = schemaType.cast(val); - cur[pieces[pieces.length - 1]] = val; - } catch (err) { - error = error || new ValidationError(); - error.addError(path, err); +/***/ }), - _checkDone(); - continue; - } - } +/***/ 7038: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - schemaType.doValidate( - val, - (err) => { - if (err) { - error = error || new ValidationError(); - if (err instanceof ValidationError) { - for (const _err of Object.keys(err.errors)) { - error.addError(`${path}.${err.errors[_err].path}`, _err); - } - } else { - error.addError(err.path, err); - } - } - _checkDone(); - }, - context, - { path: path } - ); - } +"use strict"; - function pushNestedArrayPaths(nestedArray, path) { - if (nestedArray == null) { - return; - } - for (let i = 0; i < nestedArray.length; ++i) { - if (Array.isArray(nestedArray[i])) { - pushNestedArrayPaths(nestedArray[i], path + "." + i); - } else { - paths.push(path + "." + i); - } - } - } +const clone = __nccwpck_require__(5092); + +class PopulateOptions { + constructor(obj) { + this._docs = {}; + this._childDocs = []; + + if (obj == null) { + return; + } + obj = clone(obj); + Object.assign(this, obj); + if (typeof obj.subPopulate === 'object') { + this.populate = obj.subPopulate; + } + + + if (obj.perDocumentLimit != null && obj.limit != null) { + throw new Error('Can not use `limit` and `perDocumentLimit` at the same time. Path: `' + obj.path + '`.'); + } + } +} + +/** + * The connection used to look up models by name. If not specified, Mongoose + * will default to using the connection associated with the model in + * `PopulateOptions#model`. + * + * @memberOf PopulateOptions + * @property {Connection} connection + * @api public + */ + +module.exports = PopulateOptions; - function _checkDone() { - if (--remaining <= 0) { - return cb(error); - } - } - }); - }; +/***/ }), - /** - * Implements `$geoSearch` functionality for Mongoose - * - * This function does not trigger any middleware - * - * ####Example: - * - * const options = { near: [10, 10], maxDistance: 5 }; - * Locations.geoSearch({ type : "house" }, options, function(err, res) { - * console.log(res); - * }); - * - * ####Options: - * - `near` {Array} x,y point to search for - * - `maxDistance` {Number} the maximum distance from the point near that a result can be - * - `limit` {Number} The maximum number of results to return - * - `lean` {Object|Boolean} return the raw object instead of the Mongoose Model - * - * @param {Object} conditions an object that specifies the match condition (required) - * @param {Object} options for the geoSearch, some (near, maxDistance) are required - * @param {Object|Boolean} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html). - * @param {Function} [callback] optional callback - * @return {Promise} - * @see http://docs.mongodb.org/manual/reference/command/geoSearch/ - * @see http://docs.mongodb.org/manual/core/geohaystack/ - * @api public - */ - - Model.geoSearch = function (conditions, options, callback) { - _checkContext(this, "geoSearch"); - - if (typeof options === "function") { - callback = options; - options = {}; - } - - callback = this.$handleCallbackError(callback); - - return this.db.base._promiseOrCallback( - callback, - (cb) => { - cb = this.$wrapCallback(cb); - let error; - if (conditions === undefined || !utils.isObject(conditions)) { - error = new MongooseError("Must pass conditions to geoSearch"); - } else if (!options.near) { - error = new MongooseError( - "Must specify the near option in geoSearch" - ); - } else if (!Array.isArray(options.near)) { - error = new MongooseError("near option must be an array [x, y]"); - } +/***/ 7391: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (error) { - return cb(error); - } +"use strict"; - // send the conditions in the options object - options.search = conditions; - this.$__collection.geoHaystackSearch( - options.near[0], - options.near[1], - options, - (err, res) => { - if (err) { - return cb(err); - } +const SchemaTypeOptions = __nccwpck_require__(7544); - let count = res.results.length; - if (options.lean || count === 0) { - return cb(null, res.results); - } +/** + * The options defined on an Array schematype. + * + * ####Example: + * + * const schema = new Schema({ tags: [String] }); + * schema.path('tags').options; // SchemaArrayOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaArrayOptions + */ - const errSeen = false; +class SchemaArrayOptions extends SchemaTypeOptions {} - function init(err) { - if (err && !errSeen) { - return cb(err); - } +const opts = __nccwpck_require__(1090); - if (!--count && !errSeen) { - cb(null, res.results); - } - } +/** + * If this is an array of strings, an array of allowed values for this path. + * Throws an error if this array isn't an array of strings. + * + * @api public + * @property enum + * @memberOf SchemaArrayOptions + * @type Array + * @instance + */ - for (let i = 0; i < res.results.length; ++i) { - const temp = res.results[i]; - res.results[i] = new this(); - res.results[i].init(temp, {}, init); - } - } - ); - }, - this.events - ); - }; +Object.defineProperty(SchemaArrayOptions.prototype, 'enum', opts); - /** - * Populates document references. - * - * ####Available top-level options: - * - * - path: space delimited path(s) to populate - * - select: optional fields to select - * - match: optional query conditions to match - * - model: optional name of the model to use for population - * - options: optional query options like sort, limit, etc - * - justOne: optional boolean, if true Mongoose will always set `path` to an array. Inferred from schema by default. - * - * ####Examples: - * - * // populates a single object - * User.findById(id, function (err, user) { - * const opts = [ - * { path: 'company', match: { x: 1 }, select: 'name' }, - * { path: 'notes', options: { limit: 10 }, model: 'override' } - * ]; - * - * User.populate(user, opts, function (err, user) { - * console.log(user); - * }); - * }); - * - * // populates an array of objects - * User.find(match, function (err, users) { - * const opts = [{ path: 'company', match: { x: 1 }, select: 'name' }]; - * - * const promise = User.populate(users, opts); - * promise.then(console.log).end(); - * }) - * - * // imagine a Weapon model exists with two saved documents: - * // { _id: 389, name: 'whip' } - * // { _id: 8921, name: 'boomerang' } - * // and this schema: - * // new Schema({ - * // name: String, - * // weapon: { type: ObjectId, ref: 'Weapon' } - * // }); - * - * const user = { name: 'Indiana Jones', weapon: 389 }; - * Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) { - * console.log(user.weapon.name); // whip - * }) - * - * // populate many plain objects - * const users = [{ name: 'Indiana Jones', weapon: 389 }] - * users.push({ name: 'Batman', weapon: 8921 }) - * Weapon.populate(users, { path: 'weapon' }, function (err, users) { - * users.forEach(function (user) { - * console.log('%s uses a %s', users.name, user.weapon.name) - * // Indiana Jones uses a whip - * // Batman uses a boomerang - * }); - * }); - * // Note that we didn't need to specify the Weapon model because - * // it is in the schema's ref - * - * @param {Document|Array} docs Either a single document or array of documents to populate. - * @param {Object|String} options Either the paths to populate or an object specifying all parameters - * @param {string} [options.path=null] The path to populate. - * @param {boolean} [options.retainNullValues=false] By default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries. - * @param {boolean} [options.getters=false] If true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options). - * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them. - * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object. - * @param {Boolean} [options.skipInvalidIds=false] By default, Mongoose throws a cast error if `localField` and `foreignField` schemas don't line up. If you enable this option, Mongoose will instead filter out any `localField` properties that cannot be casted to `foreignField`'s schema type. - * @param {Number} [options.perDocumentLimit=null] For legacy reasons, `limit` with `populate()` may give incorrect results because it only executes a single query for every document being populated. If you set `perDocumentLimit`, Mongoose will ensure correct `limit` per document by executing a separate query for each document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })` will execute 2 additional queries if `.find()` returns 2 documents. - * @param {Object} [options.options=null] Additional options like `limit` and `lean`. - * @param {Function} [options.transform=null] Function that Mongoose will call on every populated document that allows you to transform the populated document. - * @param {Function} [callback(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. - * @return {Promise} - * @api public - */ - - Model.populate = function (docs, paths, callback) { - _checkContext(this, "populate"); +/** + * If set, specifies the type of this array's values. Equivalent to setting + * `type` to an array whose first element is `of`. + * + * ####Example: + * + * // `arr` is an array of numbers. + * new Schema({ arr: [Number] }); + * // Equivalent way to define `arr` as an array of numbers + * new Schema({ arr: { type: Array, of: Number } }); + * + * @api public + * @property of + * @memberOf SchemaArrayOptions + * @type Function|String + * @instance + */ - const _this = this; +Object.defineProperty(SchemaArrayOptions.prototype, 'of', opts); - // normalized paths - paths = utils.populate(paths); +/*! + * ignore + */ - // data that should persist across subPopulate calls - const cache = {}; +module.exports = SchemaArrayOptions; - callback = this.$handleCallbackError(callback); - return this.db.base._promiseOrCallback( - callback, - (cb) => { - cb = this.$wrapCallback(cb); - _populate(_this, docs, paths, cache, cb); - }, - this.events - ); - }; +/***/ }), - /*! - * Populate helper - * - * @param {Model} model the model to use - * @param {Document|Array} docs Either a single document or array of documents to populate. - * @param {Object} paths - * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. - * @return {Function} - * @api private - */ +/***/ 6680: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function _populate(model, docs, paths, cache, callback) { - let pending = paths.length; - if (paths.length === 0) { - return callback(null, docs); - } +"use strict"; - // each path has its own query options and must be executed separately - for (const path of paths) { - populate(model, docs, path, next); - } - function next(err) { - if (err) { - return callback(err, null); - } - if (--pending) { - return; - } - callback(null, docs); - } - } +const SchemaTypeOptions = __nccwpck_require__(7544); - /*! - * Populates `docs` - */ - const excludeIdReg = /\s?-_id\s?/; - const excludeIdRegGlobal = /\s?-_id\s?/g; +/** + * The options defined on a Buffer schematype. + * + * ####Example: + * + * const schema = new Schema({ bitmap: Buffer }); + * schema.path('bitmap').options; // SchemaBufferOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaBufferOptions + */ - function populate(model, docs, options, callback) { - // normalize single / multiple docs passed - if (!Array.isArray(docs)) { - docs = [docs]; - } - if (docs.length === 0 || docs.every(utils.isNullOrUndefined)) { - return callback(); - } +class SchemaBufferOptions extends SchemaTypeOptions {} - const modelsMap = getModelsMapForPopulate(model, docs, options); - if (modelsMap instanceof MongooseError) { - return immediate(function () { - callback(modelsMap); - }); - } +const opts = __nccwpck_require__(1090); - const len = modelsMap.length; - let vals = []; +/** + * Set the default subtype for this buffer. + * + * @api public + * @property subtype + * @memberOf SchemaBufferOptions + * @type Number + * @instance + */ - function flatten(item) { - // no need to include undefined values in our query - return undefined !== item; - } +Object.defineProperty(SchemaBufferOptions.prototype, 'subtype', opts); - let _remaining = len; - let hasOne = false; - const params = []; - for (let i = 0; i < len; ++i) { - const mod = modelsMap[i]; - let select = mod.options.select; - let ids = utils.array.flatten(mod.ids, flatten); - ids = utils.array.unique(ids); - - const assignmentOpts = {}; - assignmentOpts.sort = get(mod, "options.options.sort", void 0); - assignmentOpts.excludeId = - excludeIdReg.test(select) || (select && select._id === 0); - - if (ids.length === 0 || ids.every(utils.isNullOrUndefined)) { - // Ensure that we set populate virtuals to 0 or empty array even - // if we don't actually execute a query because they don't have - // a value by default. See gh-7731, gh-8230 - --_remaining; - if (mod.count || mod.isVirtual) { - _assign(model, [], mod, assignmentOpts); - } - continue; - } +/*! + * ignore + */ - hasOne = true; - const match = createPopulateQueryFilter( - ids, - mod.match, - mod.foreignField, - mod.model, - mod.options.skipInvalidIds - ); +module.exports = SchemaBufferOptions; - if (assignmentOpts.excludeId) { - // override the exclusion from the query so we can use the _id - // for document matching during assignment. we'll delete the - // _id back off before returning the result. - if (typeof select === "string") { - select = select.replace(excludeIdRegGlobal, " "); - } else { - // preserve original select conditions by copying - select = utils.object.shallowCopy(select); - delete select._id; - } - } +/***/ }), - if (mod.options.options && mod.options.options.limit != null) { - assignmentOpts.originalLimit = mod.options.options.limit; - } else if (mod.options.limit != null) { - assignmentOpts.originalLimit = mod.options.limit; - } - params.push([mod, match, select, assignmentOpts, _next]); - } - if (!hasOne) { - // If no models to populate but we have a nested populate, - // keep trying, re: gh-8946 - if (options.populate != null) { - const opts = utils.populate(options.populate).map((pop) => - Object.assign({}, pop, { - path: options.path + "." + pop.path, - }) - ); - return model.populate(docs, opts, callback); - } - return callback(); - } +/***/ 5354: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (const arr of params) { - _execPopulateQuery.apply(null, arr); - } - function _next(err, valsFromDb) { - if (err != null) { - return callback(err, null); - } - vals = vals.concat(valsFromDb); - if (--_remaining === 0) { - _done(); - } - } +"use strict"; - function _done() { - for (const arr of params) { - const mod = arr[0]; - const assignmentOpts = arr[3]; - for (const val of vals) { - mod.options._childDocs.push(val); - } - _assign(model, vals, mod, assignmentOpts); - } - for (const arr of params) { - removeDeselectedForeignField( - arr[0].foreignField, - arr[0].options, - vals - ); - } - callback(); - } - } - - /*! - * ignore - */ - - function _execPopulateQuery( - mod, - match, - select, - assignmentOpts, - callback - ) { - const subPopulate = utils.clone(mod.options.populate); - const queryOptions = Object.assign( - { - skip: mod.options.skip, - limit: mod.options.limit, - perDocumentLimit: mod.options.perDocumentLimit, - }, - mod.options.options - ); +const SchemaTypeOptions = __nccwpck_require__(7544); - if (mod.count) { - delete queryOptions.skip; - } - - if (queryOptions.perDocumentLimit != null) { - queryOptions.limit = queryOptions.perDocumentLimit; - delete queryOptions.perDocumentLimit; - } else if (queryOptions.limit != null) { - queryOptions.limit = queryOptions.limit * mod.ids.length; - } - - const query = mod.model.find(match, select, queryOptions); - // If we're doing virtual populate and projection is inclusive and foreign - // field is not selected, automatically select it because mongoose needs it. - // If projection is exclusive and client explicitly unselected the foreign - // field, that's the client's fault. - for (const foreignField of mod.foreignField) { - if ( - foreignField !== "_id" && - query.selectedInclusively() && - !isPathSelectedInclusive(query._fields, foreignField) - ) { - query.select(foreignField); - } - } +/** + * The options defined on a Date schematype. + * + * ####Example: + * + * const schema = new Schema({ startedAt: Date }); + * schema.path('startedAt').options; // SchemaDateOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaDateOptions + */ - // If using count, still need the `foreignField` so we can match counts - // to documents, otherwise we would need a separate `count()` for every doc. - if (mod.count) { - for (const foreignField of mod.foreignField) { - query.select(foreignField); - } - } +class SchemaDateOptions extends SchemaTypeOptions {} - // If we need to sub-populate, call populate recursively - if (subPopulate) { - query.populate(subPopulate); - } +const opts = __nccwpck_require__(1090); - query.exec((err, docs) => { - if (err != null) { - return callback(err); - } +/** + * If set, Mongoose adds a validator that checks that this path is after the + * given `min`. + * + * @api public + * @property min + * @memberOf SchemaDateOptions + * @type Date + * @instance + */ - for (const val of docs) { - leanPopulateMap.set(val, mod.model); - } - callback(null, docs); - }); - } +Object.defineProperty(SchemaDateOptions.prototype, 'min', opts); - /*! - * ignore - */ - - function _assign(model, vals, mod, assignmentOpts) { - const options = mod.options; - const isVirtual = mod.isVirtual; - const justOne = mod.justOne; - let _val; - const lean = get(options, "options.lean", false); - const len = vals.length; - const rawOrder = {}; - const rawDocs = {}; - let key; - let val; - - // Clone because `assignRawDocsToIdStructure` will mutate the array - const allIds = utils.clone(mod.allIds); - // optimization: - // record the document positions as returned by - // the query result. - for (let i = 0; i < len; i++) { - val = vals[i]; - if (val == null) { - continue; - } +/** + * If set, Mongoose adds a validator that checks that this path is before the + * given `max`. + * + * @api public + * @property max + * @memberOf SchemaDateOptions + * @type Date + * @instance + */ - for (const foreignField of mod.foreignField) { - _val = utils.getValue(foreignField, val); - if (Array.isArray(_val)) { - _val = utils.array.unique(utils.array.flatten(_val)); +Object.defineProperty(SchemaDateOptions.prototype, 'max', opts); - for (let __val of _val) { - if (__val instanceof Document) { - __val = __val._id; - } - key = String(__val); - if (rawDocs[key]) { - if (Array.isArray(rawDocs[key])) { - rawDocs[key].push(val); - rawOrder[key].push(i); - } else { - rawDocs[key] = [rawDocs[key], val]; - rawOrder[key] = [rawOrder[key], i]; - } - } else { - if (isVirtual && !justOne) { - rawDocs[key] = [val]; - rawOrder[key] = [i]; - } else { - rawDocs[key] = val; - rawOrder[key] = i; - } - } - } - } else { - if (_val instanceof Document) { - _val = _val._id; - } - key = String(_val); - if (rawDocs[key]) { - if (Array.isArray(rawDocs[key])) { - rawDocs[key].push(val); - rawOrder[key].push(i); - } else if ( - isVirtual || - rawDocs[key].constructor !== val.constructor || - String(rawDocs[key]._id) !== String(val._id) - ) { - // May need to store multiple docs with the same id if there's multiple models - // if we have discriminators or a ref function. But avoid converting to an array - // if we have multiple queries on the same model because of `perDocumentLimit` re: gh-9906 - rawDocs[key] = [rawDocs[key], val]; - rawOrder[key] = [rawOrder[key], i]; - } - } else { - rawDocs[key] = val; - rawOrder[key] = i; - } - } - // flag each as result of population - if (!lean) { - val.$__.wasPopulated = true; - } - } - } +/** + * If set, Mongoose creates a TTL index on this path. + * + * @api public + * @property expires + * @memberOf SchemaDateOptions + * @type Date + * @instance + */ - assignVals({ - originalModel: model, - // If virtual, make sure to not mutate original field - rawIds: mod.isVirtual ? allIds : mod.allIds, - allIds: allIds, - foreignField: mod.foreignField, - rawDocs: rawDocs, - rawOrder: rawOrder, - docs: mod.docs, - path: options.path, - options: assignmentOpts, - justOne: mod.justOne, - isVirtual: mod.isVirtual, - allOptions: mod, - populatedModel: mod.model, - lean: lean, - virtual: mod.virtual, - count: mod.count, - match: mod.match, - }); - } +Object.defineProperty(SchemaDateOptions.prototype, 'expires', opts); - /*! - * Compiler utility. - * - * @param {String|Function} name model name or class extending Model - * @param {Schema} schema - * @param {String} collectionName - * @param {Connection} connection - * @param {Mongoose} base mongoose instance - */ - - Model.compile = function compile( - name, - schema, - collectionName, - connection, - base - ) { - const versioningEnabled = schema.options.versionKey !== false; - - if (versioningEnabled && !schema.paths[schema.options.versionKey]) { - // add versioning to top level documents only - const o = {}; - o[schema.options.versionKey] = Number; - schema.add(o); - } - - let model; - if (typeof name === "function" && name.prototype instanceof Model) { - model = name; - name = model.name; - schema.loadClass(model, false); - model.prototype.$isMongooseModelPrototype = true; - } else { - // generate new class - model = function model(doc, fields, skipId) { - model.hooks.execPreSync("createModel", doc); - if (!(this instanceof model)) { - return new model(doc, fields, skipId); - } - const discriminatorKey = model.schema.options.discriminatorKey; - - if ( - model.discriminators == null || - doc == null || - doc[discriminatorKey] == null - ) { - Model.call(this, doc, fields, skipId); - return; - } +/*! + * ignore + */ - // If discriminator key is set, use the discriminator instead (gh-7586) - const Discriminator = - model.discriminators[doc[discriminatorKey]] || - getDiscriminatorByValue( - model.discriminators, - doc[discriminatorKey] - ); - if (Discriminator != null) { - return new Discriminator(doc, fields, skipId); - } +module.exports = SchemaDateOptions; - // Otherwise, just use the top-level model - Model.call(this, doc, fields, skipId); - }; - } +/***/ }), - model.hooks = schema.s.hooks.clone(); - model.base = base; - model.modelName = name; +/***/ 4508: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!(model.prototype instanceof Model)) { - model.__proto__ = Model; - model.prototype.__proto__ = Model.prototype; - } - model.model = function model(name) { - return this.db.model(name); - }; - model.db = connection; - model.prototype.db = connection; - model.prototype[modelDbSymbol] = connection; - model.discriminators = model.prototype.discriminators = undefined; - model[modelSymbol] = true; - model.events = new EventEmitter(); - - model.prototype.$__setSchema(schema); - - const _userProvidedOptions = schema._userProvidedOptions || {}; - - const collectionOptions = { - schemaUserProvidedOptions: _userProvidedOptions, - capped: schema.options.capped, - Promise: model.base.Promise, - modelName: name, - }; - if (schema.options.autoCreate !== void 0) { - collectionOptions.autoCreate = schema.options.autoCreate; - } +"use strict"; - model.prototype.collection = connection.collection( - collectionName, - collectionOptions - ); - model.prototype[modelCollectionSymbol] = model.prototype.collection; - // apply methods and statics - applyMethods(model, schema); - applyStatics(model, schema); - applyHooks(model, schema); - applyStaticHooks(model, schema.s.hooks, schema.statics); +const SchemaTypeOptions = __nccwpck_require__(7544); - model.schema = model.prototype.$__schema; - model.collection = model.prototype.collection; - model.$__collection = model.collection; +/** + * The options defined on an Document Array schematype. + * + * ####Example: + * + * const schema = new Schema({ users: [{ name: string }] }); + * schema.path('users').options; // SchemaDocumentArrayOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaDocumentOptions + */ - // Create custom query constructor - model.Query = function () { - Query.apply(this, arguments); - }; - model.Query.prototype = Object.create(Query.prototype); - model.Query.base = Query.base; - applyQueryMiddleware(model.Query, model); - applyQueryMethods(model, schema.query); +class SchemaDocumentArrayOptions extends SchemaTypeOptions {} - return model; - }; +const opts = __nccwpck_require__(1090); - /*! - * Register custom query methods for this model - * - * @param {Model} model - * @param {Schema} schema - */ +/** + * If `true`, Mongoose will skip building any indexes defined in this array's schema. + * If not set, Mongoose will build all indexes defined in this array's schema. + * + * ####Example: + * + * const childSchema = Schema({ name: { type: String, index: true } }); + * // If `excludeIndexes` is `true`, Mongoose will skip building an index + * // on `arr.name`. Otherwise, Mongoose will build an index on `arr.name`. + * const parentSchema = Schema({ + * arr: { type: [childSchema], excludeIndexes: true } + * }); + * + * @api public + * @property excludeIndexes + * @memberOf SchemaDocumentArrayOptions + * @type Array + * @instance + */ - function applyQueryMethods(model, methods) { - for (const i in methods) { - model.Query.prototype[i] = methods[i]; - } - } +Object.defineProperty(SchemaDocumentArrayOptions.prototype, 'excludeIndexes', opts); - /*! - * Subclass this model with `conn`, `schema`, and `collection` settings. - * - * @param {Connection} conn - * @param {Schema} [schema] - * @param {String} [collection] - * @return {Model} - */ +/** + * If set, overwrites the child schema's `_id` option. + * + * ####Example: + * + * const childSchema = Schema({ name: String }); + * const parentSchema = Schema({ + * child: { type: childSchema, _id: false } + * }); + * parentSchema.path('child').schema.options._id; // false + * + * @api public + * @property _id + * @memberOf SchemaDocumentArrayOptions + * @type Array + * @instance + */ - Model.__subclass = function subclass(conn, schema, collection) { - // subclass model using this connection and collection name - const _this = this; +Object.defineProperty(SchemaDocumentArrayOptions.prototype, '_id', opts); - const Model = function Model(doc, fields, skipId) { - if (!(this instanceof Model)) { - return new Model(doc, fields, skipId); - } - _this.call(this, doc, fields, skipId); - }; +/*! + * ignore + */ - Model.__proto__ = _this; - Model.prototype.__proto__ = _this.prototype; - Model.db = conn; - Model.prototype.db = conn; - Model.prototype[modelDbSymbol] = conn; - - _this[subclassedSymbol] = _this[subclassedSymbol] || []; - _this[subclassedSymbol].push(Model); - if (_this.discriminators != null) { - Model.discriminators = {}; - for (const key of Object.keys(_this.discriminators)) { - Model.discriminators[key] = _this.discriminators[key].__subclass( - _this.db, - _this.discriminators[key].schema, - collection - ); - } - } +module.exports = SchemaDocumentArrayOptions; - const s = - schema && typeof schema !== "string" - ? schema - : _this.prototype.$__schema; +/***/ }), - const options = s.options || {}; - const _userProvidedOptions = s._userProvidedOptions || {}; +/***/ 2809: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!collection) { - collection = - _this.prototype.$__schema.get("collection") || - utils.toCollectionName(_this.modelName, this.base.pluralize()); - } +"use strict"; - const collectionOptions = { - schemaUserProvidedOptions: _userProvidedOptions, - capped: s && options.capped, - }; - Model.prototype.collection = conn.collection( - collection, - collectionOptions - ); - Model.prototype[modelCollectionSymbol] = Model.prototype.collection; - Model.collection = Model.prototype.collection; - Model.$__collection = Model.collection; - // Errors handled internally, so ignore - Model.init(() => {}); - return Model; - }; +const SchemaTypeOptions = __nccwpck_require__(7544); - Model.$handleCallbackError = function (callback) { - if (callback == null) { - return callback; - } - if (typeof callback !== "function") { - throw new MongooseError( - "Callback must be a function, got " + callback - ); - } +/** + * The options defined on a Map schematype. + * + * ####Example: + * + * const schema = new Schema({ socialMediaHandles: { type: Map, of: String } }); + * schema.path('socialMediaHandles').options; // SchemaMapOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaMapOptions + */ - const _this = this; - return function () { - immediate(() => { - try { - callback.apply(null, arguments); - } catch (error) { - _this.emit("error", error); - } - }); - }; - }; +class SchemaMapOptions extends SchemaTypeOptions {} - /*! - * ignore - */ +const opts = __nccwpck_require__(1090); - Model.$wrapCallback = function (callback) { - const serverSelectionError = new ServerSelectionError(); - const _this = this; +/** + * If set, specifies the type of this map's values. Mongoose will cast + * this map's values to the given type. + * + * If not set, Mongoose will not cast the map's values. + * + * ####Example: + * + * // Mongoose will cast `socialMediaHandles` values to strings + * const schema = new Schema({ socialMediaHandles: { type: Map, of: String } }); + * schema.path('socialMediaHandles').options.of; // String + * + * @api public + * @property of + * @memberOf SchemaMapOptions + * @type Function|string + * @instance + */ - return function (err) { - if (err != null && err.name === "MongoServerSelectionError") { - arguments[0] = serverSelectionError.assimilateError(err); - } - if ( - err != null && - err.name === "MongoNetworkTimeoutError" && - err.message.endsWith("timed out") - ) { - _this.db.emit("timeout"); - } +Object.defineProperty(SchemaMapOptions.prototype, 'of', opts); - return callback.apply(null, arguments); - }; - }; +module.exports = SchemaMapOptions; - /** - * Helper for console.log. Given a model named 'MyModel', returns the string - * `'Model { MyModel }'`. - * - * ####Example: - * - * const MyModel = mongoose.model('Test', Schema({ name: String })); - * MyModel.inspect(); // 'Model { Test }' - * console.log(MyModel); // Prints 'Model { Test }' - * - * @api public - */ - - Model.inspect = function () { - return `Model { ${this.modelName} }`; - }; +/***/ }), - if (util.inspect.custom) { - /*! - * Avoid Node deprecation warning DEP0079 - */ +/***/ 1079: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Model[util.inspect.custom] = Model.inspect; - } +"use strict"; - /*! - * Module exports. - */ - module.exports = exports = Model; +const SchemaTypeOptions = __nccwpck_require__(7544); - /***/ - }, +/** + * The options defined on a Number schematype. + * + * ####Example: + * + * const schema = new Schema({ count: Number }); + * schema.path('count').options; // SchemaNumberOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaNumberOptions + */ - /***/ 5684: /***/ (__unused_webpack_module, exports) => { - "use strict"; +class SchemaNumberOptions extends SchemaTypeOptions {} - /*! - * ignore - */ +const opts = __nccwpck_require__(1090); - exports.h = { - transform: false, - virtuals: false, - getters: false, - _skipDepopulateTopLevel: true, - depopulate: true, - flattenDecimals: false, - useProjection: false, - }; +/** + * If set, Mongoose adds a validator that checks that this path is at least the + * given `min`. + * + * @api public + * @property min + * @memberOf SchemaNumberOptions + * @type Number + * @instance + */ - /***/ - }, +Object.defineProperty(SchemaNumberOptions.prototype, 'min', opts); + +/** + * If set, Mongoose adds a validator that checks that this path is less than the + * given `max`. + * + * @api public + * @property max + * @memberOf SchemaNumberOptions + * @type Number + * @instance + */ - /***/ 7038: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +Object.defineProperty(SchemaNumberOptions.prototype, 'max', opts); - const clone = __nccwpck_require__(5092); +/** + * If set, Mongoose adds a validator that checks that this path is strictly + * equal to one of the given values. + * + * ####Example: + * const schema = new Schema({ + * favoritePrime: { + * type: Number, + * enum: [3, 5, 7] + * } + * }); + * schema.path('favoritePrime').options.enum; // [3, 5, 7] + * + * @api public + * @property enum + * @memberOf SchemaNumberOptions + * @type Array + * @instance + */ - class PopulateOptions { - constructor(obj) { - this._docs = {}; - this._childDocs = []; +Object.defineProperty(SchemaNumberOptions.prototype, 'enum', opts); - if (obj == null) { - return; - } - obj = clone(obj); - Object.assign(this, obj); - if (typeof obj.subPopulate === "object") { - this.populate = obj.subPopulate; - } +/** + * Sets default [populate options](/docs/populate.html#query-conditions). + * + * ####Example: + * const schema = new Schema({ + * child: { + * type: Number, + * ref: 'Child', + * populate: { select: 'name' } + * } + * }); + * const Parent = mongoose.model('Parent', schema); + * + * // Automatically adds `.select('name')` + * Parent.findOne().populate('child'); + * + * @api public + * @property populate + * @memberOf SchemaNumberOptions + * @type Object + * @instance + */ - if (obj.perDocumentLimit != null && obj.limit != null) { - throw new Error( - "Can not use `limit` and `perDocumentLimit` at the same time. Path: `" + - obj.path + - "`." - ); - } - } - } +Object.defineProperty(SchemaNumberOptions.prototype, 'populate', opts); - /** - * The connection used to look up models by name. If not specified, Mongoose - * will default to using the connection associated with the model in - * `PopulateOptions#model`. - * - * @memberOf PopulateOptions - * @property {Connection} connection - * @api public - */ +/*! + * ignore + */ - module.exports = PopulateOptions; +module.exports = SchemaNumberOptions; - /***/ - }, +/***/ }), - /***/ 7391: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const SchemaTypeOptions = __nccwpck_require__(7544); - - /** - * The options defined on an Array schematype. - * - * ####Example: - * - * const schema = new Schema({ tags: [String] }); - * schema.path('tags').options; // SchemaArrayOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaArrayOptions - */ - - class SchemaArrayOptions extends SchemaTypeOptions {} - - const opts = __nccwpck_require__(1090); - - /** - * If this is an array of strings, an array of allowed values for this path. - * Throws an error if this array isn't an array of strings. - * - * @api public - * @property enum - * @memberOf SchemaArrayOptions - * @type Array - * @instance - */ - - Object.defineProperty(SchemaArrayOptions.prototype, "enum", opts); - - /** - * If set, specifies the type of this array's values. Equivalent to setting - * `type` to an array whose first element is `of`. - * - * ####Example: - * - * // `arr` is an array of numbers. - * new Schema({ arr: [Number] }); - * // Equivalent way to define `arr` as an array of numbers - * new Schema({ arr: { type: Array, of: Number } }); - * - * @api public - * @property of - * @memberOf SchemaArrayOptions - * @type Function|String - * @instance - */ - - Object.defineProperty(SchemaArrayOptions.prototype, "of", opts); - - /*! - * ignore - */ - - module.exports = SchemaArrayOptions; - - /***/ - }, +/***/ 1374: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /***/ 6680: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const SchemaTypeOptions = __nccwpck_require__(7544); - - /** - * The options defined on a Buffer schematype. - * - * ####Example: - * - * const schema = new Schema({ bitmap: Buffer }); - * schema.path('bitmap').options; // SchemaBufferOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaBufferOptions - */ - - class SchemaBufferOptions extends SchemaTypeOptions {} - - const opts = __nccwpck_require__(1090); - - /** - * Set the default subtype for this buffer. - * - * @api public - * @property subtype - * @memberOf SchemaBufferOptions - * @type Number - * @instance - */ - - Object.defineProperty(SchemaBufferOptions.prototype, "subtype", opts); - - /*! - * ignore - */ - - module.exports = SchemaBufferOptions; - - /***/ - }, +"use strict"; - /***/ 5354: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const SchemaTypeOptions = __nccwpck_require__(7544); - - /** - * The options defined on a Date schematype. - * - * ####Example: - * - * const schema = new Schema({ startedAt: Date }); - * schema.path('startedAt').options; // SchemaDateOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaDateOptions - */ - - class SchemaDateOptions extends SchemaTypeOptions {} - - const opts = __nccwpck_require__(1090); - - /** - * If set, Mongoose adds a validator that checks that this path is after the - * given `min`. - * - * @api public - * @property min - * @memberOf SchemaDateOptions - * @type Date - * @instance - */ - - Object.defineProperty(SchemaDateOptions.prototype, "min", opts); - - /** - * If set, Mongoose adds a validator that checks that this path is before the - * given `max`. - * - * @api public - * @property max - * @memberOf SchemaDateOptions - * @type Date - * @instance - */ - - Object.defineProperty(SchemaDateOptions.prototype, "max", opts); - - /** - * If set, Mongoose creates a TTL index on this path. - * - * @api public - * @property expires - * @memberOf SchemaDateOptions - * @type Date - * @instance - */ - - Object.defineProperty(SchemaDateOptions.prototype, "expires", opts); - - /*! - * ignore - */ - - module.exports = SchemaDateOptions; - - /***/ - }, - /***/ 4508: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const SchemaTypeOptions = __nccwpck_require__(7544); - - /** - * The options defined on an Document Array schematype. - * - * ####Example: - * - * const schema = new Schema({ users: [{ name: string }] }); - * schema.path('users').options; // SchemaDocumentArrayOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaDocumentOptions - */ - - class SchemaDocumentArrayOptions extends SchemaTypeOptions {} - - const opts = __nccwpck_require__(1090); - - /** - * If `true`, Mongoose will skip building any indexes defined in this array's schema. - * If not set, Mongoose will build all indexes defined in this array's schema. - * - * ####Example: - * - * const childSchema = Schema({ name: { type: String, index: true } }); - * // If `excludeIndexes` is `true`, Mongoose will skip building an index - * // on `arr.name`. Otherwise, Mongoose will build an index on `arr.name`. - * const parentSchema = Schema({ - * arr: { type: [childSchema], excludeIndexes: true } - * }); - * - * @api public - * @property excludeIndexes - * @memberOf SchemaDocumentArrayOptions - * @type Array - * @instance - */ - - Object.defineProperty( - SchemaDocumentArrayOptions.prototype, - "excludeIndexes", - opts - ); +const SchemaTypeOptions = __nccwpck_require__(7544); - /** - * If set, overwrites the child schema's `_id` option. - * - * ####Example: - * - * const childSchema = Schema({ name: String }); - * const parentSchema = Schema({ - * child: { type: childSchema, _id: false } - * }); - * parentSchema.path('child').schema.options._id; // false - * - * @api public - * @property _id - * @memberOf SchemaDocumentArrayOptions - * @type Array - * @instance - */ - - Object.defineProperty(SchemaDocumentArrayOptions.prototype, "_id", opts); - - /*! - * ignore - */ - - module.exports = SchemaDocumentArrayOptions; - - /***/ - }, +/** + * The options defined on an ObjectId schematype. + * + * ####Example: + * + * const schema = new Schema({ testId: mongoose.ObjectId }); + * schema.path('testId').options; // SchemaObjectIdOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaObjectIdOptions + */ - /***/ 2809: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const SchemaTypeOptions = __nccwpck_require__(7544); - - /** - * The options defined on a Map schematype. - * - * ####Example: - * - * const schema = new Schema({ socialMediaHandles: { type: Map, of: String } }); - * schema.path('socialMediaHandles').options; // SchemaMapOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaMapOptions - */ - - class SchemaMapOptions extends SchemaTypeOptions {} - - const opts = __nccwpck_require__(1090); - - /** - * If set, specifies the type of this map's values. Mongoose will cast - * this map's values to the given type. - * - * If not set, Mongoose will not cast the map's values. - * - * ####Example: - * - * // Mongoose will cast `socialMediaHandles` values to strings - * const schema = new Schema({ socialMediaHandles: { type: Map, of: String } }); - * schema.path('socialMediaHandles').options.of; // String - * - * @api public - * @property of - * @memberOf SchemaMapOptions - * @type Function|string - * @instance - */ - - Object.defineProperty(SchemaMapOptions.prototype, "of", opts); - - module.exports = SchemaMapOptions; - - /***/ - }, +class SchemaObjectIdOptions extends SchemaTypeOptions {} - /***/ 1079: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const SchemaTypeOptions = __nccwpck_require__(7544); - - /** - * The options defined on a Number schematype. - * - * ####Example: - * - * const schema = new Schema({ count: Number }); - * schema.path('count').options; // SchemaNumberOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaNumberOptions - */ - - class SchemaNumberOptions extends SchemaTypeOptions {} - - const opts = __nccwpck_require__(1090); - - /** - * If set, Mongoose adds a validator that checks that this path is at least the - * given `min`. - * - * @api public - * @property min - * @memberOf SchemaNumberOptions - * @type Number - * @instance - */ - - Object.defineProperty(SchemaNumberOptions.prototype, "min", opts); - - /** - * If set, Mongoose adds a validator that checks that this path is less than the - * given `max`. - * - * @api public - * @property max - * @memberOf SchemaNumberOptions - * @type Number - * @instance - */ - - Object.defineProperty(SchemaNumberOptions.prototype, "max", opts); - - /** - * If set, Mongoose adds a validator that checks that this path is strictly - * equal to one of the given values. - * - * ####Example: - * const schema = new Schema({ - * favoritePrime: { - * type: Number, - * enum: [3, 5, 7] - * } - * }); - * schema.path('favoritePrime').options.enum; // [3, 5, 7] - * - * @api public - * @property enum - * @memberOf SchemaNumberOptions - * @type Array - * @instance - */ - - Object.defineProperty(SchemaNumberOptions.prototype, "enum", opts); - - /** - * Sets default [populate options](/docs/populate.html#query-conditions). - * - * ####Example: - * const schema = new Schema({ - * child: { - * type: Number, - * ref: 'Child', - * populate: { select: 'name' } - * } - * }); - * const Parent = mongoose.model('Parent', schema); - * - * // Automatically adds `.select('name')` - * Parent.findOne().populate('child'); - * - * @api public - * @property populate - * @memberOf SchemaNumberOptions - * @type Object - * @instance - */ - - Object.defineProperty(SchemaNumberOptions.prototype, "populate", opts); - - /*! - * ignore - */ - - module.exports = SchemaNumberOptions; - - /***/ - }, +const opts = __nccwpck_require__(1090); - /***/ 1374: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const SchemaTypeOptions = __nccwpck_require__(7544); - - /** - * The options defined on an ObjectId schematype. - * - * ####Example: - * - * const schema = new Schema({ testId: mongoose.ObjectId }); - * schema.path('testId').options; // SchemaObjectIdOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaObjectIdOptions - */ - - class SchemaObjectIdOptions extends SchemaTypeOptions {} - - const opts = __nccwpck_require__(1090); - - /** - * If truthy, uses Mongoose's default built-in ObjectId path. - * - * @api public - * @property auto - * @memberOf SchemaObjectIdOptions - * @type Boolean - * @instance - */ - - Object.defineProperty(SchemaObjectIdOptions.prototype, "auto", opts); - - /** - * Sets default [populate options](/docs/populate.html#query-conditions). - * - * ####Example: - * const schema = new Schema({ - * child: { - * type: 'ObjectId', - * ref: 'Child', - * populate: { select: 'name' } - * } - * }); - * const Parent = mongoose.model('Parent', schema); - * - * // Automatically adds `.select('name')` - * Parent.findOne().populate('child'); - * - * @api public - * @property populate - * @memberOf SchemaObjectIdOptions - * @type Object - * @instance - */ - - Object.defineProperty(SchemaObjectIdOptions.prototype, "populate", opts); - - /*! - * ignore - */ - - module.exports = SchemaObjectIdOptions; - - /***/ - }, +/** + * If truthy, uses Mongoose's default built-in ObjectId path. + * + * @api public + * @property auto + * @memberOf SchemaObjectIdOptions + * @type Boolean + * @instance + */ - /***/ 5815: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const SchemaTypeOptions = __nccwpck_require__(7544); - - /** - * The options defined on a single nested schematype. - * - * ####Example: - * - * const schema = Schema({ child: Schema({ name: String }) }); - * schema.path('child').options; // SchemaSingleNestedOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaSingleNestedOptions - */ - - class SchemaSingleNestedOptions extends SchemaTypeOptions {} - - const opts = __nccwpck_require__(1090); - - /** - * If set, overwrites the child schema's `_id` option. - * - * ####Example: - * - * const childSchema = Schema({ name: String }); - * const parentSchema = Schema({ - * child: { type: childSchema, _id: false } - * }); - * parentSchema.path('child').schema.options._id; // false - * - * @api public - * @property of - * @memberOf SchemaSingleNestedOptions - * @type Function|string - * @instance - */ - - Object.defineProperty(SchemaSingleNestedOptions.prototype, "_id", opts); - - module.exports = SchemaSingleNestedOptions; - - /***/ - }, +Object.defineProperty(SchemaObjectIdOptions.prototype, 'auto', opts); - /***/ 7692: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const SchemaTypeOptions = __nccwpck_require__(7544); - - /** - * The options defined on a string schematype. - * - * ####Example: - * - * const schema = new Schema({ name: String }); - * schema.path('name').options; // SchemaStringOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaStringOptions - */ - - class SchemaStringOptions extends SchemaTypeOptions {} - - const opts = __nccwpck_require__(1090); - - /** - * Array of allowed values for this path - * - * @api public - * @property enum - * @memberOf SchemaStringOptions - * @type Array - * @instance - */ - - Object.defineProperty(SchemaStringOptions.prototype, "enum", opts); - - /** - * Attach a validator that succeeds if the data string matches the given regular - * expression, and fails otherwise. - * - * @api public - * @property match - * @memberOf SchemaStringOptions - * @type RegExp - * @instance - */ - - Object.defineProperty(SchemaStringOptions.prototype, "match", opts); - - /** - * If truthy, Mongoose will add a custom setter that lowercases this string - * using JavaScript's built-in `String#toLowerCase()`. - * - * @api public - * @property lowercase - * @memberOf SchemaStringOptions - * @type Boolean - * @instance - */ - - Object.defineProperty(SchemaStringOptions.prototype, "lowercase", opts); - - /** - * If truthy, Mongoose will add a custom setter that removes leading and trailing - * whitespace using JavaScript's built-in `String#trim()`. - * - * @api public - * @property trim - * @memberOf SchemaStringOptions - * @type Boolean - * @instance - */ - - Object.defineProperty(SchemaStringOptions.prototype, "trim", opts); - - /** - * If truthy, Mongoose will add a custom setter that uppercases this string - * using JavaScript's built-in `String#toUpperCase()`. - * - * @api public - * @property uppercase - * @memberOf SchemaStringOptions - * @type Boolean - * @instance - */ - - Object.defineProperty(SchemaStringOptions.prototype, "uppercase", opts); - - /** - * If set, Mongoose will add a custom validator that ensures the given - * string's `length` is at least the given number. - * - * Mongoose supports two different spellings for this option: `minLength` and `minlength`. - * `minLength` is the recommended way to specify this option, but Mongoose also supports - * `minlength` (lowercase "l"). - * - * @api public - * @property minLength - * @memberOf SchemaStringOptions - * @type Number - * @instance - */ - - Object.defineProperty(SchemaStringOptions.prototype, "minLength", opts); - Object.defineProperty(SchemaStringOptions.prototype, "minlength", opts); - - /** - * If set, Mongoose will add a custom validator that ensures the given - * string's `length` is at most the given number. - * - * Mongoose supports two different spellings for this option: `maxLength` and `maxlength`. - * `maxLength` is the recommended way to specify this option, but Mongoose also supports - * `maxlength` (lowercase "l"). - * - * @api public - * @property maxLength - * @memberOf SchemaStringOptions - * @type Number - * @instance - */ - - Object.defineProperty(SchemaStringOptions.prototype, "maxLength", opts); - Object.defineProperty(SchemaStringOptions.prototype, "maxlength", opts); - - /** - * Sets default [populate options](/docs/populate.html#query-conditions). - * - * @api public - * @property populate - * @memberOf SchemaStringOptions - * @type Object - * @instance - */ - - Object.defineProperty(SchemaStringOptions.prototype, "populate", opts); - - /*! - * ignore - */ - - module.exports = SchemaStringOptions; - - /***/ - }, +/** + * Sets default [populate options](/docs/populate.html#query-conditions). + * + * ####Example: + * const schema = new Schema({ + * child: { + * type: 'ObjectId', + * ref: 'Child', + * populate: { select: 'name' } + * } + * }); + * const Parent = mongoose.model('Parent', schema); + * + * // Automatically adds `.select('name')` + * Parent.findOne().populate('child'); + * + * @api public + * @property populate + * @memberOf SchemaObjectIdOptions + * @type Object + * @instance + */ - /***/ 7544: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const clone = __nccwpck_require__(5092); - - /** - * The options defined on a schematype. - * - * ####Example: - * - * const schema = new Schema({ name: String }); - * schema.path('name').options instanceof mongoose.SchemaTypeOptions; // true - * - * @api public - * @constructor SchemaTypeOptions - */ - - class SchemaTypeOptions { - constructor(obj) { - if (obj == null) { - return this; - } - Object.assign(this, clone(obj)); - } - } - - const opts = __nccwpck_require__(1090); - - /** - * The type to cast this path to. - * - * @api public - * @property type - * @memberOf SchemaTypeOptions - * @type Function|String|Object - * @instance - */ - - Object.defineProperty(SchemaTypeOptions.prototype, "type", opts); - - /** - * Function or object describing how to validate this schematype. - * - * @api public - * @property validate - * @memberOf SchemaTypeOptions - * @type Function|Object - * @instance - */ - - Object.defineProperty(SchemaTypeOptions.prototype, "validate", opts); - - /** - * Allows overriding casting logic for this individual path. If a string, the - * given string overwrites Mongoose's default cast error message. - * - * ####Example: - * - * const schema = new Schema({ - * num: { - * type: Number, - * cast: '{VALUE} is not a valid number' - * } - * }); - * - * // Throws 'CastError: "bad" is not a valid number' - * schema.path('num').cast('bad'); - * - * const Model = mongoose.model('Test', schema); - * const doc = new Model({ num: 'fail' }); - * const err = doc.validateSync(); - * - * err.errors['num']; // 'CastError: "fail" is not a valid number' - * - * @api public - * @property cast - * @memberOf SchemaTypeOptions - * @type String - * @instance - */ - - Object.defineProperty(SchemaTypeOptions.prototype, "cast", opts); - - /** - * If true, attach a required validator to this path, which ensures this path - * path cannot be set to a nullish value. If a function, Mongoose calls the - * function and only checks for nullish values if the function returns a truthy value. - * - * @api public - * @property required - * @memberOf SchemaTypeOptions - * @type Function|Boolean - * @instance - */ - - Object.defineProperty(SchemaTypeOptions.prototype, "required", opts); - - /** - * The default value for this path. If a function, Mongoose executes the function - * and uses the return value as the default. - * - * @api public - * @property default - * @memberOf SchemaTypeOptions - * @type Function|Any - * @instance - */ - - Object.defineProperty(SchemaTypeOptions.prototype, "default", opts); - - /** - * The model that `populate()` should use if populating this path. - * - * @api public - * @property ref - * @memberOf SchemaTypeOptions - * @type Function|String - * @instance - */ - - Object.defineProperty(SchemaTypeOptions.prototype, "ref", opts); - - /** - * Whether to include or exclude this path by default when loading documents - * using `find()`, `findOne()`, etc. - * - * @api public - * @property select - * @memberOf SchemaTypeOptions - * @type Boolean|Number - * @instance - */ - - Object.defineProperty(SchemaTypeOptions.prototype, "select", opts); - - /** - * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will - * build an index on this path when the model is compiled. - * - * @api public - * @property index - * @memberOf SchemaTypeOptions - * @type Boolean|Number|Object - * @instance - */ - - Object.defineProperty(SchemaTypeOptions.prototype, "index", opts); - - /** - * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose - * will build a unique index on this path when the - * model is compiled. [The `unique` option is **not** a validator](/docs/validation.html#the-unique-option-is-not-a-validator). - * - * @api public - * @property unique - * @memberOf SchemaTypeOptions - * @type Boolean|Number - * @instance - */ - - Object.defineProperty(SchemaTypeOptions.prototype, "unique", opts); - - /** - * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will - * disallow changes to this path once the document - * is saved to the database for the first time. Read more about [immutability in Mongoose here](http://thecodebarbarian.com/whats-new-in-mongoose-5-6-immutable-properties.html). - * - * @api public - * @property immutable - * @memberOf SchemaTypeOptions - * @type Function|Boolean - * @instance - */ - - Object.defineProperty(SchemaTypeOptions.prototype, "immutable", opts); - - /** - * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will - * build a sparse index on this path. - * - * @api public - * @property sparse - * @memberOf SchemaTypeOptions - * @type Boolean|Number - * @instance - */ - - Object.defineProperty(SchemaTypeOptions.prototype, "sparse", opts); - - /** - * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose - * will build a text index on this path. - * - * @api public - * @property text - * @memberOf SchemaTypeOptions - * @type Boolean|Number|Object - * @instance - */ - - Object.defineProperty(SchemaTypeOptions.prototype, "text", opts); - - /** - * Define a transform function for this individual schema type. - * Only called when calling `toJSON()` or `toObject()`. - * - * ####Example: - * - * const schema = Schema({ - * myDate: { - * type: Date, - * transform: v => v.getFullYear() - * } - * }); - * const Model = mongoose.model('Test', schema); - * - * const doc = new Model({ myDate: new Date('2019/06/01') }); - * doc.myDate instanceof Date; // true - * - * const res = doc.toObject({ transform: true }); - * res.myDate; // 2019 - * - * @api public - * @property transform - * @memberOf SchemaTypeOptions - * @type Function - * @instance - */ - - Object.defineProperty(SchemaTypeOptions.prototype, "transform", opts); - - module.exports = SchemaTypeOptions; - - /***/ - }, +Object.defineProperty(SchemaObjectIdOptions.prototype, 'populate', opts); - /***/ 5727: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +/*! + * ignore + */ - const opts = __nccwpck_require__(1090); +module.exports = SchemaObjectIdOptions; - class VirtualOptions { - constructor(obj) { - Object.assign(this, obj); +/***/ }), - if (obj != null && obj.options != null) { - this.options = Object.assign({}, obj.options); - } - } - } +/***/ 7692: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Marks this virtual as a populate virtual, and specifies the model to - * use for populate. - * - * @api public - * @property ref - * @memberOf VirtualOptions - * @type String|Model|Function - * @instance - */ - - Object.defineProperty(VirtualOptions.prototype, "ref", opts); - - /** - * Marks this virtual as a populate virtual, and specifies the path that - * contains the name of the model to populate - * - * @api public - * @property refPath - * @memberOf VirtualOptions - * @type String|Function - * @instance - */ - - Object.defineProperty(VirtualOptions.prototype, "refPath", opts); - - /** - * The name of the property in the local model to match to `foreignField` - * in the foreign model. - * - * @api public - * @property localField - * @memberOf VirtualOptions - * @type String|Function - * @instance - */ - - Object.defineProperty(VirtualOptions.prototype, "localField", opts); - - /** - * The name of the property in the foreign model to match to `localField` - * in the local model. - * - * @api public - * @property foreignField - * @memberOf VirtualOptions - * @type String|Function - * @instance - */ - - Object.defineProperty(VirtualOptions.prototype, "foreignField", opts); - - /** - * Whether to populate this virtual as a single document (true) or an - * array of documents (false). - * - * @api public - * @property justOne - * @memberOf VirtualOptions - * @type Boolean - * @instance - */ - - Object.defineProperty(VirtualOptions.prototype, "justOne", opts); - - /** - * If true, populate just the number of documents where `localField` - * matches `foreignField`, as opposed to the documents themselves. - * - * If `count` is set, it overrides `justOne`. - * - * @api public - * @property count - * @memberOf VirtualOptions - * @type Boolean - * @instance - */ - - Object.defineProperty(VirtualOptions.prototype, "count", opts); - - /** - * Add an additional filter to populate, in addition to `localField` - * matches `foreignField`. - * - * @api public - * @property match - * @memberOf VirtualOptions - * @type Object|Function - * @instance - */ - - Object.defineProperty(VirtualOptions.prototype, "match", opts); - - /** - * Additional options to pass to the query used to `populate()`: - * - * - `sort` - * - `skip` - * - `limit` - * - * @api public - * @property options - * @memberOf VirtualOptions - * @type Object - * @instance - */ - - Object.defineProperty(VirtualOptions.prototype, "options", opts); - - /** - * If true, add a `skip` to the query used to `populate()`. - * - * @api public - * @property skip - * @memberOf VirtualOptions - * @type Number - * @instance - */ - - Object.defineProperty(VirtualOptions.prototype, "skip", opts); - - /** - * If true, add a `limit` to the query used to `populate()`. - * - * @api public - * @property limit - * @memberOf VirtualOptions - * @type Number - * @instance - */ - - Object.defineProperty(VirtualOptions.prototype, "limit", opts); - - /** - * The `limit` option for `populate()` has [some unfortunate edge cases](/docs/populate.html#query-conditions) - * when working with multiple documents, like `.find().populate()`. The - * `perDocumentLimit` option makes `populate()` execute a separate query - * for each document returned from `find()` to ensure each document - * gets up to `perDocumentLimit` populated docs if possible. - * - * @api public - * @property perDocumentLimit - * @memberOf VirtualOptions - * @type Number - * @instance - */ - - Object.defineProperty(VirtualOptions.prototype, "perDocumentLimit", opts); - - module.exports = VirtualOptions; - - /***/ - }, +"use strict"; - /***/ 1090: /***/ (module) => { - "use strict"; - module.exports = Object.freeze({ - enumerable: true, - configurable: true, - writable: true, - value: void 0, - }); +const SchemaTypeOptions = __nccwpck_require__(7544); - /***/ - }, +/** + * The options defined on a string schematype. + * + * ####Example: + * + * const schema = new Schema({ name: String }); + * schema.path('name').options; // SchemaStringOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaStringOptions + */ - /***/ 2258: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +class SchemaStringOptions extends SchemaTypeOptions {} - const clone = __nccwpck_require__(5092); +const opts = __nccwpck_require__(1090); - class RemoveOptions { - constructor(obj) { - if (obj == null) { - return; - } - Object.assign(this, clone(obj)); - } - } +/** + * Array of allowed values for this path + * + * @api public + * @property enum + * @memberOf SchemaStringOptions + * @type Array + * @instance + */ - module.exports = RemoveOptions; +Object.defineProperty(SchemaStringOptions.prototype, 'enum', opts); - /***/ - }, +/** + * Attach a validator that succeeds if the data string matches the given regular + * expression, and fails otherwise. + * + * @api public + * @property match + * @memberOf SchemaStringOptions + * @type RegExp + * @instance + */ - /***/ 8792: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +Object.defineProperty(SchemaStringOptions.prototype, 'match', opts); - const clone = __nccwpck_require__(5092); +/** + * If truthy, Mongoose will add a custom setter that lowercases this string + * using JavaScript's built-in `String#toLowerCase()`. + * + * @api public + * @property lowercase + * @memberOf SchemaStringOptions + * @type Boolean + * @instance + */ - class SaveOptions { - constructor(obj) { - if (obj == null) { - return; - } - Object.assign(this, clone(obj)); - } - } +Object.defineProperty(SchemaStringOptions.prototype, 'lowercase', opts); - module.exports = SaveOptions; +/** + * If truthy, Mongoose will add a custom setter that removes leading and trailing + * whitespace using [JavaScript's built-in `String#trim()`](https://masteringjs.io/tutorials/fundamentals/trim-string). + * + * @api public + * @property trim + * @memberOf SchemaStringOptions + * @type Boolean + * @instance + */ - /***/ - }, +Object.defineProperty(SchemaStringOptions.prototype, 'trim', opts); - /***/ 3816: /***/ (module) => { - "use strict"; +/** + * If truthy, Mongoose will add a custom setter that uppercases this string + * using JavaScript's built-in [`String#toUpperCase()`](https://masteringjs.io/tutorials/fundamentals/uppercase). + * + * @api public + * @property uppercase + * @memberOf SchemaStringOptions + * @type Boolean + * @instance + */ - /*! - * ignore - */ +Object.defineProperty(SchemaStringOptions.prototype, 'uppercase', opts); - module.exports = function (schema) { - // ensure the documents receive an id getter unless disabled - const autoIdGetter = - !schema.paths["id"] && - !schema.options.noVirtualId && - schema.options.id; - if (!autoIdGetter) { - return; - } +/** + * If set, Mongoose will add a custom validator that ensures the given + * string's `length` is at least the given number. + * + * Mongoose supports two different spellings for this option: `minLength` and `minlength`. + * `minLength` is the recommended way to specify this option, but Mongoose also supports + * `minlength` (lowercase "l"). + * + * @api public + * @property minLength + * @memberOf SchemaStringOptions + * @type Number + * @instance + */ - schema.virtual("id").get(idGetter); - }; +Object.defineProperty(SchemaStringOptions.prototype, 'minLength', opts); +Object.defineProperty(SchemaStringOptions.prototype, 'minlength', opts); - /*! - * Returns this documents _id cast to a string. - */ +/** + * If set, Mongoose will add a custom validator that ensures the given + * string's `length` is at most the given number. + * + * Mongoose supports two different spellings for this option: `maxLength` and `maxlength`. + * `maxLength` is the recommended way to specify this option, but Mongoose also supports + * `maxlength` (lowercase "l"). + * + * @api public + * @property maxLength + * @memberOf SchemaStringOptions + * @type Number + * @instance + */ - function idGetter() { - if (this._id != null) { - return String(this._id); - } +Object.defineProperty(SchemaStringOptions.prototype, 'maxLength', opts); +Object.defineProperty(SchemaStringOptions.prototype, 'maxlength', opts); - return null; - } +/** + * Sets default [populate options](/docs/populate.html#query-conditions). + * + * @api public + * @property populate + * @memberOf SchemaStringOptions + * @type Object + * @instance + */ - /***/ - }, +Object.defineProperty(SchemaStringOptions.prototype, 'populate', opts); - /***/ 1058: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const each = __nccwpck_require__(9965); - - /*! - * ignore - */ - - module.exports = function (schema) { - const unshift = true; - schema.s.hooks.pre( - "remove", - false, - function (next) { - if (this.ownerDocument) { - next(); - return; - } +/*! + * ignore + */ - const _this = this; - const subdocs = this.$getAllSubdocs(); +module.exports = SchemaStringOptions; - each( - subdocs, - function (subdoc, cb) { - subdoc.$__remove(cb); - }, - function (error) { - if (error) { - return _this.$__schema.s.hooks.execPost( - "remove:error", - _this, - [_this], - { error: error }, - function (error) { - next(error); - } - ); - } - next(); - } - ); - }, - null, - unshift - ); - }; - /***/ - }, +/***/ }), - /***/ 7277: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const each = __nccwpck_require__(9965); - - /*! - * ignore - */ - - module.exports = function (schema) { - const unshift = true; - schema.s.hooks.pre( - "save", - false, - function (next) { - if (this.ownerDocument) { - next(); - return; - } +/***/ 4244: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const _this = this; - const subdocs = this.$getAllSubdocs(); +"use strict"; - if (!subdocs.length) { - next(); - return; - } - each( - subdocs, - function (subdoc, cb) { - subdoc.$__schema.s.hooks.execPre( - "save", - subdoc, - function (err) { - cb(err); - } - ); - }, - function (error) { - if (error) { - return _this.$__schema.s.hooks.execPost( - "save:error", - _this, - [_this], - { error: error }, - function (error) { - next(error); - } - ); - } - next(); - } - ); - }, - null, - unshift - ); +const SchemaTypeOptions = __nccwpck_require__(7544); - schema.s.hooks.post( - "save", - function (doc, next) { - if (this.ownerDocument) { - next(); - return; - } +/** + * The options defined on a single nested schematype. + * + * ####Example: + * + * const schema = Schema({ child: Schema({ name: String }) }); + * schema.path('child').options; // SchemaSubdocumentOptions instance + * + * @api public + * @inherits SchemaTypeOptions + * @constructor SchemaSubdocumentOptions + */ - const _this = this; - const subdocs = this.$getAllSubdocs(); +class SchemaSubdocumentOptions extends SchemaTypeOptions {} - if (!subdocs.length) { - next(); - return; - } +const opts = __nccwpck_require__(1090); - each( - subdocs, - function (subdoc, cb) { - subdoc.$__schema.s.hooks.execPost( - "save", - subdoc, - [subdoc], - function (err) { - cb(err); - } - ); - }, - function (error) { - if (error) { - return _this.$__schema.s.hooks.execPost( - "save:error", - _this, - [_this], - { error: error }, - function (error) { - next(error); - } - ); - } - next(); - } - ); - }, - null, - unshift - ); - }; +/** + * If set, overwrites the child schema's `_id` option. + * + * ####Example: + * + * const childSchema = Schema({ name: String }); + * const parentSchema = Schema({ + * child: { type: childSchema, _id: false } + * }); + * parentSchema.path('child').schema.options._id; // false + * + * @api public + * @property of + * @memberOf SchemaSubdocumentOptions + * @type Function|string + * @instance + */ - /***/ - }, +Object.defineProperty(SchemaSubdocumentOptions.prototype, '_id', opts); - /***/ 94: /***/ (module, __unused_webpack_exports, __nccwpck_require__) => { - "use strict"; +module.exports = SchemaSubdocumentOptions; - const objectIdSymbol = __nccwpck_require__(3240).objectIdSymbol; - const utils = __nccwpck_require__(9232); +/***/ }), - /*! - * ignore - */ +/***/ 7544: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - module.exports = function shardingPlugin(schema) { - schema.post("init", function () { - storeShard.call(this); - return this; - }); - schema.pre("save", function (next) { - applyWhere.call(this); - next(); - }); - schema.pre("remove", function (next) { - applyWhere.call(this); - next(); - }); - schema.post("save", function () { - storeShard.call(this); - }); - }; +"use strict"; - /*! - * ignore - */ - function applyWhere() { - let paths; - let len; +const clone = __nccwpck_require__(5092); - if (this.$__.shardval) { - paths = Object.keys(this.$__.shardval); - len = paths.length; +/** + * The options defined on a schematype. + * + * ####Example: + * + * const schema = new Schema({ name: String }); + * schema.path('name').options instanceof mongoose.SchemaTypeOptions; // true + * + * @api public + * @constructor SchemaTypeOptions + */ - this.$where = this.$where || {}; - for (let i = 0; i < len; ++i) { - this.$where[paths[i]] = this.$__.shardval[paths[i]]; - } - } - } +class SchemaTypeOptions { + constructor(obj) { + if (obj == null) { + return this; + } + Object.assign(this, clone(obj)); + } +} - /*! - * ignore - */ +const opts = __nccwpck_require__(1090); - module.exports.storeShard = storeShard; +/** + * The type to cast this path to. + * + * @api public + * @property type + * @memberOf SchemaTypeOptions + * @type Function|String|Object + * @instance + */ - /*! - * ignore - */ +Object.defineProperty(SchemaTypeOptions.prototype, 'type', opts); - function storeShard() { - // backwards compat - const key = - this.$__schema.options.shardKey || this.$__schema.options.shardkey; - if (!utils.isPOJO(key)) { - return; - } +/** + * Function or object describing how to validate this schematype. + * + * @api public + * @property validate + * @memberOf SchemaTypeOptions + * @type Function|Object + * @instance + */ - const orig = (this.$__.shardval = {}); - const paths = Object.keys(key); - const len = paths.length; - let val; +Object.defineProperty(SchemaTypeOptions.prototype, 'validate', opts); - for (let i = 0; i < len; ++i) { - val = this.$__getValue(paths[i]); - if (val == null) { - orig[paths[i]] = val; - } else if (utils.isMongooseObject(val)) { - orig[paths[i]] = val.toObject({ - depopulate: true, - _isNested: true, - }); - } else if (val instanceof Date || val[objectIdSymbol]) { - orig[paths[i]] = val; - } else if (typeof val.valueOf === "function") { - orig[paths[i]] = val.valueOf(); - } else { - orig[paths[i]] = val; - } - } - } +/** + * Allows overriding casting logic for this individual path. If a string, the + * given string overwrites Mongoose's default cast error message. + * + * ####Example: + * + * const schema = new Schema({ + * num: { + * type: Number, + * cast: '{VALUE} is not a valid number' + * } + * }); + * + * // Throws 'CastError: "bad" is not a valid number' + * schema.path('num').cast('bad'); + * + * const Model = mongoose.model('Test', schema); + * const doc = new Model({ num: 'fail' }); + * const err = doc.validateSync(); + * + * err.errors['num']; // 'CastError: "fail" is not a valid number' + * + * @api public + * @property cast + * @memberOf SchemaTypeOptions + * @type String + * @instance + */ - /***/ - }, +Object.defineProperty(SchemaTypeOptions.prototype, 'cast', opts); - /***/ 8675: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +/** + * If true, attach a required validator to this path, which ensures this path + * cannot be set to a nullish value. If a function, Mongoose calls the + * function and only checks for nullish values if the function returns a truthy value. + * + * @api public + * @property required + * @memberOf SchemaTypeOptions + * @type Function|Boolean + * @instance + */ - const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; - const sessionNewDocuments = __nccwpck_require__(3240).sessionNewDocuments; +Object.defineProperty(SchemaTypeOptions.prototype, 'required', opts); - module.exports = function trackTransaction(schema) { - schema.pre("save", function () { - const session = this.$session(); - if (session == null) { - return; - } - if ( - session.transaction == null || - session[sessionNewDocuments] == null - ) { - return; - } +/** + * The default value for this path. If a function, Mongoose executes the function + * and uses the return value as the default. + * + * @api public + * @property default + * @memberOf SchemaTypeOptions + * @type Function|Any + * @instance + */ - if (!session[sessionNewDocuments].has(this)) { - const initialState = {}; - if (this.isNew) { - initialState.isNew = true; - } - if (this.$__schema.options.versionKey) { - initialState.versionKey = this.get( - this.$__schema.options.versionKey - ); - } +Object.defineProperty(SchemaTypeOptions.prototype, 'default', opts); - initialState.modifiedPaths = new Set( - Object.keys(this.$__.activePaths.states.modify) - ); - initialState.atomics = _getAtomics(this); +/** + * The model that `populate()` should use if populating this path. + * + * @api public + * @property ref + * @memberOf SchemaTypeOptions + * @type Function|String + * @instance + */ - session[sessionNewDocuments].set(this, initialState); - } else { - const state = session[sessionNewDocuments].get(this); +Object.defineProperty(SchemaTypeOptions.prototype, 'ref', opts); - for (const path of Object.keys( - this.$__.activePaths.states.modify - )) { - state.modifiedPaths.add(path); - } - state.atomics = _getAtomics(this, state.atomics); - } - }); - }; +/** + * Whether to include or exclude this path by default when loading documents + * using `find()`, `findOne()`, etc. + * + * @api public + * @property select + * @memberOf SchemaTypeOptions + * @type Boolean|Number + * @instance + */ - function _getAtomics(doc, previous) { - const pathToAtomics = new Map(); - previous = previous || new Map(); +Object.defineProperty(SchemaTypeOptions.prototype, 'select', opts); - const pathsToCheck = Object.keys(doc.$__.activePaths.init).concat( - Object.keys(doc.$__.activePaths.modify) - ); +/** + * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will + * build an index on this path when the model is compiled. + * + * @api public + * @property index + * @memberOf SchemaTypeOptions + * @type Boolean|Number|Object + * @instance + */ - for (const path of pathsToCheck) { - const val = doc.$__getValue(path); - if ( - val != null && - val instanceof Array && - val.isMongooseDocumentArray && - val.length && - val[arrayAtomicsSymbol] != null && - Object.keys(val[arrayAtomicsSymbol]).length > 0 - ) { - const existing = previous.get(path) || {}; - pathToAtomics.set( - path, - mergeAtomics(existing, val[arrayAtomicsSymbol]) - ); - } - } +Object.defineProperty(SchemaTypeOptions.prototype, 'index', opts); - const dirty = doc.$__dirty(); - for (const dirt of dirty) { - const path = dirt.path; - - const val = dirt.value; - if ( - val != null && - val[arrayAtomicsSymbol] != null && - Object.keys(val[arrayAtomicsSymbol]).length > 0 - ) { - const existing = previous.get(path) || {}; - pathToAtomics.set( - path, - mergeAtomics(existing, val[arrayAtomicsSymbol]) - ); - } - } +/** + * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose + * will build a unique index on this path when the + * model is compiled. [The `unique` option is **not** a validator](/docs/validation.html#the-unique-option-is-not-a-validator). + * + * @api public + * @property unique + * @memberOf SchemaTypeOptions + * @type Boolean|Number + * @instance + */ - return pathToAtomics; - } +Object.defineProperty(SchemaTypeOptions.prototype, 'unique', opts); - function mergeAtomics(destination, source) { - destination = destination || {}; +/** + * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will + * disallow changes to this path once the document + * is saved to the database for the first time. Read more about [immutability in Mongoose here](http://thecodebarbarian.com/whats-new-in-mongoose-5-6-immutable-properties.html). + * + * @api public + * @property immutable + * @memberOf SchemaTypeOptions + * @type Function|Boolean + * @instance + */ - if (source.$pullAll != null) { - destination.$pullAll = (destination.$pullAll || []).concat( - source.$pullAll - ); - } - if (source.$push != null) { - destination.$push = destination.$push || {}; - destination.$push.$each = (destination.$push.$each || []).concat( - source.$push.$each - ); - } - if (source.$addToSet != null) { - destination.$addToSet = (destination.$addToSet || []).concat( - source.$addToSet - ); - } - if (source.$set != null) { - destination.$set = Object.assign(destination.$set || {}, source.$set); - } +Object.defineProperty(SchemaTypeOptions.prototype, 'immutable', opts); - return destination; - } +/** + * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will + * build a sparse index on this path. + * + * @api public + * @property sparse + * @memberOf SchemaTypeOptions + * @type Boolean|Number + * @instance + */ - /***/ - }, +Object.defineProperty(SchemaTypeOptions.prototype, 'sparse', opts); - /***/ 1752: /***/ (module) => { - "use strict"; - - /*! - * ignore - */ - - module.exports = function (schema) { - const unshift = true; - schema.pre( - "save", - false, - function validateBeforeSave(next, options) { - const _this = this; - // Nested docs have their own presave - if (this.ownerDocument) { - return next(); - } - - const hasValidateBeforeSaveOption = - options && - typeof options === "object" && - "validateBeforeSave" in options; - - let shouldValidate; - if (hasValidateBeforeSaveOption) { - shouldValidate = !!options.validateBeforeSave; - } else { - shouldValidate = this.$__schema.options.validateBeforeSave; - } - - // Validate - if (shouldValidate) { - const hasValidateModifiedOnlyOption = - options && - typeof options === "object" && - "validateModifiedOnly" in options; - const validateOptions = hasValidateModifiedOnlyOption - ? { validateModifiedOnly: options.validateModifiedOnly } - : null; - this.validate(validateOptions, function (error) { - return _this.$__schema.s.hooks.execPost( - "save:error", - _this, - [_this], - { error: error }, - function (error) { - _this.$op = "save"; - next(error); - } - ); - }); - } else { - next(); - } - }, - null, - unshift - ); - }; +/** + * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose + * will build a text index on this path. + * + * @api public + * @property text + * @memberOf SchemaTypeOptions + * @type Boolean|Number|Object + * @instance + */ - /***/ - }, +Object.defineProperty(SchemaTypeOptions.prototype, 'text', opts); - /***/ 5176: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * ignore - */ - - const assert = __nccwpck_require__(2357); - const mquery = __nccwpck_require__(3821); - - /** - * Helper for multiplexing promise implementations - * - * @api private - */ - - const store = { - _promise: null, - }; +/** + * Define a transform function for this individual schema type. + * Only called when calling `toJSON()` or `toObject()`. + * + * ####Example: + * + * const schema = Schema({ + * myDate: { + * type: Date, + * transform: v => v.getFullYear() + * } + * }); + * const Model = mongoose.model('Test', schema); + * + * const doc = new Model({ myDate: new Date('2019/06/01') }); + * doc.myDate instanceof Date; // true + * + * const res = doc.toObject({ transform: true }); + * res.myDate; // 2019 + * + * @api public + * @property transform + * @memberOf SchemaTypeOptions + * @type Function + * @instance + */ - /** - * Get the current promise constructor - * - * @api private - */ +Object.defineProperty(SchemaTypeOptions.prototype, 'transform', opts); - store.get = function () { - return store._promise; - }; +module.exports = SchemaTypeOptions; - /** - * Set the current promise constructor - * - * @api private - */ +/***/ }), - store.set = function (lib) { - assert.ok( - typeof lib === "function", - `mongoose.Promise must be a function, got ${lib}` - ); - store._promise = lib; - mquery.Promise = lib; - }; +/***/ 5727: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /*! - * Use native promises by default - */ +"use strict"; - store.set(global.Promise); - module.exports = store; +const opts = __nccwpck_require__(1090); - /***/ - }, +class VirtualOptions { + constructor(obj) { + Object.assign(this, obj); - /***/ 1615: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const CastError = __nccwpck_require__(2798); - const DocumentNotFoundError = __nccwpck_require__(5147); - const Kareem = __nccwpck_require__(716); - const MongooseError = __nccwpck_require__(5953); - const ObjectParameterError = __nccwpck_require__(3456); - const QueryCursor = __nccwpck_require__(3588); - const ReadPreference = __nccwpck_require__(2324).get().ReadPreference; - const applyGlobalMaxTimeMS = __nccwpck_require__(7428); - const applyWriteConcern = __nccwpck_require__(5661); - const cast = __nccwpck_require__(8874); - const castArrayFilters = __nccwpck_require__(4856); - const castUpdate = __nccwpck_require__(3303); - const completeMany = __nccwpck_require__(2941); - const get = __nccwpck_require__(8730); - const promiseOrCallback = __nccwpck_require__(4046); - const getDiscriminatorByValue = __nccwpck_require__(8689); - const hasDollarKeys = __nccwpck_require__(8309); - const helpers = __nccwpck_require__(5299); - const immediate = __nccwpck_require__(4830); - const isExclusive = __nccwpck_require__(9197); - const isInclusive = __nccwpck_require__(2951); - const mquery = __nccwpck_require__(3821); - const parseProjection = __nccwpck_require__(7201); - const removeUnusedArrayFilters = __nccwpck_require__(8909); - const sanitizeProjection = __nccwpck_require__(8276); - const selectPopulatedFields = __nccwpck_require__(1907); - const setDefaultsOnInsert = __nccwpck_require__(5937); - const slice = __nccwpck_require__(9889); - const updateValidators = __nccwpck_require__(9009); - const util = __nccwpck_require__(1669); - const utils = __nccwpck_require__(9232); - const wrapThunk = __nccwpck_require__(2006); - - /** - * Query constructor used for building queries. You do not need - * to instantiate a `Query` directly. Instead use Model functions like - * [`Model.find()`](/docs/api.html#find_find). - * - * ####Example: - * - * const query = MyModel.find(); // `query` is an instance of `Query` - * query.setOptions({ lean : true }); - * query.collection(MyModel.collection); - * query.where('age').gte(21).exec(callback); - * - * // You can instantiate a query directly. There is no need to do - * // this unless you're an advanced user with a very good reason to. - * const query = new mongoose.Query(); - * - * @param {Object} [options] - * @param {Object} [model] - * @param {Object} [conditions] - * @param {Object} [collection] Mongoose collection - * @api public - */ - - function Query(conditions, options, model, collection) { - // this stuff is for dealing with custom queries created by #toConstructor - if (!this._mongooseOptions) { - this._mongooseOptions = {}; - } - options = options || {}; + if (obj != null && obj.options != null) { + this.options = Object.assign({}, obj.options); + } + } +} - this._transforms = []; - this._hooks = new Kareem(); - this._executionCount = 0; +/** + * Marks this virtual as a populate virtual, and specifies the model to + * use for populate. + * + * @api public + * @property ref + * @memberOf VirtualOptions + * @type String|Model|Function + * @instance + */ - // this is the case where we have a CustomQuery, we need to check if we got - // options passed in, and if we did, merge them in - const keys = Object.keys(options); - for (const key of keys) { - this._mongooseOptions[key] = options[key]; - } - - if (collection) { - this.mongooseCollection = collection; - } - - if (model) { - this.model = model; - this.schema = model.schema; - } - - // this is needed because map reduce returns a model that can be queried, but - // all of the queries on said model should be lean - if (this.model && this.model._mapreduce) { - this.lean(); - } - - // inherit mquery - mquery.call(this, this.mongooseCollection, options); - - if (conditions) { - this.find(conditions); - } - - this.options = this.options || {}; - - // For gh-6880. mquery still needs to support `fields` by default for old - // versions of MongoDB - this.$useProjection = true; - - const collation = get(this, "schema.options.collation", null); - if (collation != null) { - this.options.collation = collation; - } - } - - /*! - * inherit mquery - */ - - Query.prototype = new mquery(); - Query.prototype.constructor = Query; - Query.base = mquery.prototype; - - /** - * Flag to opt out of using `$geoWithin`. - * - * mongoose.Query.use$geoWithin = false; - * - * MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with `$within`). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work. - * - * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/ - * @default true - * @property use$geoWithin - * @memberOf Query - * @receiver Query - * @api public - */ - - Query.use$geoWithin = mquery.use$geoWithin; - - /** - * Converts this query to a customized, reusable query constructor with all arguments and options retained. - * - * ####Example - * - * // Create a query for adventure movies and read from the primary - * // node in the replica-set unless it is down, in which case we'll - * // read from a secondary node. - * const query = Movie.find({ tags: 'adventure' }).read('primaryPreferred'); - * - * // create a custom Query constructor based off these settings - * const Adventure = query.toConstructor(); - * - * // Adventure is now a subclass of mongoose.Query and works the same way but with the - * // default query parameters and options set. - * Adventure().exec(callback) - * - * // further narrow down our query results while still using the previous settings - * Adventure().where({ name: /^Life/ }).exec(callback); - * - * // since Adventure is a stand-alone constructor we can also add our own - * // helper methods and getters without impacting global queries - * Adventure.prototype.startsWith = function (prefix) { - * this.where({ name: new RegExp('^' + prefix) }) - * return this; - * } - * Object.defineProperty(Adventure.prototype, 'highlyRated', { - * get: function () { - * this.where({ rating: { $gt: 4.5 }}); - * return this; - * } - * }) - * Adventure().highlyRated.startsWith('Life').exec(callback) - * - * @return {Query} subclass-of-Query - * @api public - */ - - Query.prototype.toConstructor = function toConstructor() { - const model = this.model; - const coll = this.mongooseCollection; - - const CustomQuery = function (criteria, options) { - if (!(this instanceof CustomQuery)) { - return new CustomQuery(criteria, options); - } - this._mongooseOptions = utils.clone(p._mongooseOptions); - Query.call(this, criteria, options || null, model, coll); - }; +Object.defineProperty(VirtualOptions.prototype, 'ref', opts); - util.inherits(CustomQuery, model.Query); +/** + * Marks this virtual as a populate virtual, and specifies the path that + * contains the name of the model to populate + * + * @api public + * @property refPath + * @memberOf VirtualOptions + * @type String|Function + * @instance + */ - // set inherited defaults - const p = CustomQuery.prototype; +Object.defineProperty(VirtualOptions.prototype, 'refPath', opts); - p.options = {}; +/** + * The name of the property in the local model to match to `foreignField` + * in the foreign model. + * + * @api public + * @property localField + * @memberOf VirtualOptions + * @type String|Function + * @instance + */ - // Need to handle `sort()` separately because entries-style `sort()` syntax - // `sort([['prop1', 1]])` confuses mquery into losing the outer nested array. - // See gh-8159 - const options = Object.assign({}, this.options); - if (options.sort != null) { - p.sort(options.sort); - delete options.sort; - } - p.setOptions(options); +Object.defineProperty(VirtualOptions.prototype, 'localField', opts); - p.op = this.op; - p._conditions = utils.clone(this._conditions); - p._fields = utils.clone(this._fields); - p._update = utils.clone(this._update, { - flattenDecimals: false, - }); - p._path = this._path; - p._distinct = this._distinct; - p._collection = this._collection; - p._mongooseOptions = this._mongooseOptions; +/** + * The name of the property in the foreign model to match to `localField` + * in the local model. + * + * @api public + * @property foreignField + * @memberOf VirtualOptions + * @type String|Function + * @instance + */ - return CustomQuery; - }; +Object.defineProperty(VirtualOptions.prototype, 'foreignField', opts); - /** - * Specifies a javascript function or expression to pass to MongoDBs query system. - * - * ####Example - * - * query.$where('this.comments.length === 10 || this.name.length === 5') - * - * // or - * - * query.$where(function () { - * return this.comments.length === 10 || this.name.length === 5; - * }) - * - * ####NOTE: - * - * Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. - * **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.** - * - * @see $where http://docs.mongodb.org/manual/reference/operator/where/ - * @method $where - * @param {String|Function} js javascript string or function - * @return {Query} this - * @memberOf Query - * @instance - * @method $where - * @api public - */ - - /** - * Specifies a `path` for use with chaining. - * - * ####Example - * - * // instead of writing: - * User.find({age: {$gte: 21, $lte: 65}}, callback); - * - * // we can instead write: - * User.where('age').gte(21).lte(65); - * - * // passing query conditions is permitted - * User.find().where({ name: 'vonderful' }) - * - * // chaining - * User - * .where('age').gte(21).lte(65) - * .where('name', /^vonderful/i) - * .where('friends').slice(10) - * .exec(callback) - * - * @method where - * @memberOf Query - * @instance - * @param {String|Object} [path] - * @param {any} [val] - * @return {Query} this - * @api public - */ - - /** - * Specifies a `$slice` projection for an array. - * - * ####Example - * - * query.slice('comments', 5) - * query.slice('comments', -5) - * query.slice('comments', [10, 5]) - * query.where('comments').slice(5) - * query.where('comments').slice([-10, 5]) - * - * @method slice - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val number/range of elements to slice - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements - * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice - * @api public - */ - - Query.prototype.slice = function () { - if (arguments.length === 0) { - return this; - } +/** + * Whether to populate this virtual as a single document (true) or an + * array of documents (false). + * + * @api public + * @property justOne + * @memberOf VirtualOptions + * @type Boolean + * @instance + */ - this._validate("slice"); +Object.defineProperty(VirtualOptions.prototype, 'justOne', opts); - let path; - let val; +/** + * If true, populate just the number of documents where `localField` + * matches `foreignField`, as opposed to the documents themselves. + * + * If `count` is set, it overrides `justOne`. + * + * @api public + * @property count + * @memberOf VirtualOptions + * @type Boolean + * @instance + */ - if (arguments.length === 1) { - const arg = arguments[0]; - if (typeof arg === "object" && !Array.isArray(arg)) { - const keys = Object.keys(arg); - const numKeys = keys.length; - for (let i = 0; i < numKeys; ++i) { - this.slice(keys[i], arg[keys[i]]); - } - return this; - } - this._ensurePath("slice"); - path = this._path; - val = arguments[0]; - } else if (arguments.length === 2) { - if ("number" === typeof arguments[0]) { - this._ensurePath("slice"); - path = this._path; - val = slice(arguments); - } else { - path = arguments[0]; - val = arguments[1]; - } - } else if (arguments.length === 3) { - path = arguments[0]; - val = slice(arguments, 1); - } +Object.defineProperty(VirtualOptions.prototype, 'count', opts); - const p = {}; - p[path] = { $slice: val }; - this.select(p); +/** + * Add an additional filter to populate, in addition to `localField` + * matches `foreignField`. + * + * @api public + * @property match + * @memberOf VirtualOptions + * @type Object|Function + * @instance + */ - return this; - }; +Object.defineProperty(VirtualOptions.prototype, 'match', opts); - /** - * Specifies the complementary comparison value for paths specified with `where()` - * - * ####Example - * - * User.where('age').equals(49); - * - * // is the same as - * - * User.where('age', 49); - * - * @method equals - * @memberOf Query - * @instance - * @param {Object} val - * @return {Query} this - * @api public - */ - - /** - * Specifies arguments for an `$or` condition. - * - * ####Example - * - * query.or([{ color: 'red' }, { status: 'emergency' }]) - * - * @see $or http://docs.mongodb.org/manual/reference/operator/or/ - * @method or - * @memberOf Query - * @instance - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - - /** - * Specifies arguments for a `$nor` condition. - * - * ####Example - * - * query.nor([{ color: 'green' }, { status: 'ok' }]) - * - * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/ - * @method nor - * @memberOf Query - * @instance - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - - /** - * Specifies arguments for a `$and` condition. - * - * ####Example - * - * query.and([{ color: 'green' }, { status: 'ok' }]) - * - * @method and - * @memberOf Query - * @instance - * @see $and http://docs.mongodb.org/manual/reference/operator/and/ - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - - /** - * Specifies a `$gt` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * ####Example - * - * Thing.find().where('age').gt(21) - * - * // or - * Thing.find().gt('age', 21) - * - * @method gt - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/ - * @api public - */ - - /** - * Specifies a `$gte` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method gte - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/ - * @api public - */ - - /** - * Specifies a `$lt` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lt - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/ - * @api public - */ - - /** - * Specifies a `$lte` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lte - * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/ - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @api public - */ - - /** - * Specifies a `$ne` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/ - * @method ne - * @memberOf Query - * @instance - * @param {String} [path] - * @param {any} val - * @api public - */ - - /** - * Specifies an `$in` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $in http://docs.mongodb.org/manual/reference/operator/in/ - * @method in - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Array} val - * @api public - */ - - /** - * Specifies an `$nin` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/ - * @method nin - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Array} val - * @api public - */ - - /** - * Specifies an `$all` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * ####Example: - * - * MyModel.find().where('pets').all(['dog', 'cat', 'ferret']); - * // Equivalent: - * MyModel.find().all('pets', ['dog', 'cat', 'ferret']); - * - * @see $all http://docs.mongodb.org/manual/reference/operator/all/ - * @method all - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Array} val - * @api public - */ - - /** - * Specifies a `$size` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * ####Example - * - * MyModel.where('tags').size(0).exec(function (err, docs) { - * if (err) return handleError(err); - * - * assert(Array.isArray(docs)); - * console.log('documents with 0 tags', docs); - * }) - * - * @see $size http://docs.mongodb.org/manual/reference/operator/size/ - * @method size - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @api public - */ - - /** - * Specifies a `$regex` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/ - * @method regex - * @memberOf Query - * @instance - * @param {String} [path] - * @param {String|RegExp} val - * @api public - */ - - /** - * Specifies a `maxDistance` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ - * @method maxDistance - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @api public - */ - - /** - * Specifies a `$mod` condition, filters documents for documents whose - * `path` property is a number that is equal to `remainder` modulo `divisor`. - * - * ####Example - * - * // All find products whose inventory is odd - * Product.find().mod('inventory', [2, 1]); - * Product.find().where('inventory').mod([2, 1]); - * // This syntax is a little strange, but supported. - * Product.find().where('inventory').mod(2, 1); - * - * @method mod - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Array} val must be of length 2, first element is `divisor`, 2nd element is `remainder`. - * @return {Query} this - * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/ - * @api public - */ - - Query.prototype.mod = function () { - let val; - let path; - - if (arguments.length === 1) { - this._ensurePath("mod"); - val = arguments[0]; - path = this._path; - } else if (arguments.length === 2 && !Array.isArray(arguments[1])) { - this._ensurePath("mod"); - val = slice(arguments); - path = this._path; - } else if (arguments.length === 3) { - val = slice(arguments, 1); - path = arguments[0]; - } else { - val = arguments[1]; - path = arguments[0]; - } +/** + * Additional options to pass to the query used to `populate()`: + * + * - `sort` + * - `skip` + * - `limit` + * + * @api public + * @property options + * @memberOf VirtualOptions + * @type Object + * @instance + */ - const conds = this._conditions[path] || (this._conditions[path] = {}); - conds.$mod = val; - return this; - }; +Object.defineProperty(VirtualOptions.prototype, 'options', opts); - /** - * Specifies an `$exists` condition - * - * ####Example - * - * // { name: { $exists: true }} - * Thing.where('name').exists() - * Thing.where('name').exists(true) - * Thing.find().exists('name') - * - * // { name: { $exists: false }} - * Thing.where('name').exists(false); - * Thing.find().exists('name', false); - * - * @method exists - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Boolean} val - * @return {Query} this - * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/ - * @api public - */ - - /** - * Specifies an `$elemMatch` condition - * - * ####Example - * - * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) - * - * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) - * - * query.elemMatch('comment', function (elem) { - * elem.where('author').equals('autobot'); - * elem.where('votes').gte(5); - * }) - * - * query.where('comment').elemMatch(function (elem) { - * elem.where({ author: 'autobot' }); - * elem.where('votes').gte(5); - * }) - * - * @method elemMatch - * @memberOf Query - * @instance - * @param {String|Object|Function} path - * @param {Object|Function} filter - * @return {Query} this - * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/ - * @api public - */ - - /** - * Defines a `$within` or `$geoWithin` argument for geo-spatial queries. - * - * ####Example - * - * query.where(path).within().box() - * query.where(path).within().circle() - * query.where(path).within().geometry() - * - * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); - * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); - * query.where('loc').within({ polygon: [[],[],[],[]] }); - * - * query.where('loc').within([], [], []) // polygon - * query.where('loc').within([], []) // box - * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry - * - * **MUST** be used after `where()`. - * - * ####NOTE: - * - * As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin). - * - * ####NOTE: - * - * In Mongoose 3.7, `within` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). - * - * @method within - * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ - * @see $box http://docs.mongodb.org/manual/reference/operator/box/ - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @see $center http://docs.mongodb.org/manual/reference/operator/center/ - * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ - * @memberOf Query - * @instance - * @return {Query} this - * @api public - */ - - /** - * Specifies the maximum number of documents the query will return. - * - * ####Example - * - * query.limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method limit - * @memberOf Query - * @instance - * @param {Number} val - * @api public - */ - - /** - * Specifies the number of documents to skip. - * - * ####Example - * - * query.skip(100).limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method skip - * @memberOf Query - * @instance - * @param {Number} val - * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/ - * @api public - */ - - /** - * Specifies the maxScan option. - * - * ####Example - * - * query.maxScan(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method maxScan - * @memberOf Query - * @instance - * @param {Number} val - * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/ - * @api public - */ - - /** - * Specifies the batchSize option. - * - * ####Example - * - * query.batchSize(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method batchSize - * @memberOf Query - * @instance - * @param {Number} val - * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/ - * @api public - */ - - /** - * Specifies the `comment` option. - * - * ####Example - * - * query.comment('login query') - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method comment - * @memberOf Query - * @instance - * @param {String} val - * @see comment http://docs.mongodb.org/manual/reference/operator/comment/ - * @api public - */ - - /** - * Specifies this query as a `snapshot` query. - * - * ####Example - * - * query.snapshot() // true - * query.snapshot(true) - * query.snapshot(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method snapshot - * @memberOf Query - * @instance - * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/ - * @return {Query} this - * @api public - */ - - /** - * Sets query hints. - * - * ####Example - * - * query.hint({ indexA: 1, indexB: -1}) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method hint - * @memberOf Query - * @instance - * @param {Object} val a hint object - * @return {Query} this - * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/ - * @api public - */ - - /** - * Get/set the current projection (AKA fields). Pass `null` to remove the - * current projection. - * - * Unlike `projection()`, the `select()` function modifies the current - * projection in place. This function overwrites the existing projection. - * - * ####Example: - * - * const q = Model.find(); - * q.projection(); // null - * - * q.select('a b'); - * q.projection(); // { a: 1, b: 1 } - * - * q.projection({ c: 1 }); - * q.projection(); // { c: 1 } - * - * q.projection(null); - * q.projection(); // null - * - * - * @method projection - * @memberOf Query - * @instance - * @param {Object|null} arg - * @return {Object} the current projection - * @api public - */ - - Query.prototype.projection = function (arg) { - if (arguments.length === 0) { - return this._fields; - } - - this._fields = {}; - this._userProvidedFields = {}; - this.select(arg); - return this._fields; - }; +/** + * If true, add a `skip` to the query used to `populate()`. + * + * @api public + * @property skip + * @memberOf VirtualOptions + * @type Number + * @instance + */ - /** - * Specifies which document fields to include or exclude (also known as the query "projection") - * - * When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](/docs/api.html#schematype_SchemaType-select). - * - * A projection _must_ be either inclusive or exclusive. In other words, you must - * either list the fields to include (which excludes all others), or list the fields - * to exclude (which implies all other fields are included). The [`_id` field is the only exception because MongoDB includes it by default](https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#suppress-id-field). - * - * ####Example - * - * // include a and b, exclude other fields - * query.select('a b'); - * // Equivalent syntaxes: - * query.select(['a', 'b']); - * query.select({ a: 1, b: 1 }); - * - * // exclude c and d, include other fields - * query.select('-c -d'); - * - * // Use `+` to override schema-level `select: false` without making the - * // projection inclusive. - * const schema = new Schema({ - * foo: { type: String, select: false }, - * bar: String - * }); - * // ... - * query.select('+foo'); // Override foo's `select: false` without excluding `bar` - * - * // or you may use object notation, useful when - * // you have keys already prefixed with a "-" - * query.select({ a: 1, b: 1 }); - * query.select({ c: 0, d: 0 }); - * - * - * @method select - * @memberOf Query - * @instance - * @param {Object|String|Array} arg - * @return {Query} this - * @see SchemaType - * @api public - */ - - Query.prototype.select = function select() { - let arg = arguments[0]; - if (!arg) return this; - - if (arguments.length !== 1) { - throw new Error("Invalid select: select only takes 1 argument"); - } - - this._validate("select"); - - const fields = this._fields || (this._fields = {}); - const userProvidedFields = - this._userProvidedFields || (this._userProvidedFields = {}); - let sanitizeProjection = undefined; - if ( - this.model != null && - utils.hasUserDefinedProperty( - this.model.db.options, - "sanitizeProjection" - ) - ) { - sanitizeProjection = this.model.db.options.sanitizeProjection; - } else if ( - this.model != null && - utils.hasUserDefinedProperty( - this.model.base.options, - "sanitizeProjection" - ) - ) { - sanitizeProjection = this.model.base.options.sanitizeProjection; - } else { - sanitizeProjection = this._mongooseOptions.sanitizeProjection; - } +Object.defineProperty(VirtualOptions.prototype, 'skip', opts); - arg = parseProjection(arg); +/** + * If true, add a `limit` to the query used to `populate()`. + * + * @api public + * @property limit + * @memberOf VirtualOptions + * @type Number + * @instance + */ - if (utils.isObject(arg)) { - const keys = Object.keys(arg); - for (let i = 0; i < keys.length; ++i) { - let value = arg[keys[i]]; - if (typeof value === "string" && sanitizeProjection) { - value = 1; - } - fields[keys[i]] = value; - userProvidedFields[keys[i]] = value; - } - return this; - } +Object.defineProperty(VirtualOptions.prototype, 'limit', opts); - throw new TypeError( - "Invalid select() argument. Must be string or object." - ); - }; +/** + * The `limit` option for `populate()` has [some unfortunate edge cases](/docs/populate.html#query-conditions) + * when working with multiple documents, like `.find().populate()`. The + * `perDocumentLimit` option makes `populate()` execute a separate query + * for each document returned from `find()` to ensure each document + * gets up to `perDocumentLimit` populated docs if possible. + * + * @api public + * @property perDocumentLimit + * @memberOf VirtualOptions + * @type Number + * @instance + */ - /** - * _DEPRECATED_ Sets the slaveOk option. - * - * **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read). - * - * ####Example: - * - * query.slaveOk() // true - * query.slaveOk(true) - * query.slaveOk(false) - * - * @method slaveOk - * @memberOf Query - * @instance - * @deprecated use read() preferences instead if on mongodb >= 2.2 - * @param {Boolean} v defaults to true - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/ - * @see read() #query_Query-read - * @return {Query} this - * @api public - */ - - /** - * Determines the MongoDB nodes from which to read. - * - * ####Preferences: - * - * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. - * secondary Read from secondary if available, otherwise error. - * primaryPreferred Read from primary if available, otherwise a secondary. - * secondaryPreferred Read from a secondary if available, otherwise read from the primary. - * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. - * - * Aliases - * - * p primary - * pp primaryPreferred - * s secondary - * sp secondaryPreferred - * n nearest - * - * ####Example: - * - * new Query().read('primary') - * new Query().read('p') // same as primary - * - * new Query().read('primaryPreferred') - * new Query().read('pp') // same as primaryPreferred - * - * new Query().read('secondary') - * new Query().read('s') // same as secondary - * - * new Query().read('secondaryPreferred') - * new Query().read('sp') // same as secondaryPreferred - * - * new Query().read('nearest') - * new Query().read('n') // same as nearest - * - * // read from secondaries with matching tags - * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]) - * - * Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). - * - * @method read - * @memberOf Query - * @instance - * @param {String} pref one of the listed preference options or aliases - * @param {Array} [tags] optional tags for this query - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences - * @return {Query} this - * @api public - */ - - Query.prototype.read = function read(pref, tags) { - // first cast into a ReadPreference object to support tags - const read = new ReadPreference(pref, tags); - this.options.readPreference = read; - return this; - }; +Object.defineProperty(VirtualOptions.prototype, 'perDocumentLimit', opts); - /** - * Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/) - * associated with this query. Sessions are how you mark a query as part of a - * [transaction](/docs/transactions.html). - * - * Calling `session(null)` removes the session from this query. - * - * ####Example: - * - * const s = await mongoose.startSession(); - * await mongoose.model('Person').findOne({ name: 'Axl Rose' }).session(s); - * - * @method session - * @memberOf Query - * @instance - * @param {ClientSession} [session] from `await conn.startSession()` - * @see Connection.prototype.startSession() /docs/api.html#connection_Connection-startSession - * @see mongoose.startSession() /docs/api.html#mongoose_Mongoose-startSession - * @return {Query} this - * @api public - */ - - Query.prototype.session = function session(v) { - if (v == null) { - delete this.options.session; - } - this.options.session = v; - return this; - }; +module.exports = VirtualOptions; - /** - * Sets the 3 write concern parameters for this query: - * - * - `w`: Sets the specified number of `mongod` servers, or tag set of `mongod` servers, that must acknowledge this write before this write is considered successful. - * - `j`: Boolean, set to `true` to request acknowledgement that this operation has been persisted to MongoDB's on-disk journal. - * - `wtimeout`: If [`w > 1`](/docs/api.html#query_Query-w), the maximum amount of time to wait for this write to propagate through the replica set before this operation fails. The default is `0`, which means no timeout. - * - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndReplace()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the schema's [`writeConcern` option](/docs/guide.html#writeConcern) - * - * ####Example: - * - * // The 'majority' option means the `deleteOne()` promise won't resolve - * // until the `deleteOne()` has propagated to the majority of the replica set - * await mongoose.model('Person'). - * deleteOne({ name: 'Ned Stark' }). - * writeConcern({ w: 'majority' }); - * - * @method writeConcern - * @memberOf Query - * @instance - * @param {Object} writeConcern the write concern value to set - * @see mongodb https://mongodb.github.io/node-mongodb-native/3.1/api/global.html#WriteConcern - * @return {Query} this - * @api public - */ - - Query.prototype.writeConcern = function writeConcern(val) { - if (val == null) { - delete this.options.writeConcern; - return this; - } - this.options.writeConcern = val; - return this; - }; +/***/ }), - /** - * Sets the specified number of `mongod` servers, or tag set of `mongod` servers, - * that must acknowledge this write before this write is considered successful. - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndReplace()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the schema's [`writeConcern.w` option](/docs/guide.html#writeConcern) - * - * ####Example: - * - * // The 'majority' option means the `deleteOne()` promise won't resolve - * // until the `deleteOne()` has propagated to the majority of the replica set - * await mongoose.model('Person'). - * deleteOne({ name: 'Ned Stark' }). - * w('majority'); - * - * @method w - * @memberOf Query - * @instance - * @param {String|number} val 0 for fire-and-forget, 1 for acknowledged by one server, 'majority' for majority of the replica set, or [any of the more advanced options](https://docs.mongodb.com/manual/reference/write-concern/#w-option). - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#w-option - * @return {Query} this - * @api public - */ - - Query.prototype.w = function w(val) { - if (val == null) { - delete this.options.w; - } - if (this.options.writeConcern != null) { - this.options.writeConcern.w = val; - } else { - this.options.w = val; - } - return this; - }; +/***/ 1090: +/***/ ((module) => { - /** - * Requests acknowledgement that this operation has been persisted to MongoDB's - * on-disk journal. - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndReplace()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the schema's [`writeConcern.j` option](/docs/guide.html#writeConcern) - * - * ####Example: - * - * await mongoose.model('Person').deleteOne({ name: 'Ned Stark' }).j(true); - * - * @method j - * @memberOf Query - * @instance - * @param {boolean} val - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#j-option - * @return {Query} this - * @api public - */ - - Query.prototype.j = function j(val) { - if (val == null) { - delete this.options.j; - } - if (this.options.writeConcern != null) { - this.options.writeConcern.j = val; - } else { - this.options.j = val; - } - return this; - }; +"use strict"; - /** - * If [`w > 1`](/docs/api.html#query_Query-w), the maximum amount of time to - * wait for this write to propagate through the replica set before this - * operation fails. The default is `0`, which means no timeout. - * - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndReplace()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the schema's [`writeConcern.wtimeout` option](/docs/guide.html#writeConcern) - * - * ####Example: - * - * // The `deleteOne()` promise won't resolve until this `deleteOne()` has - * // propagated to at least `w = 2` members of the replica set. If it takes - * // longer than 1 second, this `deleteOne()` will fail. - * await mongoose.model('Person'). - * deleteOne({ name: 'Ned Stark' }). - * w(2). - * wtimeout(1000); - * - * @method wtimeout - * @memberOf Query - * @instance - * @param {number} ms number of milliseconds to wait - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#wtimeout - * @return {Query} this - * @api public - */ - - Query.prototype.wtimeout = function wtimeout(ms) { - if (ms == null) { - delete this.options.wtimeout; - } - if (this.options.writeConcern != null) { - this.options.writeConcern.wtimeout = ms; - } else { - this.options.wtimeout = ms; - } - return this; - }; - /** - * Sets the readConcern option for the query. - * - * ####Example: - * - * new Query().readConcern('local') - * new Query().readConcern('l') // same as local - * - * new Query().readConcern('available') - * new Query().readConcern('a') // same as available - * - * new Query().readConcern('majority') - * new Query().readConcern('m') // same as majority - * - * new Query().readConcern('linearizable') - * new Query().readConcern('lz') // same as linearizable - * - * new Query().readConcern('snapshot') - * new Query().readConcern('s') // same as snapshot - * - * - * ####Read Concern Level: - * - * local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). - * available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). - * majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. - * linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. - * snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. - * - * Aliases - * - * l local - * a available - * m majority - * lz linearizable - * s snapshot - * - * Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/). - * - * @memberOf Query - * @method readConcern - * @param {String} level one of the listed read concern level or their aliases - * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/ - * @return {Query} this - * @api public - */ - - /** - * Gets query options. - * - * ####Example: - * - * const query = new Query(); - * query.limit(10); - * query.setOptions({ maxTimeMS: 1000 }) - * query.getOptions(); // { limit: 10, maxTimeMS: 1000 } - * - * @return {Object} the options - * @api public - */ - - Query.prototype.getOptions = function () { - return this.options; - }; +module.exports = Object.freeze({ + enumerable: true, + configurable: true, + writable: true, + value: void 0 +}); - /** - * Sets query options. Some options only make sense for certain operations. - * - * ####Options: - * - * The following options are only for `find()`: - * - * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) - * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) - * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) - * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) - * - [allowDiskUse](https://docs.mongodb.com/manual/reference/method/cursor.allowDiskUse/) - * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) - * - [readPreference](http://docs.mongodb.org/manual/applications/replication/#read-preference) - * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) - * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) - * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) - * - [maxscan](https://docs.mongodb.org/v3.2/reference/operator/meta/maxScan/#metaOp._S_maxScan) - * - * The following options are only for write operations: `update()`, `updateOne()`, `updateMany()`, `replaceOne()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`: - * - * - [upsert](https://docs.mongodb.com/manual/reference/method/db.collection.update/) - * - [writeConcern](https://docs.mongodb.com/manual/reference/method/db.collection.update/) - * - [timestamps](https://mongoosejs.com/docs/guide.html#timestamps): If `timestamps` is set in the schema, set this option to `false` to skip timestamps for that particular update. Has no effect if `timestamps` is not enabled in the schema options. - * - omitUndefined: delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * - overwriteDiscriminatorKey: allow setting the discriminator key in the update. Will use the correct discriminator schema if the update changes the discriminator key. - * - overwrite: replace the entire document - * - * The following options are only for `find()`, `findOne()`, `findById()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`: - * - * - [lean](./api.html#query_Query-lean) - * - [populate](/docs/populate.html) - * - [projection](/docs/api/query.html#query_Query-projection) - * - sanitizeProjection - * - * The following options are only for all operations **except** `update()`, `updateOne()`, `updateMany()`, `remove()`, `deleteOne()`, and `deleteMany()`: - * - * - [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) - * - * The following options are for `findOneAndUpdate()` and `findOneAndRemove()` - * - * - [useFindAndModify](/docs/deprecations.html#findandmodify) - * - rawResult - * - * The following options are for all operations: - * - * - [collation](https://docs.mongodb.com/manual/reference/collation/) - * - [session](https://docs.mongodb.com/manual/reference/server-sessions/) - * - [explain](https://docs.mongodb.com/manual/reference/method/cursor.explain/) - * - * @param {Object} options - * @return {Query} this - * @api public - */ - - Query.prototype.setOptions = function (options, overwrite) { - // overwrite is only for internal use - if (overwrite) { - // ensure that _mongooseOptions & options are two different objects - this._mongooseOptions = (options && utils.clone(options)) || {}; - this.options = options || {}; - - if ("populate" in options) { - this.populate(this._mongooseOptions); - } - return this; - } - if (options == null) { - return this; - } - if (typeof options !== "object") { - throw new Error('Options must be an object, got "' + options + '"'); - } +/***/ }), - if (Array.isArray(options.populate)) { - const populate = options.populate; - delete options.populate; - const _numPopulate = populate.length; - for (let i = 0; i < _numPopulate; ++i) { - this.populate(populate[i]); - } - } +/***/ 2258: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ("useFindAndModify" in options) { - this._mongooseOptions.useFindAndModify = options.useFindAndModify; - delete options.useFindAndModify; - } - if ("omitUndefined" in options) { - this._mongooseOptions.omitUndefined = options.omitUndefined; - delete options.omitUndefined; - } - if ("setDefaultsOnInsert" in options) { - this._mongooseOptions.setDefaultsOnInsert = - options.setDefaultsOnInsert; - delete options.setDefaultsOnInsert; - } - if ("overwriteDiscriminatorKey" in options) { - this._mongooseOptions.overwriteDiscriminatorKey = - options.overwriteDiscriminatorKey; - delete options.overwriteDiscriminatorKey; - } - if ("sanitizeProjection" in options) { - if ( - options.sanitizeProjection && - !this._mongooseOptions.sanitizeProjection - ) { - sanitizeProjection(this._fields); - } +"use strict"; - this._mongooseOptions.sanitizeProjection = options.sanitizeProjection; - delete options.sanitizeProjection; - } - if ("defaults" in options) { - this._mongooseOptions.defaults = options.defaults; - // deleting options.defaults will cause 7287 to fail - } +const clone = __nccwpck_require__(5092); - return Query.base.setOptions.call(this, options); - }; +class RemoveOptions { + constructor(obj) { + if (obj == null) { + return; + } + Object.assign(this, clone(obj)); + } +} - /** - * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/), - * which makes this query return detailed execution stats instead of the actual - * query result. This method is useful for determining what index your queries - * use. - * - * Calling `query.explain(v)` is equivalent to `query.setOptions({ explain: v })` - * - * ####Example: - * - * const query = new Query(); - * const res = await query.find({ a: 1 }).explain('queryPlanner'); - * console.log(res); - * - * @param {String} [verbose] The verbosity mode. Either 'queryPlanner', 'executionStats', or 'allPlansExecution'. The default is 'queryPlanner' - * @return {Query} this - * @api public - */ - - Query.prototype.explain = function (verbose) { - if (arguments.length === 0) { - this.options.explain = true; - } else if (verbose === false) { - delete this.options.explain; - } else { - this.options.explain = verbose; - } - return this; - }; +module.exports = RemoveOptions; - /** - * Sets the [`allowDiskUse` option](https://docs.mongodb.com/manual/reference/method/cursor.allowDiskUse/), - * which allows the MongoDB server to use more than 100 MB for this query's `sort()`. This option can - * let you work around `QueryExceededMemoryLimitNoDiskUseAllowed` errors from the MongoDB server. - * - * Note that this option requires MongoDB server >= 4.4. Setting this option is a no-op for MongoDB 4.2 - * and earlier. - * - * Calling `query.allowDiskUse(v)` is equivalent to `query.setOptions({ allowDiskUse: v })` - * - * ####Example: - * - * await query.find().sort({ name: 1 }).allowDiskUse(true); - * // Equivalent: - * await query.find().sort({ name: 1 }).allowDiskUse(); - * - * @param {Boolean} [v] Enable/disable `allowDiskUse`. If called with 0 arguments, sets `allowDiskUse: true` - * @return {Query} this - * @api public - */ - - Query.prototype.allowDiskUse = function (v) { - if (arguments.length === 0) { - this.options.allowDiskUse = true; - } else if (v === false) { - delete this.options.allowDiskUse; - } else { - this.options.allowDiskUse = v; - } - return this; - }; +/***/ }), - /** - * Sets the [maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/) - * option. This will tell the MongoDB server to abort if the query or write op - * has been running for more than `ms` milliseconds. - * - * Calling `query.maxTimeMS(v)` is equivalent to `query.setOptions({ maxTimeMS: v })` - * - * ####Example: - * - * const query = new Query(); - * // Throws an error 'operation exceeded time limit' as long as there's - * // >= 1 doc in the queried collection - * const res = await query.find({ $where: 'sleep(1000) || true' }).maxTimeMS(100); - * - * @param {Number} [ms] The number of milliseconds - * @return {Query} this - * @api public - */ - - Query.prototype.maxTimeMS = function (ms) { - this.options.maxTimeMS = ms; - return this; - }; +/***/ 8792: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Returns the current query filter (also known as conditions) as a [POJO](https://masteringjs.io/tutorials/fundamentals/pojo). - * - * ####Example: - * - * const query = new Query(); - * query.find({ a: 1 }).where('b').gt(2); - * query.getFilter(); // { a: 1, b: { $gt: 2 } } - * - * @return {Object} current query filter - * @api public - */ - - Query.prototype.getFilter = function () { - return this._conditions; - }; +"use strict"; - /** - * Returns the current query filter. Equivalent to `getFilter()`. - * - * You should use `getFilter()` instead of `getQuery()` where possible. `getQuery()` - * will likely be deprecated in a future release. - * - * ####Example: - * - * const query = new Query(); - * query.find({ a: 1 }).where('b').gt(2); - * query.getQuery(); // { a: 1, b: { $gt: 2 } } - * - * @return {Object} current query filter - * @api public - */ - - Query.prototype.getQuery = function () { - return this._conditions; - }; - /** - * Sets the query conditions to the provided JSON object. - * - * ####Example: - * - * const query = new Query(); - * query.find({ a: 1 }) - * query.setQuery({ a: 2 }); - * query.getQuery(); // { a: 2 } - * - * @param {Object} new query conditions - * @return {undefined} - * @api public - */ - - Query.prototype.setQuery = function (val) { - this._conditions = val; - }; +const clone = __nccwpck_require__(5092); - /** - * Returns the current update operations as a JSON object. - * - * ####Example: - * - * const query = new Query(); - * query.update({}, { $set: { a: 5 } }); - * query.getUpdate(); // { $set: { a: 5 } } - * - * @return {Object} current update operations - * @api public - */ - - Query.prototype.getUpdate = function () { - return this._update; - }; +class SaveOptions { + constructor(obj) { + if (obj == null) { + return; + } + Object.assign(this, clone(obj)); + } +} - /** - * Sets the current update operation to new value. - * - * ####Example: - * - * const query = new Query(); - * query.update({}, { $set: { a: 5 } }); - * query.setUpdate({ $set: { b: 6 } }); - * query.getUpdate(); // { $set: { b: 6 } } - * - * @param {Object} new update operation - * @return {undefined} - * @api public - */ - - Query.prototype.setUpdate = function (val) { - this._update = val; - }; +module.exports = SaveOptions; - /** - * Returns fields selection for this query. - * - * @method _fieldsForExec - * @return {Object} - * @api private - * @receiver Query - */ - - Query.prototype._fieldsForExec = function () { - return utils.clone(this._fields); - }; +/***/ }), - /** - * Return an update document with corrected `$set` operations. - * - * @method _updateForExec - * @api private - * @receiver Query - */ - - Query.prototype._updateForExec = function () { - const update = utils.clone(this._update, { - transform: false, - depopulate: true, - }); - const ops = Object.keys(update); - let i = ops.length; - const ret = {}; +/***/ 7560: +/***/ ((module) => { - while (i--) { - const op = ops[i]; +"use strict"; - if (this.options.overwrite) { - ret[op] = update[op]; - continue; - } - if ("$" !== op[0]) { - // fix up $set sugar - if (!ret.$set) { - if (update.$set) { - ret.$set = update.$set; - } else { - ret.$set = {}; - } - } - ret.$set[op] = update[op]; - ops.splice(i, 1); - if (!~ops.indexOf("$set")) ops.push("$set"); - } else if ("$set" === op) { - if (!ret.$set) { - ret[op] = update[op]; - } - } else { - ret[op] = update[op]; - } - } +/*! + * ignore + */ - return ret; - }; +module.exports = function(schema) { + // `this.$__.validating` tracks whether there are multiple validations running + // in parallel. We need to clear `this.$__.validating` before post hooks for gh-8597 + const unshift = true; + schema.s.hooks.post('validate', false, function() { + if (this.$isSubdocument) { + return; + } - /** - * Makes sure _path is set. - * - * @method _ensurePath - * @param {String} method - * @api private - * @receiver Query - */ + this.$__.validating = null; + }, unshift); - /** - * Determines if `conds` can be merged using `mquery().merge()` - * - * @method canMerge - * @memberOf Query - * @instance - * @param {Object} conds - * @return {Boolean} - * @api private - */ + schema.s.hooks.post('validate', false, function(error, res, next) { + if (this.$isSubdocument) { + next(); + return; + } - /** - * Returns default options for this query. - * - * @param {Model} model - * @api private - */ + this.$__.validating = null; + next(); + }, unshift); +}; - Query.prototype._optionsForExec = function (model) { - const options = utils.clone(this.options); - delete options.populate; - model = model || this.model; - if (!model) { - return options; - } +/***/ }), - const safe = get(model, "schema.options.safe", null); - if (!("safe" in options) && safe != null) { - setSafe(options, safe); - } +/***/ 1058: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Apply schema-level `writeConcern` option - applyWriteConcern(model.schema, options); +"use strict"; - const readPreference = get(model, "schema.options.read"); - if (!("readPreference" in options) && readPreference) { - options.readPreference = readPreference; - } - if (options.upsert !== void 0) { - options.upsert = !!options.upsert; - } - if (options.writeConcern) { - if (options.j) { - options.writeConcern.j = options.j; - delete options.j; - } - if (options.w) { - options.writeConcern.w = options.w; - delete options.w; - } - if (options.wtimeout) { - options.writeConcern.wtimeout = options.wtimeout; - delete options.wtimeout; - } - } - return options; - }; +const each = __nccwpck_require__(9965); - /*! - * ignore - */ - - const safeDeprecationWarning = - "Mongoose: the `safe` option is deprecated. " + - "Use write concerns instead: http://bit.ly/mongoose-w"; - - const setSafe = util.deprecate(function setSafe(options, safe) { - options.safe = safe; - }, safeDeprecationWarning); - - /** - * Sets the lean option. - * - * Documents returned from queries with the `lean` option enabled are plain - * javascript objects, not [Mongoose Documents](/api/document.html). They have no - * `save` method, getters/setters, virtuals, or other Mongoose features. - * - * ####Example: - * - * new Query().lean() // true - * new Query().lean(true) - * new Query().lean(false) - * - * const docs = await Model.find().lean(); - * docs[0] instanceof mongoose.Document; // false - * - * [Lean is great for high-performance, read-only cases](/docs/tutorials/lean.html), - * especially when combined - * with [cursors](/docs/queries.html#streaming). - * - * If you need virtuals, getters/setters, or defaults with `lean()`, you need - * to use a plugin. See: - * - * - [mongoose-lean-virtuals](https://plugins.mongoosejs.io/plugins/lean-virtuals) - * - [mongoose-lean-getters](https://plugins.mongoosejs.io/plugins/lean-getters) - * - [mongoose-lean-defaults](https://www.npmjs.com/package/mongoose-lean-defaults) - * - * @param {Boolean|Object} bool defaults to true - * @return {Query} this - * @api public - */ - - Query.prototype.lean = function (v) { - this._mongooseOptions.lean = arguments.length ? v : true; - return this; - }; +/*! + * ignore + */ - /** - * Adds a `$set` to this query's update without changing the operation. - * This is useful for query middleware so you can add an update regardless - * of whether you use `updateOne()`, `updateMany()`, `findOneAndUpdate()`, etc. - * - * ####Example: - * - * // Updates `{ $set: { updatedAt: new Date() } }` - * new Query().updateOne({}, {}).set('updatedAt', new Date()); - * new Query().updateMany({}, {}).set({ updatedAt: new Date() }); - * - * @param {String|Object} path path or object of key/value pairs to set - * @param {Any} [val] the value to set - * @return {Query} this - * @api public - */ - - Query.prototype.set = function (path, val) { - if (typeof path === "object") { - const keys = Object.keys(path); - for (const key of keys) { - this.set(key, path[key]); - } - return this; - } +module.exports = function(schema) { + const unshift = true; + schema.s.hooks.pre('remove', false, function(next) { + if (this.$isSubdocument) { + next(); + return; + } - this._update = this._update || {}; - this._update.$set = this._update.$set || {}; - this._update.$set[path] = val; - return this; - }; + const _this = this; + const subdocs = this.$getAllSubdocs(); - /** - * For update operations, returns the value of a path in the update's `$set`. - * Useful for writing getters/setters that can work with both update operations - * and `save()`. - * - * ####Example: - * - * const query = Model.updateOne({}, { $set: { name: 'Jean-Luc Picard' } }); - * query.get('name'); // 'Jean-Luc Picard' - * - * @param {String|Object} path path or object of key/value pairs to get - * @return {Query} this - * @api public - */ + each(subdocs, function(subdoc, cb) { + subdoc.$__remove(cb); + }, function(error) { + if (error) { + return _this.$__schema.s.hooks.execPost('remove:error', _this, [_this], { error: error }, function(error) { + next(error); + }); + } + next(); + }); + }, null, unshift); +}; - Query.prototype.get = function get(path) { - const update = this._update; - if (update == null) { - return void 0; - } - const $set = update.$set; - if ($set == null) { - return update[path]; - } - if (utils.hasUserDefinedProperty(update, path)) { - return update[path]; - } - if (utils.hasUserDefinedProperty($set, path)) { - return $set[path]; - } +/***/ }), - return void 0; - }; +/***/ 7277: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Gets/sets the error flag on this query. If this flag is not null or - * undefined, the `exec()` promise will reject without executing. - * - * ####Example: - * - * Query().error(); // Get current error value - * Query().error(null); // Unset the current error - * Query().error(new Error('test')); // `exec()` will resolve with test - * Schema.pre('find', function() { - * if (!this.getQuery().userId) { - * this.error(new Error('Not allowed to query without setting userId')); - * } - * }); - * - * Note that query casting runs **after** hooks, so cast errors will override - * custom errors. - * - * ####Example: - * const TestSchema = new Schema({ num: Number }); - * const TestModel = db.model('Test', TestSchema); - * TestModel.find({ num: 'not a number' }).error(new Error('woops')).exec(function(error) { - * // `error` will be a cast error because `num` failed to cast - * }); - * - * @param {Error|null} err if set, `exec()` will fail fast before sending the query to MongoDB - * @return {Query} this - * @api public - */ - - Query.prototype.error = function error(err) { - if (arguments.length === 0) { - return this._error; - } - - this._error = err; - return this; - }; +"use strict"; - /*! - * ignore - */ - Query.prototype._unsetCastError = function _unsetCastError() { - if (this._error != null && !(this._error instanceof CastError)) { - return; - } - return this.error(null); - }; +const each = __nccwpck_require__(9965); - /** - * Getter/setter around the current mongoose-specific options for this query - * Below are the current Mongoose-specific options. - * - * - `populate`: an array representing what paths will be populated. Should have one entry for each call to [`Query.prototype.populate()`](/docs/api.html#query_Query-populate) - * - `lean`: if truthy, Mongoose will not [hydrate](/docs/api.html#model_Model.hydrate) any documents that are returned from this query. See [`Query.prototype.lean()`](/docs/api.html#query_Query-lean) for more information. - * - `strict`: controls how Mongoose handles keys that aren't in the schema for updates. This option is `true` by default, which means Mongoose will silently strip any paths in the update that aren't in the schema. See the [`strict` mode docs](/docs/guide.html#strict) for more information. - * - `strictQuery`: controls how Mongoose handles keys that aren't in the schema for the query `filter`. This option is `false` by default for backwards compatibility, which means Mongoose will allow `Model.find({ foo: 'bar' })` even if `foo` is not in the schema. See the [`strictQuery` docs](/docs/guide.html#strictQuery) for more information. - * - `useFindAndModify`: used to work around the [`findAndModify()` deprecation warning](/docs/deprecations.html#findandmodify) - * - `omitUndefined`: delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * - `nearSphere`: use `$nearSphere` instead of `near()`. See the [`Query.prototype.nearSphere()` docs](/docs/api.html#query_Query-nearSphere) - * - * Mongoose maintains a separate object for internal options because - * Mongoose sends `Query.prototype.options` to the MongoDB server, and the - * above options are not relevant for the MongoDB server. - * - * @param {Object} options if specified, overwrites the current options - * @return {Object} the options - * @api public - */ - - Query.prototype.mongooseOptions = function (v) { - if (arguments.length > 0) { - this._mongooseOptions = v; - } - return this._mongooseOptions; - }; +/*! + * ignore + */ - /*! - * ignore - */ +module.exports = function(schema) { + const unshift = true; + schema.s.hooks.pre('save', false, function(next) { + if (this.$isSubdocument) { + next(); + return; + } - Query.prototype._castConditions = function () { - try { - this.cast(this.model); - this._unsetCastError(); - } catch (err) { - this.error(err); - } - }; + const _this = this; + const subdocs = this.$getAllSubdocs(); - /*! - * ignore - */ + if (!subdocs.length) { + next(); + return; + } - function _castArrayFilters(query) { - try { - castArrayFilters(query); - } catch (err) { - query.error(err); - } + each(subdocs, function(subdoc, cb) { + subdoc.$__schema.s.hooks.execPre('save', subdoc, function(err) { + cb(err); + }); + }, function(error) { + if (error) { + return _this.$__schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) { + next(error); + }); } + next(); + }); + }, null, unshift); - /** - * Thunk around find() - * - * @param {Function} [callback] - * @return {Query} this - * @api private - */ - Query.prototype._find = wrapThunk(function (callback) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return null; - } + schema.s.hooks.post('save', function(doc, next) { + if (this.$isSubdocument) { + next(); + return; + } - callback = _wrapThunkCallback(this, callback); + const _this = this; + const subdocs = this.$getAllSubdocs(); - this._applyPaths(); - this._fields = this._castFields(this._fields); + if (!subdocs.length) { + next(); + return; + } - const fields = this._fieldsForExec(); - const mongooseOptions = this._mongooseOptions; - const _this = this; - const userProvidedFields = _this._userProvidedFields || {}; + each(subdocs, function(subdoc, cb) { + subdoc.$__schema.s.hooks.execPost('save', subdoc, [subdoc], function(err) { + cb(err); + }); + }, function(error) { + if (error) { + return _this.$__schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) { + next(error); + }); + } + next(); + }); + }, null, unshift); +}; - applyGlobalMaxTimeMS(this.options, this.model); - // Separate options to pass down to `completeMany()` in case we need to - // set a session on the document - const completeManyOptions = Object.assign( - {}, - { - session: get(this, "options.session", null), - } - ); +/***/ }), - const cb = (err, docs) => { - if (err) { - return callback(err); - } +/***/ 94: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (docs.length === 0) { - return callback(null, docs); - } - if (this.options.explain) { - return callback(null, docs); - } +"use strict"; - if (!mongooseOptions.populate) { - return mongooseOptions.lean - ? callback(null, docs) - : completeMany( - _this.model, - docs, - fields, - userProvidedFields, - completeManyOptions, - callback - ); - } - const pop = helpers.preparePopulationOptionsMQ( - _this, - mongooseOptions - ); - completeManyOptions.populated = pop; - _this.model.populate(docs, pop, function (err, docs) { - if (err) return callback(err); - return mongooseOptions.lean - ? callback(null, docs) - : completeMany( - _this.model, - docs, - fields, - userProvidedFields, - completeManyOptions, - callback - ); - }); - }; +const objectIdSymbol = __nccwpck_require__(3240).objectIdSymbol; +const utils = __nccwpck_require__(9232); - const options = this._optionsForExec(); - options.projection = this._fieldsForExec(); - const filter = this._conditions; +/*! + * ignore + */ - this._collection.find(filter, options, cb); - return null; - }); +module.exports = function shardingPlugin(schema) { + schema.post('init', function() { + storeShard.call(this); + return this; + }); + schema.pre('save', function(next) { + applyWhere.call(this); + next(); + }); + schema.pre('remove', function(next) { + applyWhere.call(this); + next(); + }); + schema.post('save', function() { + storeShard.call(this); + }); +}; + +/*! + * ignore + */ - /** - * Find all documents that match `selector`. The result will be an array of documents. - * - * If there are too many documents in the result to fit in memory, use - * [`Query.prototype.cursor()`](api.html#query_Query-cursor) - * - * ####Example - * - * // Using async/await - * const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } }); - * - * // Using callbacks - * Movie.find({ year: { $gte: 1980, $lte: 1989 } }, function(err, arr) {}); - * - * @param {Object|ObjectId} [filter] mongodb selector. If not specified, returns all documents. - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - - Query.prototype.find = function (conditions, callback) { - this.op = "find"; - - if (typeof conditions === "function") { - callback = conditions; - conditions = {}; - } - - conditions = utils.toObject(conditions); - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - - prepareDiscriminatorCriteria(this); - } else if (conditions != null) { - this.error(new ObjectParameterError(conditions, "filter", "find")); - } - - // if we don't have a callback, then just return the query object - if (!callback) { - return Query.base.find.call(this); - } +function applyWhere() { + let paths; + let len; - this.exec(callback); + if (this.$__.shardval) { + paths = Object.keys(this.$__.shardval); + len = paths.length; - return this; - }; + this.$where = this.$where || {}; + for (let i = 0; i < len; ++i) { + this.$where[paths[i]] = this.$__.shardval[paths[i]]; + } + } +} - /** - * Merges another Query or conditions object into this one. - * - * When a Query is passed, conditions, field selection and options are merged. - * - * @param {Query|Object} source - * @return {Query} this - */ - - Query.prototype.merge = function (source) { - if (!source) { - return this; - } +/*! + * ignore + */ - const opts = { overwrite: true }; +module.exports.storeShard = storeShard; - if (source instanceof Query) { - // if source has a feature, apply it to ourselves +/*! + * ignore + */ - if (source._conditions) { - utils.merge(this._conditions, source._conditions, opts); - } +function storeShard() { + // backwards compat + const key = this.$__schema.options.shardKey || this.$__schema.options.shardkey; + if (!utils.isPOJO(key)) { + return; + } - if (source._fields) { - this._fields || (this._fields = {}); - utils.merge(this._fields, source._fields, opts); - } + const orig = this.$__.shardval = {}; + const paths = Object.keys(key); + const len = paths.length; + let val; + + for (let i = 0; i < len; ++i) { + val = this.$__getValue(paths[i]); + if (val == null) { + orig[paths[i]] = val; + } else if (utils.isMongooseObject(val)) { + orig[paths[i]] = val.toObject({ depopulate: true, _isNested: true }); + } else if (val instanceof Date || val[objectIdSymbol]) { + orig[paths[i]] = val; + } else if (typeof val.valueOf === 'function') { + orig[paths[i]] = val.valueOf(); + } else { + orig[paths[i]] = val; + } + } +} - if (source.options) { - this.options || (this.options = {}); - utils.merge(this.options, source.options, opts); - } - if (source._update) { - this._update || (this._update = {}); - utils.mergeClone(this._update, source._update); - } +/***/ }), - if (source._distinct) { - this._distinct = source._distinct; - } +/***/ 8675: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - utils.merge(this._mongooseOptions, source._mongooseOptions); +"use strict"; - return this; - } - // plain object - utils.merge(this._conditions, source, opts); +const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; +const sessionNewDocuments = __nccwpck_require__(3240).sessionNewDocuments; - return this; - }; +module.exports = function trackTransaction(schema) { + schema.pre('save', function() { + const session = this.$session(); + if (session == null) { + return; + } + if (session.transaction == null || session[sessionNewDocuments] == null) { + return; + } - /** - * Adds a collation to this op (MongoDB 3.4 and up) - * - * @param {Object} value - * @return {Query} this - * @see MongoDB docs https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation - * @api public - */ + if (!session[sessionNewDocuments].has(this)) { + const initialState = {}; + if (this.isNew) { + initialState.isNew = true; + } + if (this.$__schema.options.versionKey) { + initialState.versionKey = this.get(this.$__schema.options.versionKey); + } - Query.prototype.collation = function (value) { - if (this.options == null) { - this.options = {}; - } - this.options.collation = value; - return this; - }; + initialState.modifiedPaths = new Set(Object.keys(this.$__.activePaths.states.modify)); + initialState.atomics = _getAtomics(this); - /** - * Hydrate a single doc from `findOne()`, `findOneAndUpdate()`, etc. - * - * @api private - */ + session[sessionNewDocuments].set(this, initialState); + } else { + const state = session[sessionNewDocuments].get(this); - Query.prototype._completeOne = function (doc, res, callback) { - if (!doc && !this.options.rawResult) { - return callback(null, null); - } + for (const path of Object.keys(this.$__.activePaths.states.modify)) { + state.modifiedPaths.add(path); + } + state.atomics = _getAtomics(this, state.atomics); + } + }); +}; + +function _getAtomics(doc, previous) { + const pathToAtomics = new Map(); + previous = previous || new Map(); + + const pathsToCheck = Object.keys(doc.$__.activePaths.init).concat(Object.keys(doc.$__.activePaths.modify)); + + for (const path of pathsToCheck) { + const val = doc.$__getValue(path); + if (val != null && + val instanceof Array && + val.isMongooseDocumentArray && + val.length && + val[arrayAtomicsSymbol] != null && + Object.keys(val[arrayAtomicsSymbol]).length > 0) { + const existing = previous.get(path) || {}; + pathToAtomics.set(path, mergeAtomics(existing, val[arrayAtomicsSymbol])); + } + } - const model = this.model; - const projection = utils.clone(this._fields); - const userProvidedFields = this._userProvidedFields || {}; - // `populate`, `lean` - const mongooseOptions = this._mongooseOptions; - // `rawResult` - const options = this.options; + const dirty = doc.$__dirty(); + for (const dirt of dirty) { + const path = dirt.path; - if (options.explain) { - return callback(null, doc); - } - - if (!mongooseOptions.populate) { - return mongooseOptions.lean - ? _completeOneLean(doc, res, options, callback) - : completeOne( - model, - doc, - res, - options, - projection, - userProvidedFields, - null, - callback - ); - } + const val = dirt.value; + if (val != null && val[arrayAtomicsSymbol] != null && Object.keys(val[arrayAtomicsSymbol]).length > 0) { + const existing = previous.get(path) || {}; + pathToAtomics.set(path, mergeAtomics(existing, val[arrayAtomicsSymbol])); + } + } - const pop = helpers.preparePopulationOptionsMQ( - this, - this._mongooseOptions - ); - model.populate(doc, pop, (err, doc) => { - if (err) { - return callback(err); - } - return mongooseOptions.lean - ? _completeOneLean(doc, res, options, callback) - : completeOne( - model, - doc, - res, - options, - projection, - userProvidedFields, - pop, - callback - ); - }); - }; + return pathToAtomics; +} - /** - * Thunk around findOne() - * - * @param {Function} [callback] - * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ - * @api private - */ +function mergeAtomics(destination, source) { + destination = destination || {}; - Query.prototype._findOne = wrapThunk(function (callback) { - this._castConditions(); + if (source.$pullAll != null) { + destination.$pullAll = (destination.$pullAll || []).concat(source.$pullAll); + } + if (source.$push != null) { + destination.$push = destination.$push || {}; + destination.$push.$each = (destination.$push.$each || []).concat(source.$push.$each); + } + if (source.$addToSet != null) { + destination.$addToSet = (destination.$addToSet || []).concat(source.$addToSet); + } + if (source.$set != null) { + destination.$set = Object.assign(destination.$set || {}, source.$set); + } - if (this.error()) { - callback(this.error()); - return null; - } + return destination; +} - this._applyPaths(); - this._fields = this._castFields(this._fields); +/***/ }), - applyGlobalMaxTimeMS(this.options, this.model); +/***/ 1752: +/***/ ((module) => { - // don't pass in the conditions because we already merged them in - Query.base.findOne.call(this, {}, (err, doc) => { - if (err) { - callback(err); - return null; - } +"use strict"; - this._completeOne(doc, null, _wrapThunkCallback(this, callback)); - }); - }); - /** - * Declares the query a findOne operation. When executed, the first found document is passed to the callback. - * - * Passing a `callback` executes the query. The result of the query is a single document. - * - * * *Note:* `conditions` is optional, and if `conditions` is null or undefined, - * mongoose will send an empty `findOne` command to MongoDB, which will return - * an arbitrary document. If you're querying by `_id`, use `Model.findById()` - * instead. - * - * This function triggers the following middleware. - * - * - `findOne()` - * - * ####Example - * - * const query = Kitten.where({ color: 'white' }); - * query.findOne(function (err, kitten) { - * if (err) return handleError(err); - * if (kitten) { - * // doc may be null if no document matched - * } - * }); - * - * @param {Object} [filter] mongodb selector - * @param {Object} [projection] optional fields to return - * @param {Object} [options] see [`setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] optional params are (error, document) - * @return {Query} this - * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ - * @see Query.select #query_Query-select - * @api public - */ - - Query.prototype.findOne = function ( - conditions, - projection, - options, - callback - ) { - this.op = "findOne"; - if (typeof conditions === "function") { - callback = conditions; - conditions = null; - projection = null; - options = null; - } else if (typeof projection === "function") { - callback = projection; - options = null; - projection = null; - } else if (typeof options === "function") { - callback = options; - options = null; - } - - // make sure we don't send in the whole Document to merge() - conditions = utils.toObject(conditions); - - if (options) { - this.setOptions(options); - } - - if (projection) { - this.select(projection); - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - - prepareDiscriminatorCriteria(this); - } else if (conditions != null) { - this.error(new ObjectParameterError(conditions, "filter", "findOne")); - } +/*! + * ignore + */ - if (!callback) { - // already merged in the conditions, don't need to send them in. - return Query.base.findOne.call(this); - } +module.exports = function(schema) { + const unshift = true; + schema.pre('save', false, function validateBeforeSave(next, options) { + const _this = this; + // Nested docs have their own presave + if (this.$isSubdocument) { + return next(); + } - this.exec(callback); - return this; - }; + const hasValidateBeforeSaveOption = options && + (typeof options === 'object') && + ('validateBeforeSave' in options); - /** - * Thunk around count() - * - * @param {Function} [callback] - * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ - * @api private - */ + let shouldValidate; + if (hasValidateBeforeSaveOption) { + shouldValidate = !!options.validateBeforeSave; + } else { + shouldValidate = this.$__schema.options.validateBeforeSave; + } - Query.prototype._count = wrapThunk(function (callback) { - try { - this.cast(this.model); - } catch (err) { - this.error(err); - } + // Validate + if (shouldValidate) { + const hasValidateModifiedOnlyOption = options && + (typeof options === 'object') && + ('validateModifiedOnly' in options); + const validateOptions = hasValidateModifiedOnlyOption ? + { validateModifiedOnly: options.validateModifiedOnly } : + null; + this.$validate(validateOptions, function(error) { + return _this.$__schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) { + _this.$op = 'save'; + next(error); + }); + }); + } else { + next(); + } + }, null, unshift); +}; - if (this.error()) { - return callback(this.error()); - } - applyGlobalMaxTimeMS(this.options, this.model); +/***/ }), - const conds = this._conditions; - const options = this._optionsForExec(); +/***/ 5176: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this._collection.count(conds, options, utils.tick(callback)); - }); +"use strict"; +/*! + * ignore + */ - /** - * Thunk around countDocuments() - * - * @param {Function} [callback] - * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments - * @api private - */ - Query.prototype._countDocuments = wrapThunk(function (callback) { - try { - this.cast(this.model); - } catch (err) { - this.error(err); - } - if (this.error()) { - return callback(this.error()); - } +const assert = __nccwpck_require__(2357); +const mquery = __nccwpck_require__(3821); - applyGlobalMaxTimeMS(this.options, this.model); +/** + * Helper for multiplexing promise implementations + * + * @api private + */ - const conds = this._conditions; - const options = this._optionsForExec(); +const store = { + _promise: null +}; - this._collection.collection.countDocuments( - conds, - options, - utils.tick(callback) - ); - }); +/** + * Get the current promise constructor + * + * @api private + */ - /** - * Thunk around estimatedDocumentCount() - * - * @param {Function} [callback] - * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount - * @api private - */ +store.get = function() { + return store._promise; +}; - Query.prototype._estimatedDocumentCount = wrapThunk(function (callback) { - if (this.error()) { - return callback(this.error()); - } +/** + * Set the current promise constructor + * + * @api private + */ - const options = this._optionsForExec(); +store.set = function(lib) { + assert.ok(typeof lib === 'function', + `mongoose.Promise must be a function, got ${lib}`); + store._promise = lib; + mquery.Promise = lib; +}; - this._collection.collection.estimatedDocumentCount( - options, - utils.tick(callback) - ); - }); +/*! + * Use native promises by default + */ - /** - * Specifies this query as a `count` query. - * - * This method is deprecated. If you want to count the number of documents in - * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#query_Query-estimatedDocumentCount) - * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#query_Query-countDocuments) function instead. - * - * Passing a `callback` executes the query. - * - * This function triggers the following middleware. - * - * - `count()` - * - * ####Example: - * - * const countQuery = model.where({ 'color': 'black' }).count(); - * - * query.count({ color: 'black' }).count(callback) - * - * query.count({ color: 'black' }, callback) - * - * query.where('color', 'black').count(function (err, count) { - * if (err) return handleError(err); - * console.log('there are %d kittens', count); - * }) - * - * @deprecated - * @param {Object} [filter] count documents that match this object - * @param {Function} [callback] optional params are (error, count) - * @return {Query} this - * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ - * @api public - */ - - Query.prototype.count = function (filter, callback) { - this.op = "count"; - if (typeof filter === "function") { - callback = filter; - filter = undefined; - } - - filter = utils.toObject(filter); - - if (mquery.canMerge(filter)) { - this.merge(filter); - } +store.set(global.Promise); - if (!callback) { - return this; - } +module.exports = store; - this.exec(callback); - return this; - }; +/***/ }), - /** - * Specifies this query as a `estimatedDocumentCount()` query. Faster than - * using `countDocuments()` for large collections because - * `estimatedDocumentCount()` uses collection metadata rather than scanning - * the entire collection. - * - * `estimatedDocumentCount()` does **not** accept a filter. `Model.find({ foo: bar }).estimatedDocumentCount()` - * is equivalent to `Model.find().estimatedDocumentCount()` - * - * This function triggers the following middleware. - * - * - `estimatedDocumentCount()` - * - * ####Example: - * - * await Model.find().estimatedDocumentCount(); - * - * @param {Object} [options] passed transparently to the [MongoDB driver](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount) - * @param {Function} [callback] optional params are (error, count) - * @return {Query} this - * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount - * @api public - */ - - Query.prototype.estimatedDocumentCount = function (options, callback) { - this.op = "estimatedDocumentCount"; - if (typeof options === "function") { - callback = options; - options = undefined; - } - - if (typeof options === "object" && options != null) { - this.setOptions(options); - } +/***/ 1615: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!callback) { - return this; - } +"use strict"; - this.exec(callback); - return this; - }; +/*! + * Module dependencies. + */ - /** - * Specifies this query as a `countDocuments()` query. Behaves like `count()`, - * except it always does a full collection scan when passed an empty filter `{}`. - * - * There are also minor differences in how `countDocuments()` handles - * [`$where` and a couple geospatial operators](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). - * versus `count()`. - * - * Passing a `callback` executes the query. - * - * This function triggers the following middleware. - * - * - `countDocuments()` - * - * ####Example: - * - * const countQuery = model.where({ 'color': 'black' }).countDocuments(); - * - * query.countDocuments({ color: 'black' }).count(callback); - * - * query.countDocuments({ color: 'black' }, callback); - * - * query.where('color', 'black').countDocuments(function(err, count) { - * if (err) return handleError(err); - * console.log('there are %d kittens', count); - * }); - * - * The `countDocuments()` function is similar to `count()`, but there are a - * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). - * Below are the operators that `count()` supports but `countDocuments()` does not, - * and the suggested replacement: - * - * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/) - * - `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center) - * - `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere) - * - * @param {Object} [filter] mongodb selector - * @param {Function} [callback] optional params are (error, count) - * @return {Query} this - * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments - * @api public - */ - - Query.prototype.countDocuments = function (conditions, callback) { - this.op = "countDocuments"; - if (typeof conditions === "function") { - callback = conditions; - conditions = undefined; - } - - conditions = utils.toObject(conditions); - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - } +const CastError = __nccwpck_require__(2798); +const DocumentNotFoundError = __nccwpck_require__(5147); +const Kareem = __nccwpck_require__(716); +const MongooseError = __nccwpck_require__(5953); +const ObjectParameterError = __nccwpck_require__(3456); +const QueryCursor = __nccwpck_require__(3588); +const ReadPreference = __nccwpck_require__(2324).get().ReadPreference; +const applyGlobalMaxTimeMS = __nccwpck_require__(7428); +const applyWriteConcern = __nccwpck_require__(5661); +const cast = __nccwpck_require__(9179); +const castArrayFilters = __nccwpck_require__(4856); +const castUpdate = __nccwpck_require__(3303); +const completeMany = __nccwpck_require__(2941); +const get = __nccwpck_require__(8730); +const promiseOrCallback = __nccwpck_require__(4046); +const getDiscriminatorByValue = __nccwpck_require__(8689); +const hasDollarKeys = __nccwpck_require__(8309); +const helpers = __nccwpck_require__(5299); +const immediate = __nccwpck_require__(4830); +const isExclusive = __nccwpck_require__(3522); +const isInclusive = __nccwpck_require__(2951); +const isSubpath = __nccwpck_require__(8578); +const mquery = __nccwpck_require__(3821); +const parseProjection = __nccwpck_require__(7201); +const removeUnusedArrayFilters = __nccwpck_require__(8909); +const sanitizeFilter = __nccwpck_require__(3824); +const sanitizeProjection = __nccwpck_require__(8276); +const selectPopulatedFields = __nccwpck_require__(1907); +const setDefaultsOnInsert = __nccwpck_require__(5937); +const slice = __nccwpck_require__(9889); +const updateValidators = __nccwpck_require__(9009); +const util = __nccwpck_require__(1669); +const utils = __nccwpck_require__(9232); +const validOps = __nccwpck_require__(2786); +const wrapThunk = __nccwpck_require__(2006); + +/** + * Query constructor used for building queries. You do not need + * to instantiate a `Query` directly. Instead use Model functions like + * [`Model.find()`](/docs/api.html#find_find). + * + * ####Example: + * + * const query = MyModel.find(); // `query` is an instance of `Query` + * query.setOptions({ lean : true }); + * query.collection(MyModel.collection); + * query.where('age').gte(21).exec(callback); + * + * // You can instantiate a query directly. There is no need to do + * // this unless you're an advanced user with a very good reason to. + * const query = new mongoose.Query(); + * + * @param {Object} [options] + * @param {Object} [model] + * @param {Object} [conditions] + * @param {Object} [collection] Mongoose collection + * @api public + */ - if (!callback) { - return this; - } +function Query(conditions, options, model, collection) { + // this stuff is for dealing with custom queries created by #toConstructor + if (!this._mongooseOptions) { + this._mongooseOptions = {}; + } + options = options || {}; - this.exec(callback); + this._transforms = []; + this._hooks = new Kareem(); + this._executionStack = null; - return this; - }; + // this is the case where we have a CustomQuery, we need to check if we got + // options passed in, and if we did, merge them in + const keys = Object.keys(options); + for (const key of keys) { + this._mongooseOptions[key] = options[key]; + } - /** - * Thunk around distinct() - * - * @param {Function} [callback] - * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ - * @api private - */ + if (collection) { + this.mongooseCollection = collection; + } - Query.prototype.__distinct = wrapThunk(function __distinct(callback) { - this._castConditions(); + if (model) { + this.model = model; + this.schema = model.schema; + } - if (this.error()) { - callback(this.error()); - return null; - } - applyGlobalMaxTimeMS(this.options, this.model); + // this is needed because map reduce returns a model that can be queried, but + // all of the queries on said model should be lean + if (this.model && this.model._mapreduce) { + this.lean(); + } - const options = this._optionsForExec(); + // inherit mquery + mquery.call(this, this.mongooseCollection, options); - // don't pass in the conditions because we already merged them in - this._collection.collection.distinct( - this._distinct, - this._conditions, - options, - callback - ); - }); + if (conditions) { + this.find(conditions); + } - /** - * Declares or executes a distinct() operation. - * - * Passing a `callback` executes the query. - * - * This function does not trigger any middleware. - * - * ####Example - * - * distinct(field, conditions, callback) - * distinct(field, conditions) - * distinct(field, callback) - * distinct(field) - * distinct(callback) - * distinct() - * - * @param {String} [field] - * @param {Object|Query} [filter] - * @param {Function} [callback] optional params are (error, arr) - * @return {Query} this - * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ - * @api public - */ - - Query.prototype.distinct = function (field, conditions, callback) { - this.op = "distinct"; - if (!callback) { - if (typeof conditions === "function") { - callback = conditions; - conditions = undefined; - } else if (typeof field === "function") { - callback = field; - field = undefined; - conditions = undefined; - } - } + this.options = this.options || {}; - conditions = utils.toObject(conditions); + // For gh-6880. mquery still needs to support `fields` by default for old + // versions of MongoDB + this.$useProjection = true; - if (mquery.canMerge(conditions)) { - this.merge(conditions); + const collation = get(this, 'schema.options.collation', null); + if (collation != null) { + this.options.collation = collation; + } +} - prepareDiscriminatorCriteria(this); - } else if (conditions != null) { - this.error( - new ObjectParameterError(conditions, "filter", "distinct") - ); - } +/*! + * inherit mquery + */ - if (field != null) { - this._distinct = field; - } +Query.prototype = new mquery; +Query.prototype.constructor = Query; +Query.base = mquery.prototype; - if (callback != null) { - this.exec(callback); - } +/** + * Flag to opt out of using `$geoWithin`. + * + * mongoose.Query.use$geoWithin = false; + * + * MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with `$within`). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work. + * + * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/ + * @default true + * @property use$geoWithin + * @memberOf Query + * @receiver Query + * @api public + */ - return this; - }; +Query.use$geoWithin = mquery.use$geoWithin; - /** - * Sets the sort order - * - * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. - * - * If a string is passed, it must be a space delimited list of path names. The - * sort order of each path is ascending unless the path name is prefixed with `-` - * which will be treated as descending. - * - * ####Example - * - * // sort by "field" ascending and "test" descending - * query.sort({ field: 'asc', test: -1 }); - * - * // equivalent - * query.sort('field -test'); - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object|String} arg - * @return {Query} this - * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/ - * @api public - */ - - Query.prototype.sort = function (arg) { - if (arguments.length > 1) { - throw new Error("sort() only takes 1 Argument"); - } - - return Query.base.sort.call(this, arg); - }; +/** + * Converts this query to a customized, reusable query constructor with all arguments and options retained. + * + * ####Example + * + * // Create a query for adventure movies and read from the primary + * // node in the replica-set unless it is down, in which case we'll + * // read from a secondary node. + * const query = Movie.find({ tags: 'adventure' }).read('primaryPreferred'); + * + * // create a custom Query constructor based off these settings + * const Adventure = query.toConstructor(); + * + * // Adventure is now a subclass of mongoose.Query and works the same way but with the + * // default query parameters and options set. + * Adventure().exec(callback) + * + * // further narrow down our query results while still using the previous settings + * Adventure().where({ name: /^Life/ }).exec(callback); + * + * // since Adventure is a stand-alone constructor we can also add our own + * // helper methods and getters without impacting global queries + * Adventure.prototype.startsWith = function (prefix) { + * this.where({ name: new RegExp('^' + prefix) }) + * return this; + * } + * Object.defineProperty(Adventure.prototype, 'highlyRated', { + * get: function () { + * this.where({ rating: { $gt: 4.5 }}); + * return this; + * } + * }) + * Adventure().highlyRated.startsWith('Life').exec(callback) + * + * @return {Query} subclass-of-Query + * @api public + */ - /** - * Declare and/or execute this query as a remove() operation. `remove()` is - * deprecated, you should use [`deleteOne()`](#query_Query-deleteOne) - * or [`deleteMany()`](#query_Query-deleteMany) instead. - * - * This function does not trigger any middleware - * - * ####Example - * - * Character.remove({ name: /Stark/ }, callback); - * - * This function calls the MongoDB driver's [`Collection#remove()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove). - * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an - * object that contains 3 properties: - * - * - `ok`: `1` if no errors occurred - * - `deletedCount`: the number of documents deleted - * - `n`: the number of documents deleted. Equal to `deletedCount`. - * - * ####Example - * - * const res = await Character.remove({ name: /Stark/ }); - * // Number of docs deleted - * res.deletedCount; - * - * ####Note - * - * Calling `remove()` creates a [Mongoose query](./queries.html), and a query - * does not execute until you either pass a callback, call [`Query#then()`](#query_Query-then), - * or call [`Query#exec()`](#query_Query-exec). - * - * // not executed - * const query = Character.remove({ name: /Stark/ }); - * - * // executed - * Character.remove({ name: /Stark/ }, callback); - * Character.remove({ name: /Stark/ }).remove(callback); - * - * // executed without a callback - * Character.exec(); - * - * @param {Object|Query} [filter] mongodb selector - * @param {Function} [callback] optional params are (error, mongooseDeleteResult) - * @return {Query} this - * @deprecated - * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult - * @see MongoDB driver remove http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove - * @api public - */ - - Query.prototype.remove = function (filter, callback) { - this.op = "remove"; - if (typeof filter === "function") { - callback = filter; - filter = null; - } - - filter = utils.toObject(filter); - - if (mquery.canMerge(filter)) { - this.merge(filter); - - prepareDiscriminatorCriteria(this); - } else if (filter != null) { - this.error(new ObjectParameterError(filter, "filter", "remove")); - } +Query.prototype.toConstructor = function toConstructor() { + const model = this.model; + const coll = this.mongooseCollection; - if (!callback) { - return Query.base.remove.call(this); - } + const CustomQuery = function(criteria, options) { + if (!(this instanceof CustomQuery)) { + return new CustomQuery(criteria, options); + } + this._mongooseOptions = utils.clone(p._mongooseOptions); + Query.call(this, criteria, options || null, model, coll); + }; - this.exec(callback); - return this; - }; + util.inherits(CustomQuery, model.Query); - /*! - * ignore - */ + // set inherited defaults + const p = CustomQuery.prototype; - Query.prototype._remove = wrapThunk(function (callback) { - this._castConditions(); + p.options = {}; - if (this.error() != null) { - callback(this.error()); - return this; - } + // Need to handle `sort()` separately because entries-style `sort()` syntax + // `sort([['prop1', 1]])` confuses mquery into losing the outer nested array. + // See gh-8159 + const options = Object.assign({}, this.options); + if (options.sort != null) { + p.sort(options.sort); + delete options.sort; + } + p.setOptions(options); + + p.op = this.op; + p._validateOp(); + p._conditions = utils.clone(this._conditions); + p._fields = utils.clone(this._fields); + p._update = utils.clone(this._update, { + flattenDecimals: false + }); + p._path = this._path; + p._distinct = this._distinct; + p._collection = this._collection; + p._mongooseOptions = this._mongooseOptions; + + return CustomQuery; +}; + +/** + * Make a copy of this query so you can re-execute it. + * + * ####Example: + * const q = Book.findOne({ title: 'Casino Royale' }); + * await q.exec(); + * await q.exec(); // Throws an error because you can't execute a query twice + * + * await q.clone().exec(); // Works + * + * @method clone + * @return {Query} copy + * @memberOf Query + * @instance + * @api public + */ - callback = _wrapThunkCallback(this, callback); +Query.prototype.clone = function clone() { + const model = this.model; + const collection = this.mongooseCollection; - return Query.base.remove.call( - this, - helpers.handleDeleteWriteOpResult(callback) - ); - }); + const q = new this.constructor({}, {}, model, collection); - /** - * Declare and/or execute this query as a `deleteOne()` operation. Works like - * remove, except it deletes at most one document regardless of the `single` - * option. - * - * This function triggers `deleteOne` middleware. - * - * ####Example - * - * await Character.deleteOne({ name: 'Eddard Stark' }); - * - * // Using callbacks: - * Character.deleteOne({ name: 'Eddard Stark' }, callback); - * - * This function calls the MongoDB driver's [`Collection#deleteOne()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne). - * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an - * object that contains 3 properties: - * - * - `ok`: `1` if no errors occurred - * - `deletedCount`: the number of documents deleted - * - `n`: the number of documents deleted. Equal to `deletedCount`. - * - * ####Example - * - * const res = await Character.deleteOne({ name: 'Eddard Stark' }); - * // `1` if MongoDB deleted a doc, `0` if no docs matched the filter `{ name: ... }` - * res.deletedCount; - * - * @param {Object|Query} [filter] mongodb selector - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] optional params are (error, mongooseDeleteResult) - * @return {Query} this - * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult - * @see MongoDB Driver deleteOne http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne - * @api public - */ - - Query.prototype.deleteOne = function (filter, options, callback) { - this.op = "deleteOne"; - if (typeof filter === "function") { - callback = filter; - filter = null; - options = null; - } else if (typeof options === "function") { - callback = options; - options = null; - } else { - this.setOptions(options); - } + // Need to handle `sort()` separately because entries-style `sort()` syntax + // `sort([['prop1', 1]])` confuses mquery into losing the outer nested array. + // See gh-8159 + const options = Object.assign({}, this.options); + if (options.sort != null) { + q.sort(options.sort); + delete options.sort; + } + q.setOptions(options); + + q.op = this.op; + q._validateOp(); + q._conditions = utils.clone(this._conditions); + q._fields = utils.clone(this._fields); + q._update = utils.clone(this._update, { + flattenDecimals: false + }); + q._path = this._path; + q._distinct = this._distinct; + q._collection = this._collection; + q._mongooseOptions = this._mongooseOptions; + + return q; +}; + +/** + * Specifies a javascript function or expression to pass to MongoDBs query system. + * + * ####Example + * + * query.$where('this.comments.length === 10 || this.name.length === 5') + * + * // or + * + * query.$where(function () { + * return this.comments.length === 10 || this.name.length === 5; + * }) + * + * ####NOTE: + * + * Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. + * **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.** + * + * @see $where http://docs.mongodb.org/manual/reference/operator/where/ + * @method $where + * @param {String|Function} js javascript string or function + * @return {Query} this + * @memberOf Query + * @instance + * @method $where + * @api public + */ - filter = utils.toObject(filter); +/** + * Specifies a `path` for use with chaining. + * + * ####Example + * + * // instead of writing: + * User.find({age: {$gte: 21, $lte: 65}}, callback); + * + * // we can instead write: + * User.where('age').gte(21).lte(65); + * + * // passing query conditions is permitted + * User.find().where({ name: 'vonderful' }) + * + * // chaining + * User + * .where('age').gte(21).lte(65) + * .where('name', /^vonderful/i) + * .where('friends').slice(10) + * .exec(callback) + * + * @method where + * @memberOf Query + * @instance + * @param {String|Object} [path] + * @param {any} [val] + * @return {Query} this + * @api public + */ - if (mquery.canMerge(filter)) { - this.merge(filter); +/** + * Specifies a `$slice` projection for an array. + * + * ####Example + * + * query.slice('comments', 5) + * query.slice('comments', -5) + * query.slice('comments', [10, 5]) + * query.where('comments').slice(5) + * query.where('comments').slice([-10, 5]) + * + * @method slice + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Number} val number/range of elements to slice + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements + * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice + * @api public + */ - prepareDiscriminatorCriteria(this); - } else if (filter != null) { - this.error(new ObjectParameterError(filter, "filter", "deleteOne")); - } +Query.prototype.slice = function() { + if (arguments.length === 0) { + return this; + } - if (!callback) { - return Query.base.deleteOne.call(this); - } + this._validate('slice'); - this.exec.call(this, callback); + let path; + let val; - return this; - }; + if (arguments.length === 1) { + const arg = arguments[0]; + if (typeof arg === 'object' && !Array.isArray(arg)) { + const keys = Object.keys(arg); + const numKeys = keys.length; + for (let i = 0; i < numKeys; ++i) { + this.slice(keys[i], arg[keys[i]]); + } + return this; + } + this._ensurePath('slice'); + path = this._path; + val = arguments[0]; + } else if (arguments.length === 2) { + if ('number' === typeof arguments[0]) { + this._ensurePath('slice'); + path = this._path; + val = slice(arguments); + } else { + path = arguments[0]; + val = arguments[1]; + } + } else if (arguments.length === 3) { + path = arguments[0]; + val = slice(arguments, 1); + } - /*! - * Internal thunk for `deleteOne()` - */ + const p = {}; + p[path] = { $slice: val }; + this.select(p); - Query.prototype._deleteOne = wrapThunk(function (callback) { - this._castConditions(); + return this; +}; - if (this.error() != null) { - callback(this.error()); - return this; - } +/*! + * ignore + */ - callback = _wrapThunkCallback(this, callback); +const validOpsSet = new Set(validOps); - return Query.base.deleteOne.call( - this, - helpers.handleDeleteWriteOpResult(callback) - ); - }); +Query.prototype._validateOp = function() { + if (this.op != null && !validOpsSet.has(this.op)) { + this.error(new Error('Query has invalid `op`: "' + this.op + '"')); + } +}; - /** - * Declare and/or execute this query as a `deleteMany()` operation. Works like - * remove, except it deletes _every_ document that matches `filter` in the - * collection, regardless of the value of `single`. - * - * This function triggers `deleteMany` middleware. - * - * ####Example - * - * await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }); - * - * // Using callbacks: - * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, callback); - * - * This function calls the MongoDB driver's [`Collection#deleteMany()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany). - * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an - * object that contains 3 properties: - * - * - `ok`: `1` if no errors occurred - * - `deletedCount`: the number of documents deleted - * - `n`: the number of documents deleted. Equal to `deletedCount`. - * - * ####Example - * - * const res = await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }); - * // `0` if no docs matched the filter, number of docs deleted otherwise - * res.deletedCount; - * - * @param {Object|Query} [filter] mongodb selector - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] optional params are (error, mongooseDeleteResult) - * @return {Query} this - * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult - * @see MongoDB Driver deleteMany http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany - * @api public - */ - - Query.prototype.deleteMany = function (filter, options, callback) { - this.op = "deleteMany"; - if (typeof filter === "function") { - callback = filter; - filter = null; - options = null; - } else if (typeof options === "function") { - callback = options; - options = null; - } else { - this.setOptions(options); - } +/** + * Specifies the complementary comparison value for paths specified with `where()` + * + * ####Example + * + * User.where('age').equals(49); + * + * // is the same as + * + * User.where('age', 49); + * + * @method equals + * @memberOf Query + * @instance + * @param {Object} val + * @return {Query} this + * @api public + */ - filter = utils.toObject(filter); +/** + * Specifies arguments for an `$or` condition. + * + * ####Example + * + * query.or([{ color: 'red' }, { status: 'emergency' }]) + * + * @see $or http://docs.mongodb.org/manual/reference/operator/or/ + * @method or + * @memberOf Query + * @instance + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ - if (mquery.canMerge(filter)) { - this.merge(filter); +/** + * Specifies arguments for a `$nor` condition. + * + * ####Example + * + * query.nor([{ color: 'green' }, { status: 'ok' }]) + * + * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/ + * @method nor + * @memberOf Query + * @instance + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ - prepareDiscriminatorCriteria(this); - } else if (filter != null) { - this.error(new ObjectParameterError(filter, "filter", "deleteMany")); - } +/** + * Specifies arguments for a `$and` condition. + * + * ####Example + * + * query.and([{ color: 'green' }, { status: 'ok' }]) + * + * @method and + * @memberOf Query + * @instance + * @see $and http://docs.mongodb.org/manual/reference/operator/and/ + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ - if (!callback) { - return Query.base.deleteMany.call(this); - } +/** + * Specifies a `$gt` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * ####Example + * + * Thing.find().where('age').gt(21) + * + * // or + * Thing.find().gt('age', 21) + * + * @method gt + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Number} val + * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/ + * @api public + */ - this.exec.call(this, callback); +/** + * Specifies a `$gte` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method gte + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Number} val + * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/ + * @api public + */ - return this; - }; +/** + * Specifies a `$lt` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lt + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Number} val + * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/ + * @api public + */ - /*! - * Internal thunk around `deleteMany()` - */ +/** + * Specifies a `$lte` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lte + * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/ + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Number} val + * @api public + */ - Query.prototype._deleteMany = wrapThunk(function (callback) { - this._castConditions(); +/** + * Specifies a `$ne` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/ + * @method ne + * @memberOf Query + * @instance + * @param {String} [path] + * @param {any} val + * @api public + */ - if (this.error() != null) { - callback(this.error()); - return this; - } +/** + * Specifies an `$in` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $in http://docs.mongodb.org/manual/reference/operator/in/ + * @method in + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Array} val + * @api public + */ - callback = _wrapThunkCallback(this, callback); +/** + * Specifies an `$nin` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/ + * @method nin + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Array} val + * @api public + */ - return Query.base.deleteMany.call( - this, - helpers.handleDeleteWriteOpResult(callback) - ); - }); +/** + * Specifies an `$all` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * ####Example: + * + * MyModel.find().where('pets').all(['dog', 'cat', 'ferret']); + * // Equivalent: + * MyModel.find().all('pets', ['dog', 'cat', 'ferret']); + * + * @see $all http://docs.mongodb.org/manual/reference/operator/all/ + * @method all + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Array} val + * @api public + */ - /*! - * hydrates a document - * - * @param {Model} model - * @param {Document} doc - * @param {Object} res 3rd parameter to callback - * @param {Object} fields - * @param {Query} self - * @param {Array} [pop] array of paths used in population - * @param {Function} callback - */ - - function completeOne( - model, - doc, - res, - options, - fields, - userProvidedFields, - pop, - callback - ) { - const opts = pop ? { populated: pop } : undefined; - - if (options.rawResult && doc == null) { - _init(null); - return null; - } - - const casted = helpers.createModel( - model, - doc, - fields, - userProvidedFields, - options - ); - try { - casted.init(doc, opts, _init); - } catch (error) { - _init(error); - } +/** + * Specifies a `$size` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * ####Example + * + * const docs = await MyModel.where('tags').size(0).exec(); + * assert(Array.isArray(docs)); + * console.log('documents with 0 tags', docs); + * + * @see $size http://docs.mongodb.org/manual/reference/operator/size/ + * @method size + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Number} val + * @api public + */ - function _init(err) { - if (err) { - return immediate(() => callback(err)); - } +/** + * Specifies a `$regex` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/ + * @method regex + * @memberOf Query + * @instance + * @param {String} [path] + * @param {String|RegExp} val + * @api public + */ - if (options.rawResult) { - if (doc && casted) { - if (options.session != null) { - casted.$session(options.session); - } - res.value = casted; - } else { - res.value = null; - } - return immediate(() => callback(null, res)); - } - if (options.session != null) { - casted.$session(options.session); - } - immediate(() => callback(null, casted)); - } - } +/** + * Specifies a `maxDistance` query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ + * @method maxDistance + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Number} val + * @api public + */ - /*! - * If the model is a discriminator type and not root, then add the key & value to the criteria. - */ +/** + * Specifies a `$mod` condition, filters documents for documents whose + * `path` property is a number that is equal to `remainder` modulo `divisor`. + * + * ####Example + * + * // All find products whose inventory is odd + * Product.find().mod('inventory', [2, 1]); + * Product.find().where('inventory').mod([2, 1]); + * // This syntax is a little strange, but supported. + * Product.find().where('inventory').mod(2, 1); + * + * @method mod + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Array} val must be of length 2, first element is `divisor`, 2nd element is `remainder`. + * @return {Query} this + * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/ + * @api public + */ - function prepareDiscriminatorCriteria(query) { - if (!query || !query.model || !query.model.schema) { - return; - } +Query.prototype.mod = function() { + let val; + let path; + + if (arguments.length === 1) { + this._ensurePath('mod'); + val = arguments[0]; + path = this._path; + } else if (arguments.length === 2 && !Array.isArray(arguments[1])) { + this._ensurePath('mod'); + val = slice(arguments); + path = this._path; + } else if (arguments.length === 3) { + val = slice(arguments, 1); + path = arguments[0]; + } else { + val = arguments[1]; + path = arguments[0]; + } - const schema = query.model.schema; + const conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$mod = val; + return this; +}; - if ( - schema && - schema.discriminatorMapping && - !schema.discriminatorMapping.isRoot - ) { - query._conditions[schema.discriminatorMapping.key] = - schema.discriminatorMapping.value; - } - } - - /** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found - * document (if any) to the callback. The query executes if - * `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndUpdate()` - * - * ####Available options - * - * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()` - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false. - * - * ####Callback Signature - * function(error, doc) { - * // error: any errors that occurred - * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` - * } - * - * ####Examples - * - * query.findOneAndUpdate(conditions, update, options, callback) // executes - * query.findOneAndUpdate(conditions, update, options) // returns Query - * query.findOneAndUpdate(conditions, update, callback) // executes - * query.findOneAndUpdate(conditions, update) // returns Query - * query.findOneAndUpdate(update, callback) // returns Query - * query.findOneAndUpdate(update) // returns Query - * query.findOneAndUpdate(callback) // executes - * query.findOneAndUpdate() // returns Query - * - * @method findOneAndUpdate - * @memberOf Query - * @instance - * @param {Object|Query} [filter] - * @param {Object} [doc] - * @param {Object} [options] - * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. - * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. - * @param {Function} [callback] optional params are (error, doc), _unless_ `rawResult` is used, in which case params are (error, writeOpResult) - * @see Tutorial /docs/tutorials/findoneandupdate.html - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @return {Query} this - * @api public - */ - - Query.prototype.findOneAndUpdate = function ( - criteria, - doc, - options, - callback - ) { - this.op = "findOneAndUpdate"; - this._validate(); - - switch (arguments.length) { - case 3: - if (typeof options === "function") { - callback = options; - options = {}; - } - break; - case 2: - if (typeof doc === "function") { - callback = doc; - doc = criteria; - criteria = undefined; - } - options = undefined; - break; - case 1: - if (typeof criteria === "function") { - callback = criteria; - criteria = options = doc = undefined; - } else { - doc = criteria; - criteria = options = undefined; - } - } +/** + * Specifies an `$exists` condition + * + * ####Example + * + * // { name: { $exists: true }} + * Thing.where('name').exists() + * Thing.where('name').exists(true) + * Thing.find().exists('name') + * + * // { name: { $exists: false }} + * Thing.where('name').exists(false); + * Thing.find().exists('name', false); + * + * @method exists + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Boolean} val + * @return {Query} this + * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/ + * @api public + */ - if (mquery.canMerge(criteria)) { - this.merge(criteria); - } +/** + * Specifies an `$elemMatch` condition + * + * ####Example + * + * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) + * + * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) + * + * query.elemMatch('comment', function (elem) { + * elem.where('author').equals('autobot'); + * elem.where('votes').gte(5); + * }) + * + * query.where('comment').elemMatch(function (elem) { + * elem.where({ author: 'autobot' }); + * elem.where('votes').gte(5); + * }) + * + * @method elemMatch + * @memberOf Query + * @instance + * @param {String|Object|Function} path + * @param {Object|Function} filter + * @return {Query} this + * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/ + * @api public + */ - // apply doc - if (doc) { - this._mergeUpdate(doc); - } +/** + * Defines a `$within` or `$geoWithin` argument for geo-spatial queries. + * + * ####Example + * + * query.where(path).within().box() + * query.where(path).within().circle() + * query.where(path).within().geometry() + * + * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); + * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); + * query.where('loc').within({ polygon: [[],[],[],[]] }); + * + * query.where('loc').within([], [], []) // polygon + * query.where('loc').within([], []) // box + * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry + * + * **MUST** be used after `where()`. + * + * ####NOTE: + * + * As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin). + * + * ####NOTE: + * + * In Mongoose 3.7, `within` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). + * + * @method within + * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ + * @see $box http://docs.mongodb.org/manual/reference/operator/box/ + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @see $center http://docs.mongodb.org/manual/reference/operator/center/ + * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ + * @memberOf Query + * @instance + * @return {Query} this + * @api public + */ - options = options ? utils.clone(options) : {}; +/** + * Specifies the maximum number of documents the query will return. + * + * ####Example + * + * query.limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method limit + * @memberOf Query + * @instance + * @param {Number} val + * @api public + */ - if (options.projection) { - this.select(options.projection); - delete options.projection; - } - if (options.fields) { - this.select(options.fields); - delete options.fields; - } +/** + * Specifies the number of documents to skip. + * + * ####Example + * + * query.skip(100).limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method skip + * @memberOf Query + * @instance + * @param {Number} val + * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/ + * @api public + */ - const returnOriginal = get(this, "model.base.options.returnOriginal"); - if ( - options.new == null && - options.returnDocument == null && - options.returnOriginal == null && - returnOriginal != null - ) { - options.returnOriginal = returnOriginal; - } +/** + * Specifies the maxScan option. + * + * ####Example + * + * query.maxScan(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method maxScan + * @memberOf Query + * @instance + * @param {Number} val + * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/ + * @api public + */ - this.setOptions(options); +/** + * Specifies the batchSize option. + * + * ####Example + * + * query.batchSize(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method batchSize + * @memberOf Query + * @instance + * @param {Number} val + * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/ + * @api public + */ - if (!callback) { - return this; - } +/** + * Specifies the `comment` option. + * + * ####Example + * + * query.comment('login query') + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method comment + * @memberOf Query + * @instance + * @param {String} val + * @see comment http://docs.mongodb.org/manual/reference/operator/comment/ + * @api public + */ - this.exec(callback); +/** + * Specifies this query as a `snapshot` query. + * + * ####Example + * + * query.snapshot() // true + * query.snapshot(true) + * query.snapshot(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method snapshot + * @memberOf Query + * @instance + * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/ + * @return {Query} this + * @api public + */ - return this; - }; +/** + * Sets query hints. + * + * ####Example + * + * query.hint({ indexA: 1, indexB: -1}) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method hint + * @memberOf Query + * @instance + * @param {Object} val a hint object + * @return {Query} this + * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/ + * @api public + */ - /*! - * Thunk around findOneAndUpdate() - * - * @param {Function} [callback] - * @api private - */ +/** + * Get/set the current projection (AKA fields). Pass `null` to remove the + * current projection. + * + * Unlike `projection()`, the `select()` function modifies the current + * projection in place. This function overwrites the existing projection. + * + * ####Example: + * + * const q = Model.find(); + * q.projection(); // null + * + * q.select('a b'); + * q.projection(); // { a: 1, b: 1 } + * + * q.projection({ c: 1 }); + * q.projection(); // { c: 1 } + * + * q.projection(null); + * q.projection(); // null + * + * + * @method projection + * @memberOf Query + * @instance + * @param {Object|null} arg + * @return {Object} the current projection + * @api public + */ - Query.prototype._findOneAndUpdate = wrapThunk(function (callback) { - if (this.error() != null) { - return callback(this.error()); - } +Query.prototype.projection = function(arg) { + if (arguments.length === 0) { + return this._fields; + } - this._findAndModify("update", callback); - }); + this._fields = {}; + this._userProvidedFields = {}; + this.select(arg); + return this._fields; +}; - /** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. - * - * Finds a matching document, removes it, passing the found document (if any) to - * the callback. Executes if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndRemove()` - * - * ####Available options - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - * ####Callback Signature - * function(error, doc) { - * // error: any errors that occurred - * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` - * } - * - * ####Examples - * - * A.where().findOneAndRemove(conditions, options, callback) // executes - * A.where().findOneAndRemove(conditions, options) // return Query - * A.where().findOneAndRemove(conditions, callback) // executes - * A.where().findOneAndRemove(conditions) // returns Query - * A.where().findOneAndRemove(callback) // executes - * A.where().findOneAndRemove() // returns Query - * - * @method findOneAndRemove - * @memberOf Query - * @instance - * @param {Object} [conditions] - * @param {Object} [options] - * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Function} [callback] optional params are (error, document) - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - - Query.prototype.findOneAndRemove = function ( - conditions, - options, - callback - ) { - this.op = "findOneAndRemove"; - this._validate(); - - switch (arguments.length) { - case 2: - if (typeof options === "function") { - callback = options; - options = {}; - } - break; - case 1: - if (typeof conditions === "function") { - callback = conditions; - conditions = undefined; - options = undefined; - } - break; - } +/** + * Specifies which document fields to include or exclude (also known as the query "projection") + * + * When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](/docs/api.html#schematype_SchemaType-select). + * + * A projection _must_ be either inclusive or exclusive. In other words, you must + * either list the fields to include (which excludes all others), or list the fields + * to exclude (which implies all other fields are included). The [`_id` field is the only exception because MongoDB includes it by default](https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#suppress-id-field). + * + * ####Example + * + * // include a and b, exclude other fields + * query.select('a b'); + * // Equivalent syntaxes: + * query.select(['a', 'b']); + * query.select({ a: 1, b: 1 }); + * + * // exclude c and d, include other fields + * query.select('-c -d'); + * + * // Use `+` to override schema-level `select: false` without making the + * // projection inclusive. + * const schema = new Schema({ + * foo: { type: String, select: false }, + * bar: String + * }); + * // ... + * query.select('+foo'); // Override foo's `select: false` without excluding `bar` + * + * // or you may use object notation, useful when + * // you have keys already prefixed with a "-" + * query.select({ a: 1, b: 1 }); + * query.select({ c: 0, d: 0 }); + * + * Additional calls to select can override the previous selection: + * query.select({ a: 1, b: 1 }).select({ b: 0 }); // selection is now { a: 1 } + * query.select({ a: 0, b: 0 }).select({ b: 1 }); // selection is now { a: 0 } + * + * + * @method select + * @memberOf Query + * @instance + * @param {Object|String|Array} arg + * @return {Query} this + * @see SchemaType + * @api public + */ - if (mquery.canMerge(conditions)) { - this.merge(conditions); - } +Query.prototype.select = function select() { + let arg = arguments[0]; + if (!arg) return this; - options && this.setOptions(options); + if (arguments.length !== 1) { + throw new Error('Invalid select: select only takes 1 argument'); + } - if (!callback) { - return this; - } + this._validate('select'); + + const fields = this._fields || (this._fields = {}); + const userProvidedFields = this._userProvidedFields || (this._userProvidedFields = {}); + let sanitizeProjection = undefined; + if (this.model != null && utils.hasUserDefinedProperty(this.model.db.options, 'sanitizeProjection')) { + sanitizeProjection = this.model.db.options.sanitizeProjection; + } else if (this.model != null && utils.hasUserDefinedProperty(this.model.base.options, 'sanitizeProjection')) { + sanitizeProjection = this.model.base.options.sanitizeProjection; + } else { + sanitizeProjection = this._mongooseOptions.sanitizeProjection; + } - this.exec(callback); + function sanitizeValue(value) { + return typeof value === 'string' && sanitizeProjection ? value = 1 : value; + } - return this; - }; + arg = parseProjection(arg); - /** - * Issues a MongoDB [findOneAndDelete](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndDelete/) command. - * - * Finds a matching document, removes it, and passes the found document (if any) - * to the callback. Executes if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndDelete()` - * - * This function differs slightly from `Model.findOneAndRemove()` in that - * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/), - * as opposed to a `findOneAndDelete()` command. For most mongoose use cases, - * this distinction is purely pedantic. You should use `findOneAndDelete()` - * unless you have a good reason not to. - * - * ####Available options - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - * ####Callback Signature - * function(error, doc) { - * // error: any errors that occurred - * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` - * } - * - * ####Examples - * - * A.where().findOneAndDelete(conditions, options, callback) // executes - * A.where().findOneAndDelete(conditions, options) // return Query - * A.where().findOneAndDelete(conditions, callback) // executes - * A.where().findOneAndDelete(conditions) // returns Query - * A.where().findOneAndDelete(callback) // executes - * A.where().findOneAndDelete() // returns Query - * - * @method findOneAndDelete - * @memberOf Query - * @param {Object} [conditions] - * @param {Object} [options] - * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Function} [callback] optional params are (error, document) - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - - Query.prototype.findOneAndDelete = function ( - conditions, - options, - callback - ) { - this.op = "findOneAndDelete"; - this._validate(); - - switch (arguments.length) { - case 2: - if (typeof options === "function") { - callback = options; - options = {}; - } - break; - case 1: - if (typeof conditions === "function") { - callback = conditions; - conditions = undefined; - options = undefined; + if (utils.isObject(arg)) { + if (this.selectedInclusively()) { + Object.entries(arg).forEach(([key, value]) => { + if (value) { + // Add the field to the projection + fields[key] = userProvidedFields[key] = sanitizeValue(value); + } else { + // Remove the field from the projection + Object.keys(userProvidedFields).forEach(field => { + if (isSubpath(key, field)) { + delete fields[field]; + delete userProvidedFields[field]; } - break; - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions); + }); } - - options && this.setOptions(options); - - if (!callback) { - return this; + }); + } else if (this.selectedExclusively()) { + Object.entries(arg).forEach(([key, value]) => { + if (!value) { + // Add the field to the projection + fields[key] = userProvidedFields[key] = sanitizeValue(value); + } else { + // Remove the field from the projection + Object.keys(userProvidedFields).forEach(field => { + if (isSubpath(key, field)) { + delete fields[field]; + delete userProvidedFields[field]; + } + }); } + }); + } else { + const keys = Object.keys(arg); + for (let i = 0; i < keys.length; ++i) { + const value = arg[keys[i]]; + fields[keys[i]] = sanitizeValue(value); + userProvidedFields[keys[i]] = sanitizeValue(value); + } + } + return this; + } - this.exec(callback); - - return this; - }; + throw new TypeError('Invalid select() argument. Must be string or object.'); +}; - /*! - * Thunk around findOneAndDelete() - * - * @param {Function} [callback] - * @return {Query} this - * @api private - */ - Query.prototype._findOneAndDelete = wrapThunk(function (callback) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return null; - } - - const filter = this._conditions; - const options = this._optionsForExec(); - let fields = null; - - if (this._fields != null) { - options.projection = this._castFields(utils.clone(this._fields)); - fields = options.projection; - if (fields instanceof Error) { - callback(fields); - return null; - } - } +/** + * _DEPRECATED_ Sets the slaveOk option. + * + * **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read). + * + * ####Example: + * + * query.slaveOk() // true + * query.slaveOk(true) + * query.slaveOk(false) + * + * @method slaveOk + * @memberOf Query + * @instance + * @deprecated use read() preferences instead if on mongodb >= 2.2 + * @param {Boolean} v defaults to true + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/ + * @see read() #query_Query-read + * @return {Query} this + * @api public + */ - this._collection.collection.findOneAndDelete( - filter, - options, - _wrapThunkCallback(this, (err, res) => { - if (err) { - return callback(err); - } +/** + * Determines the MongoDB nodes from which to read. + * + * ####Preferences: + * + * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. + * secondary Read from secondary if available, otherwise error. + * primaryPreferred Read from primary if available, otherwise a secondary. + * secondaryPreferred Read from a secondary if available, otherwise read from the primary. + * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. + * + * Aliases + * + * p primary + * pp primaryPreferred + * s secondary + * sp secondaryPreferred + * n nearest + * + * ####Example: + * + * new Query().read('primary') + * new Query().read('p') // same as primary + * + * new Query().read('primaryPreferred') + * new Query().read('pp') // same as primaryPreferred + * + * new Query().read('secondary') + * new Query().read('s') // same as secondary + * + * new Query().read('secondaryPreferred') + * new Query().read('sp') // same as secondaryPreferred + * + * new Query().read('nearest') + * new Query().read('n') // same as nearest + * + * // read from secondaries with matching tags + * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]) + * + * Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). + * + * @method read + * @memberOf Query + * @instance + * @param {String} pref one of the listed preference options or aliases + * @param {Array} [tags] optional tags for this query + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences + * @return {Query} this + * @api public + */ - const doc = res.value; +Query.prototype.read = function read(pref, tags) { + // first cast into a ReadPreference object to support tags + const read = new ReadPreference(pref, tags); + this.options.readPreference = read; + return this; +}; - return this._completeOne(doc, res, callback); - }) - ); - }); +/*! + * ignore + */ - /** - * Issues a MongoDB [findOneAndReplace](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/) command. - * - * Finds a matching document, removes it, and passes the found document (if any) - * to the callback. Executes if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndReplace()` - * - * ####Available options - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - * ####Callback Signature - * function(error, doc) { - * // error: any errors that occurred - * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` - * } - * - * ####Examples - * - * A.where().findOneAndReplace(filter, replacement, options, callback); // executes - * A.where().findOneAndReplace(filter, replacement, options); // return Query - * A.where().findOneAndReplace(filter, replacement, callback); // executes - * A.where().findOneAndReplace(filter); // returns Query - * A.where().findOneAndReplace(callback); // executes - * A.where().findOneAndReplace(); // returns Query - * - * @method findOneAndReplace - * @memberOf Query - * @param {Object} [filter] - * @param {Object} [replacement] - * @param {Object} [options] - * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. - * @param {Function} [callback] optional params are (error, document) - * @return {Query} this - * @api public - */ - - Query.prototype.findOneAndReplace = function ( - filter, - replacement, - options, - callback - ) { - this.op = "findOneAndReplace"; - this._validate(); - - switch (arguments.length) { - case 3: - if (typeof options === "function") { - callback = options; - options = void 0; - } - break; - case 2: - if (typeof replacement === "function") { - callback = replacement; - replacement = void 0; - } - break; - case 1: - if (typeof filter === "function") { - callback = filter; - filter = void 0; - replacement = void 0; - options = void 0; - } - break; - } +Query.prototype.toString = function toString() { + if (this.op === 'count' || + this.op === 'countDocuments' || + this.op === 'find' || + this.op === 'findOne' || + this.op === 'deleteMany' || + this.op === 'deleteOne' || + this.op === 'findOneAndDelete' || + this.op === 'findOneAndRemove' || + this.op === 'remove') { + return `${this.model.modelName}.${this.op}(${util.inspect(this._conditions)})`; + } + if (this.op === 'distinct') { + return `${this.model.modelName}.distinct('${this._distinct}', ${util.inspect(this._conditions)})`; + } + if (this.op === 'findOneAndReplace' || + this.op === 'findOneAndUpdate' || + this.op === 'replaceOne' || + this.op === 'update' || + this.op === 'updateMany' || + this.op === 'updateOne') { + return `${this.model.modelName}.${this.op}(${util.inspect(this._conditions)}, ${util.inspect(this._update)})`; + } - if (mquery.canMerge(filter)) { - this.merge(filter); - } + // 'estimatedDocumentCount' or any others + return `${this.model.modelName}.${this.op}()`; +}; - if (replacement != null) { - if (hasDollarKeys(replacement)) { - throw new Error( - "The replacement document must not contain atomic operators." - ); - } - this._mergeUpdate(replacement); - } +/** + * Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/) + * associated with this query. Sessions are how you mark a query as part of a + * [transaction](/docs/transactions.html). + * + * Calling `session(null)` removes the session from this query. + * + * ####Example: + * + * const s = await mongoose.startSession(); + * await mongoose.model('Person').findOne({ name: 'Axl Rose' }).session(s); + * + * @method session + * @memberOf Query + * @instance + * @param {ClientSession} [session] from `await conn.startSession()` + * @see Connection.prototype.startSession() /docs/api.html#connection_Connection-startSession + * @see mongoose.startSession() /docs/api.html#mongoose_Mongoose-startSession + * @return {Query} this + * @api public + */ - options = options || {}; +Query.prototype.session = function session(v) { + if (v == null) { + delete this.options.session; + } + this.options.session = v; + return this; +}; - const returnOriginal = get(this, "model.base.options.returnOriginal"); - if ( - options.new == null && - options.returnDocument == null && - options.returnOriginal == null && - returnOriginal != null - ) { - options.returnOriginal = returnOriginal; - } - this.setOptions(options); - this.setOptions({ overwrite: true }); +/** + * Sets the 3 write concern parameters for this query: + * + * - `w`: Sets the specified number of `mongod` servers, or tag set of `mongod` servers, that must acknowledge this write before this write is considered successful. + * - `j`: Boolean, set to `true` to request acknowledgement that this operation has been persisted to MongoDB's on-disk journal. + * - `wtimeout`: If [`w > 1`](/docs/api.html#query_Query-w), the maximum amount of time to wait for this write to propagate through the replica set before this operation fails. The default is `0`, which means no timeout. + * + * This option is only valid for operations that write to the database: + * + * - `deleteOne()` + * - `deleteMany()` + * - `findOneAndDelete()` + * - `findOneAndReplace()` + * - `findOneAndUpdate()` + * - `remove()` + * - `update()` + * - `updateOne()` + * - `updateMany()` + * + * Defaults to the schema's [`writeConcern` option](/docs/guide.html#writeConcern) + * + * ####Example: + * + * // The 'majority' option means the `deleteOne()` promise won't resolve + * // until the `deleteOne()` has propagated to the majority of the replica set + * await mongoose.model('Person'). + * deleteOne({ name: 'Ned Stark' }). + * writeConcern({ w: 'majority' }); + * + * @method writeConcern + * @memberOf Query + * @instance + * @param {Object} writeConcern the write concern value to set + * @see mongodb https://mongodb.github.io/node-mongodb-native/3.1/api/global.html#WriteConcern + * @return {Query} this + * @api public + */ - if (!callback) { - return this; - } +Query.prototype.writeConcern = function writeConcern(val) { + if (val == null) { + delete this.options.writeConcern; + return this; + } + this.options.writeConcern = val; + return this; +}; + +/** + * Sets the specified number of `mongod` servers, or tag set of `mongod` servers, + * that must acknowledge this write before this write is considered successful. + * This option is only valid for operations that write to the database: + * + * - `deleteOne()` + * - `deleteMany()` + * - `findOneAndDelete()` + * - `findOneAndReplace()` + * - `findOneAndUpdate()` + * - `remove()` + * - `update()` + * - `updateOne()` + * - `updateMany()` + * + * Defaults to the schema's [`writeConcern.w` option](/docs/guide.html#writeConcern) + * + * ####Example: + * + * // The 'majority' option means the `deleteOne()` promise won't resolve + * // until the `deleteOne()` has propagated to the majority of the replica set + * await mongoose.model('Person'). + * deleteOne({ name: 'Ned Stark' }). + * w('majority'); + * + * @method w + * @memberOf Query + * @instance + * @param {String|number} val 0 for fire-and-forget, 1 for acknowledged by one server, 'majority' for majority of the replica set, or [any of the more advanced options](https://docs.mongodb.com/manual/reference/write-concern/#w-option). + * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#w-option + * @return {Query} this + * @api public + */ - this.exec(callback); +Query.prototype.w = function w(val) { + if (val == null) { + delete this.options.w; + } + if (this.options.writeConcern != null) { + this.options.writeConcern.w = val; + } else { + this.options.w = val; + } + return this; +}; - return this; - }; +/** + * Requests acknowledgement that this operation has been persisted to MongoDB's + * on-disk journal. + * This option is only valid for operations that write to the database: + * + * - `deleteOne()` + * - `deleteMany()` + * - `findOneAndDelete()` + * - `findOneAndReplace()` + * - `findOneAndUpdate()` + * - `remove()` + * - `update()` + * - `updateOne()` + * - `updateMany()` + * + * Defaults to the schema's [`writeConcern.j` option](/docs/guide.html#writeConcern) + * + * ####Example: + * + * await mongoose.model('Person').deleteOne({ name: 'Ned Stark' }).j(true); + * + * @method j + * @memberOf Query + * @instance + * @param {boolean} val + * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#j-option + * @return {Query} this + * @api public + */ - /*! - * Thunk around findOneAndReplace() - * - * @param {Function} [callback] - * @return {Query} this - * @api private - */ - Query.prototype._findOneAndReplace = wrapThunk(function (callback) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return null; - } - - const filter = this._conditions; - const options = this._optionsForExec(); - convertNewToReturnDocument(options); - let fields = null; - - let castedDoc = new this.model(this._update, null, true); - this._update = castedDoc; - - this._applyPaths(); - if (this._fields != null) { - options.projection = this._castFields(utils.clone(this._fields)); - fields = options.projection; - if (fields instanceof Error) { - callback(fields); - return null; - } - } +Query.prototype.j = function j(val) { + if (val == null) { + delete this.options.j; + } + if (this.options.writeConcern != null) { + this.options.writeConcern.j = val; + } else { + this.options.j = val; + } + return this; +}; - castedDoc.validate((err) => { - if (err != null) { - return callback(err); - } +/** + * If [`w > 1`](/docs/api.html#query_Query-w), the maximum amount of time to + * wait for this write to propagate through the replica set before this + * operation fails. The default is `0`, which means no timeout. + * + * This option is only valid for operations that write to the database: + * + * - `deleteOne()` + * - `deleteMany()` + * - `findOneAndDelete()` + * - `findOneAndReplace()` + * - `findOneAndUpdate()` + * - `remove()` + * - `update()` + * - `updateOne()` + * - `updateMany()` + * + * Defaults to the schema's [`writeConcern.wtimeout` option](/docs/guide.html#writeConcern) + * + * ####Example: + * + * // The `deleteOne()` promise won't resolve until this `deleteOne()` has + * // propagated to at least `w = 2` members of the replica set. If it takes + * // longer than 1 second, this `deleteOne()` will fail. + * await mongoose.model('Person'). + * deleteOne({ name: 'Ned Stark' }). + * w(2). + * wtimeout(1000); + * + * @method wtimeout + * @memberOf Query + * @instance + * @param {number} ms number of milliseconds to wait + * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#wtimeout + * @return {Query} this + * @api public + */ - if (castedDoc.toBSON) { - castedDoc = castedDoc.toBSON(); - } +Query.prototype.wtimeout = function wtimeout(ms) { + if (ms == null) { + delete this.options.wtimeout; + } + if (this.options.writeConcern != null) { + this.options.writeConcern.wtimeout = ms; + } else { + this.options.wtimeout = ms; + } + return this; +}; - this._collection.collection.findOneAndReplace( - filter, - castedDoc, - options, - _wrapThunkCallback(this, (err, res) => { - if (err) { - return callback(err); - } +/** + * Sets the readConcern option for the query. + * + * ####Example: + * + * new Query().readConcern('local') + * new Query().readConcern('l') // same as local + * + * new Query().readConcern('available') + * new Query().readConcern('a') // same as available + * + * new Query().readConcern('majority') + * new Query().readConcern('m') // same as majority + * + * new Query().readConcern('linearizable') + * new Query().readConcern('lz') // same as linearizable + * + * new Query().readConcern('snapshot') + * new Query().readConcern('s') // same as snapshot + * + * + * ####Read Concern Level: + * + * local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). + * available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). + * majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. + * linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. + * snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. + * + * Aliases + * + * l local + * a available + * m majority + * lz linearizable + * s snapshot + * + * Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/). + * + * @memberOf Query + * @method readConcern + * @param {String} level one of the listed read concern level or their aliases + * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/ + * @return {Query} this + * @api public + */ + +/** + * Gets query options. + * + * ####Example: + * + * const query = new Query(); + * query.limit(10); + * query.setOptions({ maxTimeMS: 1000 }) + * query.getOptions(); // { limit: 10, maxTimeMS: 1000 } + * + * @return {Object} the options + * @api public + */ - const doc = res.value; +Query.prototype.getOptions = function() { + return this.options; +}; - return this._completeOne(doc, res, callback); - }) - ); - }); - }); +/** + * Sets query options. Some options only make sense for certain operations. + * + * ####Options: + * + * The following options are only for `find()`: + * + * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) + * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) + * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) + * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) + * - [allowDiskUse](https://docs.mongodb.com/manual/reference/method/cursor.allowDiskUse/) + * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) + * - [readPreference](http://docs.mongodb.org/manual/applications/replication/#read-preference) + * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) + * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) + * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) + * - [maxscan](https://docs.mongodb.org/v3.2/reference/operator/meta/maxScan/#metaOp._S_maxScan) + * + * The following options are only for write operations: `update()`, `updateOne()`, `updateMany()`, `replaceOne()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`: + * + * - [upsert](https://docs.mongodb.com/manual/reference/method/db.collection.update/) + * - [writeConcern](https://docs.mongodb.com/manual/reference/method/db.collection.update/) + * - [timestamps](https://mongoosejs.com/docs/guide.html#timestamps): If `timestamps` is set in the schema, set this option to `false` to skip timestamps for that particular update. Has no effect if `timestamps` is not enabled in the schema options. + * - overwriteDiscriminatorKey: allow setting the discriminator key in the update. Will use the correct discriminator schema if the update changes the discriminator key. + * + * The following options are only for `find()`, `findOne()`, `findById()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`: + * + * - [lean](./api.html#query_Query-lean) + * - [populate](/docs/populate.html) + * - [projection](/docs/api/query.html#query_Query-projection) + * - sanitizeProjection + * + * The following options are only for all operations **except** `update()`, `updateOne()`, `updateMany()`, `remove()`, `deleteOne()`, and `deleteMany()`: + * + * - [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) + * + * The following options are for `findOneAndUpdate()` and `findOneAndRemove()` + * + * - rawResult + * + * The following options are for all operations: + * + * - [strict](/docs/guide.html#strict) + * - [collation](https://docs.mongodb.com/manual/reference/collation/) + * - [session](https://docs.mongodb.com/manual/reference/server-sessions/) + * - [explain](https://docs.mongodb.com/manual/reference/method/cursor.explain/) + * + * @param {Object} options + * @return {Query} this + * @api public + */ - /*! - * Support the `new` option as an alternative to `returnOriginal` for backwards - * compat. - */ - - function convertNewToReturnDocument(options) { - if ("new" in options) { - options.returnDocument = options["new"] ? "after" : "before"; - delete options["new"]; - } - if ("returnOriginal" in options) { - options.returnDocument = options["returnOriginal"] - ? "before" - : "after"; - delete options["returnOriginal"]; - } - } - - /*! - * Thunk around findOneAndRemove() - * - * @param {Function} [callback] - * @return {Query} this - * @api private - */ - Query.prototype._findOneAndRemove = wrapThunk(function (callback) { - if (this.error() != null) { - callback(this.error()); - return; - } +Query.prototype.setOptions = function(options, overwrite) { + // overwrite is only for internal use + if (overwrite) { + // ensure that _mongooseOptions & options are two different objects + this._mongooseOptions = (options && utils.clone(options)) || {}; + this.options = options || {}; - this._findAndModify("remove", callback); - }); + if ('populate' in options) { + this.populate(this._mongooseOptions); + } + return this; + } + if (options == null) { + return this; + } + if (typeof options !== 'object') { + throw new Error('Options must be an object, got "' + options + '"'); + } - /*! - * Get options from query opts, falling back to the base mongoose object. - */ + if (Array.isArray(options.populate)) { + const populate = options.populate; + delete options.populate; + const _numPopulate = populate.length; + for (let i = 0; i < _numPopulate; ++i) { + this.populate(populate[i]); + } + } - function _getOption(query, option, def) { - const opts = query._optionsForExec(query.model); + if ('setDefaultsOnInsert' in options) { + this._mongooseOptions.setDefaultsOnInsert = options.setDefaultsOnInsert; + delete options.setDefaultsOnInsert; + } + if ('overwriteDiscriminatorKey' in options) { + this._mongooseOptions.overwriteDiscriminatorKey = options.overwriteDiscriminatorKey; + delete options.overwriteDiscriminatorKey; + } + if ('sanitizeProjection' in options) { + if (options.sanitizeProjection && !this._mongooseOptions.sanitizeProjection) { + sanitizeProjection(this._fields); + } - if (option in opts) { - return opts[option]; - } - if (option in query.model.base.options) { - return query.model.base.options[option]; - } - return def; - } + this._mongooseOptions.sanitizeProjection = options.sanitizeProjection; + delete options.sanitizeProjection; + } + if ('sanitizeFilter' in options) { + this._mongooseOptions.sanitizeFilter = options.sanitizeFilter; + delete options.sanitizeFilter; + } - /*! - * Override mquery.prototype._findAndModify to provide casting etc. - * - * @param {String} type - either "remove" or "update" - * @param {Function} callback - * @api private - */ + if ('defaults' in options) { + this._mongooseOptions.defaults = options.defaults; + // deleting options.defaults will cause 7287 to fail + } - Query.prototype._findAndModify = function (type, callback) { - if (typeof callback !== "function") { - throw new Error("Expected callback in _findAndModify"); - } + return Query.base.setOptions.call(this, options); +}; - const model = this.model; - const schema = model.schema; - const _this = this; - let fields; +/** + * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/), + * which makes this query return detailed execution stats instead of the actual + * query result. This method is useful for determining what index your queries + * use. + * + * Calling `query.explain(v)` is equivalent to `query.setOptions({ explain: v })` + * + * ####Example: + * + * const query = new Query(); + * const res = await query.find({ a: 1 }).explain('queryPlanner'); + * console.log(res); + * + * @param {String} [verbose] The verbosity mode. Either 'queryPlanner', 'executionStats', or 'allPlansExecution'. The default is 'queryPlanner' + * @return {Query} this + * @api public + */ - const castedQuery = castQuery(this); - if (castedQuery instanceof Error) { - return callback(castedQuery); - } +Query.prototype.explain = function(verbose) { + if (arguments.length === 0) { + this.options.explain = true; + } else if (verbose === false) { + delete this.options.explain; + } else { + this.options.explain = verbose; + } + return this; +}; - _castArrayFilters(this); +/** + * Sets the [`allowDiskUse` option](https://docs.mongodb.com/manual/reference/method/cursor.allowDiskUse/), + * which allows the MongoDB server to use more than 100 MB for this query's `sort()`. This option can + * let you work around `QueryExceededMemoryLimitNoDiskUseAllowed` errors from the MongoDB server. + * + * Note that this option requires MongoDB server >= 4.4. Setting this option is a no-op for MongoDB 4.2 + * and earlier. + * + * Calling `query.allowDiskUse(v)` is equivalent to `query.setOptions({ allowDiskUse: v })` + * + * ####Example: + * + * await query.find().sort({ name: 1 }).allowDiskUse(true); + * // Equivalent: + * await query.find().sort({ name: 1 }).allowDiskUse(); + * + * @param {Boolean} [v] Enable/disable `allowDiskUse`. If called with 0 arguments, sets `allowDiskUse: true` + * @return {Query} this + * @api public + */ - const opts = this._optionsForExec(model); +Query.prototype.allowDiskUse = function(v) { + if (arguments.length === 0) { + this.options.allowDiskUse = true; + } else if (v === false) { + delete this.options.allowDiskUse; + } else { + this.options.allowDiskUse = v; + } + return this; +}; - if ("strict" in opts) { - this._mongooseOptions.strict = opts.strict; - } +/** + * Sets the [maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/) + * option. This will tell the MongoDB server to abort if the query or write op + * has been running for more than `ms` milliseconds. + * + * Calling `query.maxTimeMS(v)` is equivalent to `query.setOptions({ maxTimeMS: v })` + * + * ####Example: + * + * const query = new Query(); + * // Throws an error 'operation exceeded time limit' as long as there's + * // >= 1 doc in the queried collection + * const res = await query.find({ $where: 'sleep(1000) || true' }).maxTimeMS(100); + * + * @param {Number} [ms] The number of milliseconds + * @return {Query} this + * @api public + */ - const isOverwriting = - this.options.overwrite && !hasDollarKeys(this._update); - if (isOverwriting) { - this._update = new this.model(this._update, null, true); - } +Query.prototype.maxTimeMS = function(ms) { + this.options.maxTimeMS = ms; + return this; +}; - if (type === "remove") { - opts.remove = true; - } else { - if ( - !("new" in opts) && - !("returnOriginal" in opts) && - !("returnDocument" in opts) - ) { - opts.new = false; - } - if (!("upsert" in opts)) { - opts.upsert = false; - } - if (opts.upsert || opts["new"]) { - opts.remove = false; - } +/** + * Returns the current query filter (also known as conditions) as a [POJO](https://masteringjs.io/tutorials/fundamentals/pojo). + * + * ####Example: + * + * const query = new Query(); + * query.find({ a: 1 }).where('b').gt(2); + * query.getFilter(); // { a: 1, b: { $gt: 2 } } + * + * @return {Object} current query filter + * @api public + */ - if (!isOverwriting) { - this._update = castDoc(this, opts.overwrite); - const _opts = Object.assign({}, opts, { - setDefaultsOnInsert: this._mongooseOptions.setDefaultsOnInsert, - }); - this._update = setDefaultsOnInsert( - this._conditions, - schema, - this._update, - _opts - ); - if (!this._update || Object.keys(this._update).length === 0) { - if (opts.upsert) { - // still need to do the upsert to empty doc - const doc = utils.clone(castedQuery); - delete doc._id; - this._update = { $set: doc }; - } else { - this.findOne(callback); - return this; - } - } else if (this._update instanceof Error) { - return callback(this._update); - } else { - // In order to make MongoDB 2.6 happy (see - // https://jira.mongodb.org/browse/SERVER-12266 and related issues) - // if we have an actual update document but $set is empty, junk the $set. - if ( - this._update.$set && - Object.keys(this._update.$set).length === 0 - ) { - delete this._update.$set; - } - } - } +Query.prototype.getFilter = function() { + return this._conditions; +}; - if (Array.isArray(opts.arrayFilters)) { - opts.arrayFilters = removeUnusedArrayFilters( - this._update, - opts.arrayFilters - ); - } - } +/** + * Returns the current query filter. Equivalent to `getFilter()`. + * + * You should use `getFilter()` instead of `getQuery()` where possible. `getQuery()` + * will likely be deprecated in a future release. + * + * ####Example: + * + * const query = new Query(); + * query.find({ a: 1 }).where('b').gt(2); + * query.getQuery(); // { a: 1, b: { $gt: 2 } } + * + * @return {Object} current query filter + * @api public + */ - this._applyPaths(); +Query.prototype.getQuery = function() { + return this._conditions; +}; - const options = this._mongooseOptions; +/** + * Sets the query conditions to the provided JSON object. + * + * ####Example: + * + * const query = new Query(); + * query.find({ a: 1 }) + * query.setQuery({ a: 2 }); + * query.getQuery(); // { a: 2 } + * + * @param {Object} new query conditions + * @return {undefined} + * @api public + */ - if (this._fields) { - fields = utils.clone(this._fields); - opts.projection = this._castFields(fields); - if (opts.projection instanceof Error) { - return callback(opts.projection); - } - } +Query.prototype.setQuery = function(val) { + this._conditions = val; +}; - if (opts.sort) convertSortToArray(opts); +/** + * Returns the current update operations as a JSON object. + * + * ####Example: + * + * const query = new Query(); + * query.update({}, { $set: { a: 5 } }); + * query.getUpdate(); // { $set: { a: 5 } } + * + * @return {Object} current update operations + * @api public + */ - const cb = function (err, doc, res) { - if (err) { - return callback(err); - } +Query.prototype.getUpdate = function() { + return this._update; +}; - _this._completeOne(doc, res, callback); - }; +/** + * Sets the current update operation to new value. + * + * ####Example: + * + * const query = new Query(); + * query.update({}, { $set: { a: 5 } }); + * query.setUpdate({ $set: { b: 6 } }); + * query.getUpdate(); // { $set: { b: 6 } } + * + * @param {Object} new update operation + * @return {undefined} + * @api public + */ - let useFindAndModify = true; - const runValidators = _getOption(this, "runValidators", false); - const base = _this.model && _this.model.base; - const conn = get(model, "collection.conn", {}); - if ("useFindAndModify" in base.options) { - useFindAndModify = base.get("useFindAndModify"); - } - if ("useFindAndModify" in conn.config) { - useFindAndModify = conn.config.useFindAndModify; - } - if ("useFindAndModify" in options) { - useFindAndModify = options.useFindAndModify; - } - if (useFindAndModify === false) { - // Bypass mquery - const collection = _this._collection.collection; - convertNewToReturnDocument(opts); - - if (type === "remove") { - collection.findOneAndDelete( - castedQuery, - opts, - _wrapThunkCallback(_this, function (error, res) { - return cb(error, res ? res.value : res, res); - }) - ); +Query.prototype.setUpdate = function(val) { + this._update = val; +}; - return this; - } +/** + * Returns fields selection for this query. + * + * @method _fieldsForExec + * @return {Object} + * @api private + * @receiver Query + */ - // honors legacy overwrite option for backward compatibility - const updateMethod = isOverwriting - ? "findOneAndReplace" - : "findOneAndUpdate"; +Query.prototype._fieldsForExec = function() { + return utils.clone(this._fields); +}; - if (runValidators) { - this.validate(this._update, opts, isOverwriting, (error) => { - if (error) { - return callback(error); - } - if (this._update && this._update.toBSON) { - this._update = this._update.toBSON(); - } - collection[updateMethod]( - castedQuery, - this._update, - opts, - _wrapThunkCallback(_this, function (error, res) { - return cb(error, res ? res.value : res, res); - }) - ); - }); - } else { - if (this._update && this._update.toBSON) { - this._update = this._update.toBSON(); - } - collection[updateMethod]( - castedQuery, - this._update, - opts, - _wrapThunkCallback(_this, function (error, res) { - return cb(error, res ? res.value : res, res); - }) - ); - } +/** + * Return an update document with corrected `$set` operations. + * + * @method _updateForExec + * @api private + * @receiver Query + */ - return this; - } +Query.prototype._updateForExec = function() { + const update = utils.clone(this._update, { + transform: false, + depopulate: true + }); + const ops = Object.keys(update); + let i = ops.length; + const ret = {}; + + while (i--) { + const op = ops[i]; + + if (this.options.overwrite) { + ret[op] = update[op]; + continue; + } - if (runValidators) { - this.validate(this._update, opts, isOverwriting, function (error) { - if (error) { - return callback(error); - } - _legacyFindAndModify.call( - _this, - castedQuery, - _this._update, - opts, - cb - ); - }); + if ('$' !== op[0]) { + // fix up $set sugar + if (!ret.$set) { + if (update.$set) { + ret.$set = update.$set; } else { - _legacyFindAndModify.call( - _this, - castedQuery, - _this._update, - opts, - cb - ); + ret.$set = {}; } + } + ret.$set[op] = update[op]; + ops.splice(i, 1); + if (!~ops.indexOf('$set')) ops.push('$set'); + } else if ('$set' === op) { + if (!ret.$set) { + ret[op] = update[op]; + } + } else { + ret[op] = update[op]; + } + } - return this; - }; + return ret; +}; - /*! - * ignore - */ +/** + * Makes sure _path is set. + * + * @method _ensurePath + * @param {String} method + * @api private + * @receiver Query + */ - function _completeOneLean(doc, res, opts, callback) { - if (opts.rawResult) { - return callback(null, res); - } - return callback(null, doc); - } +/** + * Determines if `conds` can be merged using `mquery().merge()` + * + * @method canMerge + * @memberOf Query + * @instance + * @param {Object} conds + * @return {Boolean} + * @api private + */ - /*! - * ignore - */ +/** + * Returns default options for this query. + * + * @param {Model} model + * @api private + */ - const _legacyFindAndModify = util.deprecate(function ( - filter, - update, - opts, - cb - ) { - if (update && update.toBSON) { - update = update.toBSON(); - } - const collection = this._collection; - const sort = opts != null && Array.isArray(opts.sort) ? opts.sort : []; - const _cb = _wrapThunkCallback(this, function (error, res) { - return cb(error, res ? res.value : res, res); - }); - collection.collection._findAndModify(filter, sort, update, opts, _cb); - }, - "Mongoose: `findOneAndUpdate()` and `findOneAndDelete()` without the " + "`useFindAndModify` option set to false are deprecated. See: " + "https://mongoosejs.com/docs/deprecations.html#findandmodify"); +Query.prototype._optionsForExec = function(model) { + const options = utils.clone(this.options); + delete options.populate; + model = model || this.model; - /*! - * Override mquery.prototype._mergeUpdate to handle mongoose objects in - * updates. - * - * @param {Object} doc - * @api private - */ + if (!model) { + return options; + } - Query.prototype._mergeUpdate = function (doc) { - if ( - doc == null || - (typeof doc === "object" && Object.keys(doc).length === 0) - ) { - return; - } + // Apply schema-level `writeConcern` option + applyWriteConcern(model.schema, options); - if (!this._update) { - this._update = Array.isArray(doc) ? [] : {}; - } - if (doc instanceof Query) { - if (Array.isArray(this._update)) { - throw new Error("Cannot mix array and object updates"); - } - if (doc._update) { - utils.mergeClone(this._update, doc._update); - } - } else if (Array.isArray(doc)) { - if (!Array.isArray(this._update)) { - throw new Error("Cannot mix array and object updates"); - } - this._update = this._update.concat(doc); - } else { - if (Array.isArray(this._update)) { - throw new Error("Cannot mix array and object updates"); - } - utils.mergeClone(this._update, doc); - } - }; + const readPreference = get(model, 'schema.options.read'); + if (!('readPreference' in options) && readPreference) { + options.readPreference = readPreference; + } - /*! - * The mongodb driver 1.3.23 only supports the nested array sort - * syntax. We must convert it or sorting findAndModify will not work. - */ + if (options.upsert !== void 0) { + options.upsert = !!options.upsert; + } + if (options.writeConcern) { + if (options.j) { + options.writeConcern.j = options.j; + delete options.j; + } + if (options.w) { + options.writeConcern.w = options.w; + delete options.w; + } + if (options.wtimeout) { + options.writeConcern.wtimeout = options.wtimeout; + delete options.wtimeout; + } + } + return options; +}; - function convertSortToArray(opts) { - if (Array.isArray(opts.sort)) { - return; - } - if (!utils.isObject(opts.sort)) { - return; - } +/** + * Sets the lean option. + * + * Documents returned from queries with the `lean` option enabled are plain + * javascript objects, not [Mongoose Documents](/api/document.html). They have no + * `save` method, getters/setters, virtuals, or other Mongoose features. + * + * ####Example: + * + * new Query().lean() // true + * new Query().lean(true) + * new Query().lean(false) + * + * const docs = await Model.find().lean(); + * docs[0] instanceof mongoose.Document; // false + * + * [Lean is great for high-performance, read-only cases](/docs/tutorials/lean.html), + * especially when combined + * with [cursors](/docs/queries.html#streaming). + * + * If you need virtuals, getters/setters, or defaults with `lean()`, you need + * to use a plugin. See: + * + * - [mongoose-lean-virtuals](https://plugins.mongoosejs.io/plugins/lean-virtuals) + * - [mongoose-lean-getters](https://plugins.mongoosejs.io/plugins/lean-getters) + * - [mongoose-lean-defaults](https://www.npmjs.com/package/mongoose-lean-defaults) + * + * @param {Boolean|Object} bool defaults to true + * @return {Query} this + * @api public + */ - const sort = []; +Query.prototype.lean = function(v) { + this._mongooseOptions.lean = arguments.length ? v : true; + return this; +}; - for (const key in opts.sort) { - if (utils.object.hasOwnProperty(opts.sort, key)) { - sort.push([key, opts.sort[key]]); - } - } +/** + * Adds a `$set` to this query's update without changing the operation. + * This is useful for query middleware so you can add an update regardless + * of whether you use `updateOne()`, `updateMany()`, `findOneAndUpdate()`, etc. + * + * ####Example: + * + * // Updates `{ $set: { updatedAt: new Date() } }` + * new Query().updateOne({}, {}).set('updatedAt', new Date()); + * new Query().updateMany({}, {}).set({ updatedAt: new Date() }); + * + * @param {String|Object} path path or object of key/value pairs to set + * @param {Any} [val] the value to set + * @return {Query} this + * @api public + */ - opts.sort = sort; - } +Query.prototype.set = function(path, val) { + if (typeof path === 'object') { + const keys = Object.keys(path); + for (const key of keys) { + this.set(key, path[key]); + } + return this; + } - /*! - * ignore - */ + this._update = this._update || {}; + this._update.$set = this._update.$set || {}; + this._update.$set[path] = val; + return this; +}; - function _updateThunk(op, callback) { - this._castConditions(); +/** + * For update operations, returns the value of a path in the update's `$set`. + * Useful for writing getters/setters that can work with both update operations + * and `save()`. + * + * ####Example: + * + * const query = Model.updateOne({}, { $set: { name: 'Jean-Luc Picard' } }); + * query.get('name'); // 'Jean-Luc Picard' + * + * @param {String|Object} path path or object of key/value pairs to get + * @return {Query} this + * @api public + */ - _castArrayFilters(this); +Query.prototype.get = function get(path) { + const update = this._update; + if (update == null) { + return void 0; + } + const $set = update.$set; + if ($set == null) { + return update[path]; + } - if (this.error() != null) { - callback(this.error()); - return null; - } + if (utils.hasUserDefinedProperty(update, path)) { + return update[path]; + } + if (utils.hasUserDefinedProperty($set, path)) { + return $set[path]; + } - callback = _wrapThunkCallback(this, callback); - const oldCb = callback; - callback = function (error, result) { - oldCb(error, result ? result.result : { ok: 0, n: 0, nModified: 0 }); - }; + return void 0; +}; - const castedQuery = this._conditions; - const options = this._optionsForExec(this.model); - - ++this._executionCount; - - this._update = utils.clone(this._update, options); - const isOverwriting = - this.options.overwrite && !hasDollarKeys(this._update); - if (isOverwriting) { - if (op === "updateOne" || op === "updateMany") { - return callback( - new MongooseError( - "The MongoDB server disallows " + - "overwriting documents using `" + - op + - "`. See: " + - "https://mongoosejs.com/docs/deprecations.html#update" - ) - ); - } - this._update = new this.model(this._update, null, true); - } else { - this._update = castDoc(this, options.overwrite); +/** + * Gets/sets the error flag on this query. If this flag is not null or + * undefined, the `exec()` promise will reject without executing. + * + * ####Example: + * + * Query().error(); // Get current error value + * Query().error(null); // Unset the current error + * Query().error(new Error('test')); // `exec()` will resolve with test + * Schema.pre('find', function() { + * if (!this.getQuery().userId) { + * this.error(new Error('Not allowed to query without setting userId')); + * } + * }); + * + * Note that query casting runs **after** hooks, so cast errors will override + * custom errors. + * + * ####Example: + * const TestSchema = new Schema({ num: Number }); + * const TestModel = db.model('Test', TestSchema); + * TestModel.find({ num: 'not a number' }).error(new Error('woops')).exec(function(error) { + * // `error` will be a cast error because `num` failed to cast + * }); + * + * @param {Error|null} err if set, `exec()` will fail fast before sending the query to MongoDB + * @return {Query} this + * @api public + */ - if (this._update instanceof Error) { - callback(this._update); - return null; - } +Query.prototype.error = function error(err) { + if (arguments.length === 0) { + return this._error; + } - if (this._update == null || Object.keys(this._update).length === 0) { - callback(null, 0); - return null; - } + this._error = err; + return this; +}; - const _opts = Object.assign({}, options, { - setDefaultsOnInsert: this._mongooseOptions.setDefaultsOnInsert, - }); - this._update = setDefaultsOnInsert( - this._conditions, - this.model.schema, - this._update, - _opts - ); - } +/*! + * ignore + */ - if (Array.isArray(options.arrayFilters)) { - options.arrayFilters = removeUnusedArrayFilters( - this._update, - options.arrayFilters - ); - } +Query.prototype._unsetCastError = function _unsetCastError() { + if (this._error != null && !(this._error instanceof CastError)) { + return; + } + return this.error(null); +}; - const runValidators = _getOption(this, "runValidators", false); - if (runValidators) { - this.validate(this._update, options, isOverwriting, (err) => { - if (err) { - return callback(err); - } +/** + * Getter/setter around the current mongoose-specific options for this query + * Below are the current Mongoose-specific options. + * + * - `populate`: an array representing what paths will be populated. Should have one entry for each call to [`Query.prototype.populate()`](/docs/api.html#query_Query-populate) + * - `lean`: if truthy, Mongoose will not [hydrate](/docs/api.html#model_Model.hydrate) any documents that are returned from this query. See [`Query.prototype.lean()`](/docs/api.html#query_Query-lean) for more information. + * - `strict`: controls how Mongoose handles keys that aren't in the schema for updates. This option is `true` by default, which means Mongoose will silently strip any paths in the update that aren't in the schema. See the [`strict` mode docs](/docs/guide.html#strict) for more information. + * - `strictQuery`: controls how Mongoose handles keys that aren't in the schema for the query `filter`. This option is `false` by default for backwards compatibility, which means Mongoose will allow `Model.find({ foo: 'bar' })` even if `foo` is not in the schema. See the [`strictQuery` docs](/docs/guide.html#strictQuery) for more information. + * - `nearSphere`: use `$nearSphere` instead of `near()`. See the [`Query.prototype.nearSphere()` docs](/docs/api.html#query_Query-nearSphere) + * + * Mongoose maintains a separate object for internal options because + * Mongoose sends `Query.prototype.options` to the MongoDB server, and the + * above options are not relevant for the MongoDB server. + * + * @param {Object} options if specified, overwrites the current options + * @return {Object} the options + * @api public + */ - if (this._update.toBSON) { - this._update = this._update.toBSON(); - } - this._collection[op](castedQuery, this._update, options, callback); - }); - return null; - } +Query.prototype.mongooseOptions = function(v) { + if (arguments.length > 0) { + this._mongooseOptions = v; + } + return this._mongooseOptions; +}; - if (this._update.toBSON) { - this._update = this._update.toBSON(); - } +/*! + * ignore + */ - this._collection[op](castedQuery, this._update, options, callback); - return null; - } +Query.prototype._castConditions = function() { + let sanitizeFilterOpt = undefined; + if (this.model != null && utils.hasUserDefinedProperty(this.model.db.options, 'sanitizeFilter')) { + sanitizeFilterOpt = this.model.db.options.sanitizeFilter; + } else if (this.model != null && utils.hasUserDefinedProperty(this.model.base.options, 'sanitizeFilter')) { + sanitizeFilterOpt = this.model.base.options.sanitizeFilter; + } else { + sanitizeFilterOpt = this._mongooseOptions.sanitizeFilter; + } - /*! - * Mongoose calls this function internally to validate the query if - * `runValidators` is set - * - * @param {Object} castedDoc the update, after casting - * @param {Object} options the options from `_optionsForExec()` - * @param {Function} callback - * @api private - */ - - Query.prototype.validate = function validate( - castedDoc, - options, - isOverwriting, - callback - ) { - return promiseOrCallback(callback, (cb) => { - try { - if (isOverwriting) { - castedDoc.validate(cb); - } else { - updateValidators(this, this.model.schema, castedDoc, options, cb); - } - } catch (err) { - immediate(function () { - cb(err); - }); - } - }); - }; + if (sanitizeFilterOpt) { + sanitizeFilter(this._conditions); + } - /*! - * Internal thunk for .update() - * - * @param {Function} callback - * @see Model.update #model_Model.update - * @api private - */ - Query.prototype._execUpdate = wrapThunk(function (callback) { - return _updateThunk.call(this, "update", callback); - }); + try { + this.cast(this.model); + this._unsetCastError(); + } catch (err) { + this.error(err); + } +}; - /*! - * Internal thunk for .updateMany() - * - * @param {Function} callback - * @see Model.update #model_Model.update - * @api private - */ - Query.prototype._updateMany = wrapThunk(function (callback) { - return _updateThunk.call(this, "updateMany", callback); - }); +/*! + * ignore + */ - /*! - * Internal thunk for .updateOne() - * - * @param {Function} callback - * @see Model.update #model_Model.update - * @api private - */ - Query.prototype._updateOne = wrapThunk(function (callback) { - return _updateThunk.call(this, "updateOne", callback); - }); +function _castArrayFilters(query) { + try { + castArrayFilters(query); + } catch (err) { + query.error(err); + } +} - /*! - * Internal thunk for .replaceOne() - * - * @param {Function} callback - * @see Model.replaceOne #model_Model.replaceOne - * @api private - */ - Query.prototype._replaceOne = wrapThunk(function (callback) { - return _updateThunk.call(this, "replaceOne", callback); - }); +/** + * Thunk around find() + * + * @param {Function} [callback] + * @return {Query} this + * @api private + */ +Query.prototype._find = wrapThunk(function(callback) { + this._castConditions(); - /** - * Declare and/or execute this query as an update() operation. - * - * _All paths passed that are not [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operations will become `$set` ops._ - * - * This function triggers the following middleware. - * - * - `update()` - * - * ####Example - * - * Model.where({ _id: id }).update({ title: 'words' }) - * - * // becomes - * - * Model.where({ _id: id }).update({ $set: { title: 'words' }}) - * - * ####Valid options: - * - * - `upsert` (boolean) whether to create the doc if it doesn't match (false) - * - `multi` (boolean) whether multiple documents should be updated (false) - * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * - `strict` (boolean) overrides the `strict` option for this update - * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false) - * - `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false. - * - `read` - * - `writeConcern` - * - * ####Note - * - * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. - * - * ####Note - * - * The operation is only executed when a callback is passed. To force execution without a callback, we must first call update() and then execute it by using the `exec()` method. - * - * const q = Model.where({ _id: id }); - * q.update({ $set: { name: 'bob' }}).update(); // not executed - * - * q.update({ $set: { name: 'bob' }}).exec(); // executed - * - * // keys that are not [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) ops become `$set`. - * // this executes the same command as the previous example. - * q.update({ name: 'bob' }).exec(); - * - * // overwriting with empty docs - * const q = Model.where({ _id: id }).setOptions({ overwrite: true }) - * q.update({ }, callback); // executes - * - * // multi update with overwrite to empty doc - * const q = Model.where({ _id: id }); - * q.setOptions({ multi: true, overwrite: true }) - * q.update({ }); - * q.update(callback); // executed - * - * // multi updates - * Model.where() - * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) - * - * // more multi updates - * Model.where() - * .setOptions({ multi: true }) - * .update({ $set: { arr: [] }}, callback) - * - * // single update by default - * Model.where({ email: 'address@example.com' }) - * .update({ $inc: { counter: 1 }}, callback) - * - * API summary - * - * update(filter, doc, options, cb) // executes - * update(filter, doc, options) - * update(filter, doc, cb) // executes - * update(filter, doc) - * update(doc, cb) // executes - * update(doc) - * update(cb) // executes - * update(true) // executes - * update() - * - * @param {Object} [filter] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. - * @param {Function} [callback] params are (error, writeOpResult) - * @return {Query} this - * @see Model.update #model_Model.update - * @see Query docs https://mongoosejs.com/docs/queries.html - * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output - * @api public - */ - - Query.prototype.update = function (conditions, doc, options, callback) { - if (typeof options === "function") { - // .update(conditions, doc, callback) - callback = options; - options = null; - } else if (typeof doc === "function") { - // .update(doc, callback); - callback = doc; - doc = conditions; - conditions = {}; - options = null; - } else if (typeof conditions === "function") { - // .update(callback) - callback = conditions; - conditions = undefined; - doc = undefined; - options = undefined; - } else if ( - typeof conditions === "object" && - !doc && - !options && - !callback - ) { - // .update(doc) - doc = conditions; - conditions = undefined; - options = undefined; - callback = undefined; - } + if (this.error() != null) { + callback(this.error()); + return null; + } - return _update(this, "update", conditions, doc, options, callback); - }; + callback = _wrapThunkCallback(this, callback); - /** - * Declare and/or execute this query as an updateMany() operation. Same as - * `update()`, except MongoDB will update _all_ documents that match - * `filter` (as opposed to just the first one) regardless of the value of - * the `multi` option. - * - * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')` - * and `post('updateMany')` instead. - * - * ####Example: - * const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true }); - * res.n; // Number of documents matched - * res.nModified; // Number of documents modified - * - * This function triggers the following middleware. - * - * - `updateMany()` - * - * @param {Object} [filter] - * @param {Object|Array} [update] the update command - * @param {Object} [options] - * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. - * @param {Function} [callback] params are (error, writeOpResult) - * @return {Query} this - * @see Model.update #model_Model.update - * @see Query docs https://mongoosejs.com/docs/queries.html - * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output - * @api public - */ - - Query.prototype.updateMany = function ( - conditions, - doc, - options, - callback - ) { - if (typeof options === "function") { - // .update(conditions, doc, callback) - callback = options; - options = null; - } else if (typeof doc === "function") { - // .update(doc, callback); - callback = doc; - doc = conditions; - conditions = {}; - options = null; - } else if (typeof conditions === "function") { - // .update(callback) - callback = conditions; - conditions = undefined; - doc = undefined; - options = undefined; - } else if ( - typeof conditions === "object" && - !doc && - !options && - !callback - ) { - // .update(doc) - doc = conditions; - conditions = undefined; - options = undefined; - callback = undefined; - } + this._applyPaths(); + this._fields = this._castFields(this._fields); - return _update(this, "updateMany", conditions, doc, options, callback); - }; + const fields = this._fieldsForExec(); + const mongooseOptions = this._mongooseOptions; + const _this = this; + const userProvidedFields = _this._userProvidedFields || {}; - /** - * Declare and/or execute this query as an updateOne() operation. Same as - * `update()`, except it does not support the `multi` or `overwrite` options. - * - * - MongoDB will update _only_ the first document that matches `filter` regardless of the value of the `multi` option. - * - Use `replaceOne()` if you want to overwrite an entire document rather than using [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators like `$set`. - * - * **Note** updateOne will _not_ fire update middleware. Use `pre('updateOne')` - * and `post('updateOne')` instead. - * - * ####Example: - * const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' }); - * res.n; // Number of documents matched - * res.nModified; // Number of documents modified - * - * This function triggers the following middleware. - * - * - `updateOne()` - * - * @param {Object} [filter] - * @param {Object|Array} [update] the update command - * @param {Object} [options] - * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Function} [callback] params are (error, writeOpResult) - * @return {Query} this - * @see Model.update #model_Model.update - * @see Query docs https://mongoosejs.com/docs/queries.html - * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output - * @api public - */ - - Query.prototype.updateOne = function ( - conditions, - doc, - options, - callback - ) { - if (typeof options === "function") { - // .update(conditions, doc, callback) - callback = options; - options = null; - } else if (typeof doc === "function") { - // .update(doc, callback); - callback = doc; - doc = conditions; - conditions = {}; - options = null; - } else if (typeof conditions === "function") { - // .update(callback) - callback = conditions; - conditions = undefined; - doc = undefined; - options = undefined; - } else if ( - typeof conditions === "object" && - !doc && - !options && - !callback - ) { - // .update(doc) - doc = conditions; - conditions = undefined; - options = undefined; - callback = undefined; - } + applyGlobalMaxTimeMS(this.options, this.model); - return _update(this, "updateOne", conditions, doc, options, callback); - }; + // Separate options to pass down to `completeMany()` in case we need to + // set a session on the document + const completeManyOptions = Object.assign({}, { + session: get(this, 'options.session', null) + }); - /** - * Declare and/or execute this query as a replaceOne() operation. Same as - * `update()`, except MongoDB will replace the existing document and will - * not accept any [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators (`$set`, etc.) - * - * **Note** replaceOne will _not_ fire update middleware. Use `pre('replaceOne')` - * and `post('replaceOne')` instead. - * - * ####Example: - * const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' }); - * res.n; // Number of documents matched - * res.nModified; // Number of documents modified - * - * This function triggers the following middleware. - * - * - `replaceOne()` - * - * @param {Object} [filter] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. - * @param {Function} [callback] params are (error, writeOpResult) - * @return {Query} this - * @see Model.update #model_Model.update - * @see Query docs https://mongoosejs.com/docs/queries.html - * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output - * @api public - */ - - Query.prototype.replaceOne = function ( - conditions, - doc, - options, - callback - ) { - if (typeof options === "function") { - // .update(conditions, doc, callback) - callback = options; - options = null; - } else if (typeof doc === "function") { - // .update(doc, callback); - callback = doc; - doc = conditions; - conditions = {}; - options = null; - } else if (typeof conditions === "function") { - // .update(callback) - callback = conditions; - conditions = undefined; - doc = undefined; - options = undefined; - } else if ( - typeof conditions === "object" && - !doc && - !options && - !callback - ) { - // .update(doc) - doc = conditions; - conditions = undefined; - options = undefined; - callback = undefined; - } + const cb = (err, docs) => { + if (err) { + return callback(err); + } - this.setOptions({ overwrite: true }); - return _update(this, "replaceOne", conditions, doc, options, callback); - }; + if (docs.length === 0) { + return callback(null, docs); + } + if (this.options.explain) { + return callback(null, docs); + } - /*! - * Internal helper for update, updateMany, updateOne, replaceOne - */ + if (!mongooseOptions.populate) { + return mongooseOptions.lean ? + callback(null, docs) : + completeMany(_this.model, docs, fields, userProvidedFields, completeManyOptions, callback); + } - function _update(query, op, filter, doc, options, callback) { - // make sure we don't send in the whole Document to merge() - query.op = op; - filter = utils.toObject(filter); - doc = doc || {}; + const pop = helpers.preparePopulationOptionsMQ(_this, mongooseOptions); - // strict is an option used in the update checking, make sure it gets set - if (options != null) { - if ("strict" in options) { - query._mongooseOptions.strict = options.strict; - } - } + if (mongooseOptions.lean) { + return _this.model.populate(docs, pop, callback); + } - if ( - !(filter instanceof Query) && - filter != null && - filter.toString() !== "[object Object]" - ) { - query.error(new ObjectParameterError(filter, "filter", op)); - } else { - query.merge(filter); - } + completeMany(_this.model, docs, fields, userProvidedFields, completeManyOptions, (err, docs) => { + if (err != null) { + return callback(err); + } + _this.model.populate(docs, pop, callback); + }); + }; - if (utils.isObject(options)) { - query.setOptions(options); - } + const options = this._optionsForExec(); + options.projection = this._fieldsForExec(); + const filter = this._conditions; - query._mergeUpdate(doc); + this._collection.collection.find(filter, options, (err, cursor) => { + if (err != null) { + return cb(err); + } - // Hooks - if (callback) { - query.exec(callback); - - return query; - } - - return Query.base[op].call(query, filter, void 0, options, callback); - } - - /** - * Runs a function `fn` and treats the return value of `fn` as the new value - * for the query to resolve to. - * - * Any functions you pass to `map()` will run **after** any post hooks. - * - * ####Example: - * - * const res = await MyModel.findOne().map(res => { - * // Sets a `loadedAt` property on the doc that tells you the time the - * // document was loaded. - * return res == null ? - * res : - * Object.assign(res, { loadedAt: new Date() }); - * }); - * - * @method map - * @memberOf Query - * @instance - * @param {Function} fn function to run to transform the query result - * @return {Query} this - */ - - Query.prototype.map = function (fn) { - this._transforms.push(fn); - return this; - }; + if (options.explain) { + return cursor.explain(cb); + } + try { + return cursor.toArray(cb); + } catch (err) { + return cb(err); + } + }); +}); - /** - * Make this query throw an error if no documents match the given `filter`. - * This is handy for integrating with async/await, because `orFail()` saves you - * an extra `if` statement to check if no document was found. - * - * ####Example: - * - * // Throws if no doc returned - * await Model.findOne({ foo: 'bar' }).orFail(); - * - * // Throws if no document was updated - * await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail(); - * - * // Throws "No docs found!" error if no docs match `{ foo: 'bar' }` - * await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!')); - * - * // Throws "Not found" error if no document was found - * await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }). - * orFail(() => Error('Not found')); - * - * @method orFail - * @memberOf Query - * @instance - * @param {Function|Error} [err] optional error to throw if no docs match `filter`. If not specified, `orFail()` will throw a `DocumentNotFoundError` - * @return {Query} this - */ - - Query.prototype.orFail = function (err) { - this.map((res) => { - switch (this.op) { - case "find": - if (res.length === 0) { - throw _orFailError(err, this); - } - break; - case "findOne": - if (res == null) { - throw _orFailError(err, this); - } - break; - case "update": - case "updateMany": - case "updateOne": - if (get(res, "nModified") === 0) { - throw _orFailError(err, this); - } - break; - case "findOneAndDelete": - case "findOneAndRemove": - if (get(res, "lastErrorObject.n") === 0) { - throw _orFailError(err, this); - } - break; - case "findOneAndUpdate": - case "findOneAndReplace": - if (get(res, "lastErrorObject.updatedExisting") === false) { - throw _orFailError(err, this); - } - break; - case "deleteMany": - case "deleteOne": - case "remove": - if (res.n === 0) { - throw _orFailError(err, this); - } - break; - default: - break; - } +/** + * Find all documents that match `selector`. The result will be an array of documents. + * + * If there are too many documents in the result to fit in memory, use + * [`Query.prototype.cursor()`](api.html#query_Query-cursor) + * + * ####Example + * + * // Using async/await + * const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } }); + * + * // Using callbacks + * Movie.find({ year: { $gte: 1980, $lte: 1989 } }, function(err, arr) {}); + * + * @param {Object|ObjectId} [filter] mongodb selector. If not specified, returns all documents. + * @param {Function} [callback] + * @return {Query} this + * @api public + */ - return res; - }); - return this; - }; +Query.prototype.find = function(conditions, callback) { + this.op = 'find'; - /*! - * Get the error to throw for `orFail()` - */ + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } - function _orFailError(err, query) { - if (typeof err === "function") { - err = err.call(query); - } + conditions = utils.toObject(conditions); - if (err == null) { - err = new DocumentNotFoundError( - query.getQuery(), - query.model.modelName - ); - } + if (mquery.canMerge(conditions)) { + this.merge(conditions); - return err; - } + prepareDiscriminatorCriteria(this); + } else if (conditions != null) { + this.error(new ObjectParameterError(conditions, 'filter', 'find')); + } - /** - * Executes the query - * - * ####Examples: - * - * const promise = query.exec(); - * const promise = query.exec('update'); - * - * query.exec(callback); - * query.exec('find', callback); - * - * @param {String|Function} [operation] - * @param {Function} [callback] optional params depend on the function being called - * @return {Promise} - * @api public - */ - - Query.prototype.exec = function exec(op, callback) { - const _this = this; - // Ensure that `exec()` is the first thing that shows up in - // the stack when cast errors happen. - const castError = new CastError(); + // if we don't have a callback, then just return the query object + if (!callback) { + return Query.base.find.call(this); + } - if (typeof op === "function") { - callback = op; - op = null; - } else if (typeof op === "string") { - this.op = op; - } + this.exec(callback); - callback = this.model.$handleCallbackError(callback); + return this; +}; - return promiseOrCallback( - callback, - (cb) => { - cb = this.model.$wrapCallback(cb); +/** + * Merges another Query or conditions object into this one. + * + * When a Query is passed, conditions, field selection and options are merged. + * + * @param {Query|Object} source + * @return {Query} this + */ - if (!_this.op) { - cb(); - return; - } +Query.prototype.merge = function(source) { + if (!source) { + return this; + } - this._hooks.execPre("exec", this, [], (error) => { - if (error != null) { - return cb(_cleanCastErrorStack(castError, error)); - } - let thunk = "_" + this.op; - if (this.op === "update") { - thunk = "_execUpdate"; - } else if (this.op === "distinct") { - thunk = "__distinct"; - } - this[thunk].call(this, (error, res) => { - if (error) { - return cb(_cleanCastErrorStack(castError, error)); - } + const opts = { overwrite: true }; - this._hooks.execPost("exec", this, [], {}, (error) => { - if (error) { - return cb(_cleanCastErrorStack(castError, error)); - } + if (source instanceof Query) { + // if source has a feature, apply it to ourselves - cb(null, res); - }); - }); - }); - }, - this.model.events - ); - }; + if (source._conditions) { + utils.merge(this._conditions, source._conditions, opts); + } - /*! - * ignore - */ + if (source._fields) { + this._fields || (this._fields = {}); + utils.merge(this._fields, source._fields, opts); + } - function _cleanCastErrorStack(castError, error) { - if (error instanceof CastError) { - castError.copy(error); - return castError; - } + if (source.options) { + this.options || (this.options = {}); + utils.merge(this.options, source.options, opts); + } + + if (source._update) { + this._update || (this._update = {}); + utils.mergeClone(this._update, source._update); + } - return error; - } + if (source._distinct) { + this._distinct = source._distinct; + } - /*! - * ignore - */ + utils.merge(this._mongooseOptions, source._mongooseOptions); - function _wrapThunkCallback(query, cb) { - return function (error, res) { - if (error != null) { - return cb(error); - } + return this; + } - for (const fn of query._transforms) { - try { - res = fn(res); - } catch (error) { - return cb(error); - } - } + // plain object + utils.merge(this._conditions, source, opts); - return cb(null, res); - }; - } + return this; +}; - /** - * Executes the query returning a `Promise` which will be - * resolved with either the doc(s) or rejected with the error. - * - * More about [`then()` in JavaScript](https://masteringjs.io/tutorials/fundamentals/then). - * - * @param {Function} [resolve] - * @param {Function} [reject] - * @return {Promise} - * @api public - */ - - Query.prototype.then = function (resolve, reject) { - return this.exec().then(resolve, reject); - }; +/** + * Adds a collation to this op (MongoDB 3.4 and up) + * + * @param {Object} value + * @return {Query} this + * @see MongoDB docs https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation + * @api public + */ - /** - * Executes the query returning a `Promise` which will be - * resolved with either the doc(s) or rejected with the error. - * Like `.then()`, but only takes a rejection handler. - * - * More about [Promise `catch()` in JavaScript](https://masteringjs.io/tutorials/fundamentals/catch). - * - * @param {Function} [reject] - * @return {Promise} - * @api public - */ - - Query.prototype.catch = function (reject) { - return this.exec().then(null, reject); - }; +Query.prototype.collation = function(value) { + if (this.options == null) { + this.options = {}; + } + this.options.collation = value; + return this; +}; - /** - * Add pre [middleware](/docs/middleware.html) to this query instance. Doesn't affect - * other queries. - * - * ####Example: - * - * const q1 = Question.find({ answer: 42 }); - * q1.pre(function middleware() { - * console.log(this.getFilter()); - * }); - * await q1.exec(); // Prints "{ answer: 42 }" - * - * // Doesn't print anything, because `middleware()` is only - * // registered on `q1`. - * await Question.find({ answer: 42 }); - * - * @param {Function} fn - * @return {Promise} - * @api public - */ - - Query.prototype.pre = function (fn) { - this._hooks.pre("exec", fn); - return this; - }; +/** + * Hydrate a single doc from `findOne()`, `findOneAndUpdate()`, etc. + * + * @api private + */ - /** - * Add post [middleware](/docs/middleware.html) to this query instance. Doesn't affect - * other queries. - * - * ####Example: - * - * const q1 = Question.find({ answer: 42 }); - * q1.post(function middleware() { - * console.log(this.getFilter()); - * }); - * await q1.exec(); // Prints "{ answer: 42 }" - * - * // Doesn't print anything, because `middleware()` is only - * // registered on `q1`. - * await Question.find({ answer: 42 }); - * - * @param {Function} fn - * @return {Promise} - * @api public - */ - - Query.prototype.post = function (fn) { - this._hooks.post("exec", fn); - return this; - }; +Query.prototype._completeOne = function(doc, res, callback) { + if (!doc && !this.options.rawResult) { + return callback(null, null); + } - /*! - * Casts obj for an update command. - * - * @param {Object} obj - * @return {Object} obj after casting its values - * @api private - */ + const model = this.model; + const projection = utils.clone(this._fields); + const userProvidedFields = this._userProvidedFields || {}; + // `populate`, `lean` + const mongooseOptions = this._mongooseOptions; + // `rawResult` + const options = this.options; - Query.prototype._castUpdate = function _castUpdate(obj, overwrite) { - let strict; - let schema = this.schema; + if (options.explain) { + return callback(null, doc); + } - const discriminatorKey = schema.options.discriminatorKey; - const baseSchema = schema._baseSchema ? schema._baseSchema : schema; - if ( - this._mongooseOptions.overwriteDiscriminatorKey && - obj[discriminatorKey] != null && - baseSchema.discriminators - ) { - const _schema = baseSchema.discriminators[obj[discriminatorKey]]; - if (_schema != null) { - schema = _schema; - } - } + if (!mongooseOptions.populate) { + return mongooseOptions.lean ? + _completeOneLean(doc, res, options, callback) : + completeOne(model, doc, res, options, projection, userProvidedFields, + null, callback); + } - if ("strict" in this._mongooseOptions) { - strict = this._mongooseOptions.strict; - } else if (this.schema && this.schema.options) { - strict = this.schema.options.strict; - } else { - strict = true; - } + const pop = helpers.preparePopulationOptionsMQ(this, this._mongooseOptions); + if (mongooseOptions.lean) { + return model.populate(doc, pop, (err, doc) => { + if (err != null) { + return callback(err); + } + _completeOneLean(doc, res, options, callback); + }); + } - let omitUndefined = false; - if ("omitUndefined" in this._mongooseOptions) { - omitUndefined = this._mongooseOptions.omitUndefined; - } + completeOne(model, doc, res, options, projection, userProvidedFields, [], (err, doc) => { + if (err != null) { + return callback(err); + } + model.populate(doc, pop, callback); + }); +}; - let useNestedStrict; - if ("useNestedStrict" in this.options) { - useNestedStrict = this.options.useNestedStrict; - } +/** + * Thunk around findOne() + * + * @param {Function} [callback] + * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ + * @api private + */ - let upsert; - if ("upsert" in this.options) { - upsert = this.options.upsert; - } +Query.prototype._findOne = wrapThunk(function(callback) { + this._castConditions(); - const filter = this._conditions; - if ( - schema != null && - utils.hasUserDefinedProperty( - filter, - schema.options.discriminatorKey - ) && - typeof filter[schema.options.discriminatorKey] !== "object" && - schema.discriminators != null - ) { - const discriminatorValue = filter[schema.options.discriminatorKey]; - const byValue = getDiscriminatorByValue( - this.model.discriminators, - discriminatorValue - ); - schema = - schema.discriminators[discriminatorValue] || - (byValue && byValue.schema) || - schema; - } - - return castUpdate( - schema, - obj, - { - overwrite: overwrite, - strict: strict, - omitUndefined, - useNestedStrict: useNestedStrict, - upsert: upsert, - arrayFilters: this.options.arrayFilters, - }, - this, - this._conditions - ); - }; + if (this.error()) { + callback(this.error()); + return null; + } - /*! - * castQuery - * @api private - */ + this._applyPaths(); + this._fields = this._castFields(this._fields); - function castQuery(query) { - try { - return query.cast(query.model); - } catch (err) { - return err; - } - } + applyGlobalMaxTimeMS(this.options, this.model); - /*! - * castDoc - * @api private - */ + // don't pass in the conditions because we already merged them in + Query.base.findOne.call(this, {}, (err, doc) => { + if (err) { + callback(err); + return null; + } - function castDoc(query, overwrite) { - try { - return query._castUpdate(query._update, overwrite); - } catch (err) { - return err; - } - } - - /** - * Specifies paths which should be populated with other documents. - * - * ####Example: - * - * let book = await Book.findOne().populate('authors'); - * book.title; // 'Node.js in Action' - * book.authors[0].name; // 'TJ Holowaychuk' - * book.authors[1].name; // 'Nathan Rajlich' - * - * let books = await Book.find().populate({ - * path: 'authors', - * // `match` and `sort` apply to the Author model, - * // not the Book model. These options do not affect - * // which documents are in `books`, just the order and - * // contents of each book document's `authors`. - * match: { name: new RegExp('.*h.*', 'i') }, - * sort: { name: -1 } - * }); - * books[0].title; // 'Node.js in Action' - * // Each book's `authors` are sorted by name, descending. - * books[0].authors[0].name; // 'TJ Holowaychuk' - * books[0].authors[1].name; // 'Marc Harter' - * - * books[1].title; // 'Professional AngularJS' - * // Empty array, no authors' name has the letter 'h' - * books[1].authors; // [] - * - * Paths are populated after the query executes and a response is received. A - * separate query is then executed for each path specified for population. After - * a response for each query has also been returned, the results are passed to - * the callback. - * - * @param {Object|String} path either the path to populate or an object specifying all parameters - * @param {Object|String} [select] Field selection for the population query - * @param {Model} [model] The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field. - * @param {Object} [match] Conditions for the population query - * @param {Object} [options] Options for the population query (sort, etc) - * @param {String} [options.path=null] The path to populate. - * @param {boolean} [options.retainNullValues=false] by default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries. - * @param {boolean} [options.getters=false] if true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options). - * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them. - * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object. - * @param {Function} [options.transform=null] Function that Mongoose will call on every populated document that allows you to transform the populated document. - * @param {Object} [options.options=null] Additional options like `limit` and `lean`. - * @see population ./populate.html - * @see Query#select #query_Query-select - * @see Model.populate #model_Model.populate - * @return {Query} this - * @api public - */ - - Query.prototype.populate = function () { - // Bail when given no truthy arguments - if (!Array.from(arguments).some(Boolean)) { - return this; - } + this._completeOne(doc, null, _wrapThunkCallback(this, callback)); + }); +}); - const res = utils.populate.apply(null, arguments); +/** + * Declares the query a findOne operation. When executed, the first found document is passed to the callback. + * + * Passing a `callback` executes the query. The result of the query is a single document. + * + * * *Note:* `conditions` is optional, and if `conditions` is null or undefined, + * mongoose will send an empty `findOne` command to MongoDB, which will return + * an arbitrary document. If you're querying by `_id`, use `Model.findById()` + * instead. + * + * This function triggers the following middleware. + * + * - `findOne()` + * + * ####Example + * + * const query = Kitten.where({ color: 'white' }); + * query.findOne(function (err, kitten) { + * if (err) return handleError(err); + * if (kitten) { + * // doc may be null if no document matched + * } + * }); + * + * @param {Object} [filter] mongodb selector + * @param {Object} [projection] optional fields to return + * @param {Object} [options] see [`setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] optional params are (error, document) + * @return {Query} this + * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ + * @see Query.select #query_Query-select + * @api public + */ - // Propagate readConcern and readPreference and lean from parent query, - // unless one already specified - if (this.options != null) { - const readConcern = this.options.readConcern; - const readPref = this.options.readPreference; +Query.prototype.findOne = function(conditions, projection, options, callback) { + this.op = 'findOne'; + this._validateOp(); + + if (typeof conditions === 'function') { + callback = conditions; + conditions = null; + projection = null; + options = null; + } else if (typeof projection === 'function') { + callback = projection; + options = null; + projection = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } - for (const populateOptions of res) { - if ( - readConcern != null && - get(populateOptions, "options.readConcern") == null - ) { - populateOptions.options = populateOptions.options || {}; - populateOptions.options.readConcern = readConcern; - } - if ( - readPref != null && - get(populateOptions, "options.readPreference") == null - ) { - populateOptions.options = populateOptions.options || {}; - populateOptions.options.readPreference = readPref; - } - } - } + // make sure we don't send in the whole Document to merge() + conditions = utils.toObject(conditions); - const opts = this._mongooseOptions; + if (options) { + this.setOptions(options); + } - if (opts.lean != null) { - const lean = opts.lean; - for (const populateOptions of res) { - if (get(populateOptions, "options.lean") == null) { - populateOptions.options = populateOptions.options || {}; - populateOptions.options.lean = lean; - } - } - } + if (projection) { + this.select(projection); + } - if (!utils.isObject(opts.populate)) { - opts.populate = {}; - } + if (mquery.canMerge(conditions)) { + this.merge(conditions); - const pop = opts.populate; + prepareDiscriminatorCriteria(this); + } else if (conditions != null) { + this.error(new ObjectParameterError(conditions, 'filter', 'findOne')); + } - for (const populateOptions of res) { - const path = populateOptions.path; - if (pop[path] && pop[path].populate && populateOptions.populate) { - populateOptions.populate = pop[path].populate.concat( - populateOptions.populate - ); - } + if (!callback) { + // already merged in the conditions, don't need to send them in. + return Query.base.findOne.call(this); + } - pop[populateOptions.path] = populateOptions; - } - return this; - }; + this.exec(callback); + return this; +}; - /** - * Gets a list of paths to be populated by this query - * - * ####Example: - * bookSchema.pre('findOne', function() { - * let keys = this.getPopulatedPaths(); // ['author'] - * }); - * ... - * Book.findOne({}).populate('author'); - * - * ####Example: - * // Deep populate - * const q = L1.find().populate({ - * path: 'level2', - * populate: { path: 'level3' } - * }); - * q.getPopulatedPaths(); // ['level2', 'level2.level3'] - * - * @return {Array} an array of strings representing populated paths - * @api public - */ - - Query.prototype.getPopulatedPaths = function getPopulatedPaths() { - const obj = this._mongooseOptions.populate || {}; - const ret = Object.keys(obj); - for (const path of Object.keys(obj)) { - const pop = obj[path]; - if (!Array.isArray(pop.populate)) { - continue; - } - _getPopulatedPaths(ret, pop.populate, path + "."); - } - return ret; - }; +/** + * Thunk around count() + * + * @param {Function} [callback] + * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ + * @api private + */ - /*! - * ignore - */ +Query.prototype._count = wrapThunk(function(callback) { + try { + this.cast(this.model); + } catch (err) { + this.error(err); + } - function _getPopulatedPaths(list, arr, prefix) { - for (const pop of arr) { - list.push(prefix + pop.path); - if (!Array.isArray(pop.populate)) { - continue; - } - _getPopulatedPaths(list, pop.populate, prefix + pop.path + "."); - } - } + if (this.error()) { + return callback(this.error()); + } - /** - * Casts this query to the schema of `model` - * - * ####Note - * - * If `obj` is present, it is cast instead of this query. - * - * @param {Model} [model] the model to cast to. If not set, defaults to `this.model` - * @param {Object} [obj] - * @return {Object} - * @api public - */ + applyGlobalMaxTimeMS(this.options, this.model); - Query.prototype.cast = function (model, obj) { - obj || (obj = this._conditions); + const conds = this._conditions; + const options = this._optionsForExec(); - model = model || this.model; - const discriminatorKey = model.schema.options.discriminatorKey; - if (obj != null && obj.hasOwnProperty(discriminatorKey)) { - model = - getDiscriminatorByValue( - model.discriminators, - obj[discriminatorKey] - ) || model; - } + this._collection.count(conds, options, utils.tick(callback)); +}); - try { - return cast( - model.schema, - obj, - { - upsert: this.options && this.options.upsert, - strict: - this.options && "strict" in this.options - ? this.options.strict - : get(model, "schema.options.strict", null), - strictQuery: - (this.options && this.options.strictQuery) || - get(model, "schema.options.strictQuery", null), - }, - this - ); - } catch (err) { - // CastError, assign model - if (typeof err.setModel === "function") { - err.setModel(model); - } - throw err; - } - }; +/** + * Thunk around countDocuments() + * + * @param {Function} [callback] + * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments + * @api private + */ - /** - * Casts selected field arguments for field selection with mongo 2.2 - * - * query.select({ ids: { $elemMatch: { $in: [hexString] }}) - * - * @param {Object} fields - * @see https://github.com/Automattic/mongoose/issues/1091 - * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/ - * @api private - */ - - Query.prototype._castFields = function _castFields(fields) { - let selected, elemMatchKeys, keys, key, out, i; - - if (fields) { - keys = Object.keys(fields); - elemMatchKeys = []; - i = keys.length; - - // collect $elemMatch args - while (i--) { - key = keys[i]; - if (fields[key].$elemMatch) { - selected || (selected = {}); - selected[key] = fields[key]; - elemMatchKeys.push(key); - } - } - } +Query.prototype._countDocuments = wrapThunk(function(callback) { + try { + this.cast(this.model); + } catch (err) { + this.error(err); + } - if (selected) { - // they passed $elemMatch, cast em - try { - out = this.cast(this.model, selected); - } catch (err) { - return err; - } + if (this.error()) { + return callback(this.error()); + } - // apply the casted field args - i = elemMatchKeys.length; - while (i--) { - key = elemMatchKeys[i]; - fields[key] = out[key]; - } - } + applyGlobalMaxTimeMS(this.options, this.model); - return fields; - }; + const conds = this._conditions; + const options = this._optionsForExec(); - /** - * Applies schematype selected options to this query. - * @api private - */ + this._collection.collection.countDocuments(conds, options, utils.tick(callback)); +}); - Query.prototype._applyPaths = function applyPaths() { - this._fields = this._fields || {}; - helpers.applyPaths(this._fields, this.model.schema); +/** + * Thunk around estimatedDocumentCount() + * + * @param {Function} [callback] + * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount + * @api private + */ - let _selectPopulatedPaths = true; +Query.prototype._estimatedDocumentCount = wrapThunk(function(callback) { + if (this.error()) { + return callback(this.error()); + } - if ("selectPopulatedPaths" in this.model.base.options) { - _selectPopulatedPaths = this.model.base.options.selectPopulatedPaths; - } - if ("selectPopulatedPaths" in this.model.schema.options) { - _selectPopulatedPaths = - this.model.schema.options.selectPopulatedPaths; - } + const options = this._optionsForExec(); - if (_selectPopulatedPaths) { - selectPopulatedFields( - this._fields, - this._userProvidedFields, - this._mongooseOptions.populate - ); - } - }; + this._collection.collection.estimatedDocumentCount(options, utils.tick(callback)); +}); - /** - * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html). - * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function. - * - * The `.cursor()` function triggers pre find hooks, but **not** post find hooks. - * - * ####Example - * - * // There are 2 ways to use a cursor. First, as a stream: - * Thing. - * find({ name: /^hello/ }). - * cursor(). - * on('data', function(doc) { console.log(doc); }). - * on('end', function() { console.log('Done!'); }); - * - * // Or you can use `.next()` to manually get the next doc in the stream. - * // `.next()` returns a promise, so you can use promises or callbacks. - * const cursor = Thing.find({ name: /^hello/ }).cursor(); - * cursor.next(function(error, doc) { - * console.log(doc); - * }); - * - * // Because `.next()` returns a promise, you can use co - * // to easily iterate through all documents without loading them - * // all into memory. - * co(function*() { - * const cursor = Thing.find({ name: /^hello/ }).cursor(); - * for (let doc = yield cursor.next(); doc != null; doc = yield cursor.next()) { - * console.log(doc); - * } - * }); - * - * ####Valid options - * - * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data` and returned by `.next()`. - * - * @return {QueryCursor} - * @param {Object} [options] - * @see QueryCursor - * @api public - */ - - Query.prototype.cursor = function cursor(opts) { - this._applyPaths(); - this._fields = this._castFields(this._fields); - this.setOptions({ projection: this._fieldsForExec() }); - if (opts) { - this.setOptions(opts); - } - - const options = Object.assign({}, this._optionsForExec(), { - projection: this.projection(), - }); - try { - this.cast(this.model); - } catch (err) { - return new QueryCursor(this, options)._markError(err); - } +/** + * Specifies this query as a `count` query. + * + * This method is deprecated. If you want to count the number of documents in + * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#query_Query-estimatedDocumentCount) + * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#query_Query-countDocuments) function instead. + * + * Passing a `callback` executes the query. + * + * This function triggers the following middleware. + * + * - `count()` + * + * ####Example: + * + * const countQuery = model.where({ 'color': 'black' }).count(); + * + * query.count({ color: 'black' }).count(callback) + * + * query.count({ color: 'black' }, callback) + * + * query.where('color', 'black').count(function (err, count) { + * if (err) return handleError(err); + * console.log('there are %d kittens', count); + * }) + * + * @deprecated + * @param {Object} [filter] count documents that match this object + * @param {Function} [callback] optional params are (error, count) + * @return {Query} this + * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ + * @api public + */ - return new QueryCursor(this, options); - }; +Query.prototype.count = function(filter, callback) { + this.op = 'count'; + this._validateOp(); + if (typeof filter === 'function') { + callback = filter; + filter = undefined; + } - // the rest of these are basically to support older Mongoose syntax with mquery - - /** - * _DEPRECATED_ Alias of `maxScan` - * - * @deprecated - * @see maxScan #query_Query-maxScan - * @method maxscan - * @memberOf Query - * @instance - */ - - Query.prototype.maxscan = Query.base.maxScan; - - /** - * Sets the tailable option (for use with capped collections). - * - * ####Example - * - * query.tailable() // true - * query.tailable(true) - * query.tailable(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Boolean} bool defaults to true - * @param {Object} [opts] options to set - * @param {Number} [opts.numberOfRetries] if cursor is exhausted, retry this many times before giving up - * @param {Number} [opts.tailableRetryInterval] if cursor is exhausted, wait this many milliseconds before retrying - * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/ - * @api public - */ - - Query.prototype.tailable = function (val, opts) { - // we need to support the tailable({ awaitdata : true }) as well as the - // tailable(true, {awaitdata :true}) syntax that mquery does not support - if ( - val != null && - typeof val.constructor === "function" && - val.constructor.name === "Object" - ) { - opts = val; - val = true; - } + filter = utils.toObject(filter); - if (val === undefined) { - val = true; - } + if (mquery.canMerge(filter)) { + this.merge(filter); + } - if (opts && typeof opts === "object") { - for (const key of Object.keys(opts)) { - if (key === "awaitdata") { - // For backwards compatibility - this.options[key] = !!opts[key]; - } else { - this.options[key] = opts[key]; - } - } - } + if (!callback) { + return this; + } - return Query.base.tailable.call(this, val); - }; + this.exec(callback); - /** - * Declares an intersects query for `geometry()`. - * - * ####Example - * - * query.where('path').intersects().geometry({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * query.where('path').intersects({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * ####NOTE: - * - * **MUST** be used after `where()`. - * - * ####NOTE: - * - * In Mongoose 3.7, `intersects` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). - * - * @method intersects - * @memberOf Query - * @instance - * @param {Object} [arg] - * @return {Query} this - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/ - * @api public - */ - - /** - * Specifies a `$geometry` condition - * - * ####Example - * - * const polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] - * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) - * - * // or - * const polyB = [[ 0, 0 ], [ 1, 1 ]] - * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) - * - * // or - * const polyC = [ 0, 0 ] - * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) - * - * // or - * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) - * - * The argument is assigned to the most recent path passed to `where()`. - * - * ####NOTE: - * - * `geometry()` **must** come after either `intersects()` or `within()`. - * - * The `object` argument must contain `type` and `coordinates` properties. - * - type {String} - * - coordinates {Array} - * - * @method geometry - * @memberOf Query - * @instance - * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. - * @return {Query} this - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - - /** - * Specifies a `$near` or `$nearSphere` condition - * - * These operators return documents sorted by distance. - * - * ####Example - * - * query.where('loc').near({ center: [10, 10] }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); - * query.near('loc', { center: [10, 10], maxDistance: 5 }); - * - * @method near - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Object} val - * @return {Query} this - * @see $near http://docs.mongodb.org/manual/reference/operator/near/ - * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ - * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - - /*! - * Overwriting mquery is needed to support a couple different near() forms found in older - * versions of mongoose - * near([1,1]) - * near(1,1) - * near(field, [1,2]) - * near(field, 1, 2) - * In addition to all of the normal forms supported by mquery - */ - - Query.prototype.near = function () { - const params = []; - const sphere = this._mongooseOptions.nearSphere; - - // TODO refactor - - if (arguments.length === 1) { - if (Array.isArray(arguments[0])) { - params.push({ center: arguments[0], spherical: sphere }); - } else if (typeof arguments[0] === "string") { - // just passing a path - params.push(arguments[0]); - } else if (utils.isObject(arguments[0])) { - if (typeof arguments[0].spherical !== "boolean") { - arguments[0].spherical = sphere; - } - params.push(arguments[0]); - } else { - throw new TypeError("invalid argument"); - } - } else if (arguments.length === 2) { - if ( - typeof arguments[0] === "number" && - typeof arguments[1] === "number" - ) { - params.push({ - center: [arguments[0], arguments[1]], - spherical: sphere, - }); - } else if ( - typeof arguments[0] === "string" && - Array.isArray(arguments[1]) - ) { - params.push(arguments[0]); - params.push({ center: arguments[1], spherical: sphere }); - } else if ( - typeof arguments[0] === "string" && - utils.isObject(arguments[1]) - ) { - params.push(arguments[0]); - if (typeof arguments[1].spherical !== "boolean") { - arguments[1].spherical = sphere; - } - params.push(arguments[1]); - } else { - throw new TypeError("invalid argument"); - } - } else if (arguments.length === 3) { - if ( - typeof arguments[0] === "string" && - typeof arguments[1] === "number" && - typeof arguments[2] === "number" - ) { - params.push(arguments[0]); - params.push({ - center: [arguments[1], arguments[2]], - spherical: sphere, - }); - } else { - throw new TypeError("invalid argument"); - } - } else { - throw new TypeError("invalid argument"); - } + return this; +}; - return Query.base.near.apply(this, params); - }; +/** + * Specifies this query as a `estimatedDocumentCount()` query. Faster than + * using `countDocuments()` for large collections because + * `estimatedDocumentCount()` uses collection metadata rather than scanning + * the entire collection. + * + * `estimatedDocumentCount()` does **not** accept a filter. `Model.find({ foo: bar }).estimatedDocumentCount()` + * is equivalent to `Model.find().estimatedDocumentCount()` + * + * This function triggers the following middleware. + * + * - `estimatedDocumentCount()` + * + * ####Example: + * + * await Model.find().estimatedDocumentCount(); + * + * @param {Object} [options] passed transparently to the [MongoDB driver](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount) + * @param {Function} [callback] optional params are (error, count) + * @return {Query} this + * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount + * @api public + */ - /** - * _DEPRECATED_ Specifies a `$nearSphere` condition - * - * ####Example - * - * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); - * - * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`. - * - * ####Example - * - * query.where('loc').near({ center: [10, 10], spherical: true }); - * - * @deprecated - * @see near() #query_Query-near - * @see $near http://docs.mongodb.org/manual/reference/operator/near/ - * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ - * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ - */ - - Query.prototype.nearSphere = function () { - this._mongooseOptions.nearSphere = true; - this.near.apply(this, arguments); - return this; - }; +Query.prototype.estimatedDocumentCount = function(options, callback) { + this.op = 'estimatedDocumentCount'; + this._validateOp(); + if (typeof options === 'function') { + callback = options; + options = undefined; + } - /** - * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js) - * This function *only* works for `find()` queries. - * You do not need to call this function explicitly, the JavaScript runtime - * will call it for you. - * - * ####Example - * - * for await (const doc of Model.aggregate([{ $sort: { name: 1 } }])) { - * console.log(doc.name); - * } - * - * Node.js 10.x supports async iterators natively without any flags. You can - * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). - * - * **Note:** This function is not if `Symbol.asyncIterator` is undefined. If - * `Symbol.asyncIterator` is undefined, that means your Node.js version does not - * support async iterators. - * - * @method Symbol.asyncIterator - * @memberOf Query - * @instance - * @api public - */ - - if (Symbol.asyncIterator != null) { - Query.prototype[Symbol.asyncIterator] = function () { - return this.cursor().transformNull()._transformForAsyncIterator(); - }; - } + if (typeof options === 'object' && options != null) { + this.setOptions(options); + } - /** - * Specifies a `$polygon` condition - * - * ####Example - * - * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) - * query.polygon('loc', [10,20], [13, 25], [7,15]) - * - * @method polygon - * @memberOf Query - * @instance - * @param {String|Array} [path] - * @param {Array|Object} [coordinatePairs...] - * @return {Query} this - * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - - /** - * Specifies a `$box` condition - * - * ####Example - * - * const lowerLeft = [40.73083, -73.99756] - * const upperRight= [40.741404, -73.988135] - * - * query.where('loc').within().box(lowerLeft, upperRight) - * query.box({ ll : lowerLeft, ur : upperRight }) - * - * @method box - * @memberOf Query - * @instance - * @see $box http://docs.mongodb.org/manual/reference/operator/box/ - * @see within() Query#within #query_Query-within - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @param {Object} val - * @param [Array] Upper Right Coords - * @return {Query} this - * @api public - */ - - /*! - * this is needed to support the mongoose syntax of: - * box(field, { ll : [x,y], ur : [x2,y2] }) - * box({ ll : [x,y], ur : [x2,y2] }) - */ - - Query.prototype.box = function (ll, ur) { - if (!Array.isArray(ll) && utils.isObject(ll)) { - ur = ll.ur; - ll = ll.ll; - } - return Query.base.box.call(this, ll, ur); - }; + if (!callback) { + return this; + } - /** - * Specifies a `$center` or `$centerSphere` condition. - * - * ####Example - * - * const area = { center: [50, 50], radius: 10, unique: true } - * query.where('loc').within().circle(area) - * // alternatively - * query.circle('loc', area); - * - * // spherical calculations - * const area = { center: [50, 50], radius: 10, unique: true, spherical: true } - * query.where('loc').within().circle(area) - * // alternatively - * query.circle('loc', area); - * - * @method circle - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Object} area - * @return {Query} this - * @see $center http://docs.mongodb.org/manual/reference/operator/center/ - * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ - * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/geoWithin/ - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - - /** - * _DEPRECATED_ Alias for [circle](#query_Query-circle) - * - * **Deprecated.** Use [circle](#query_Query-circle) instead. - * - * @deprecated - * @method center - * @memberOf Query - * @instance - * @api public - */ - - Query.prototype.center = Query.base.circle; - - /** - * _DEPRECATED_ Specifies a `$centerSphere` condition - * - * **Deprecated.** Use [circle](#query_Query-circle) instead. - * - * ####Example - * - * const area = { center: [50, 50], radius: 10 }; - * query.where('loc').within().centerSphere(area); - * - * @deprecated - * @param {String} [path] - * @param {Object} val - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ - * @api public - */ - - Query.prototype.centerSphere = function () { - if ( - arguments[0] != null && - typeof arguments[0].constructor === "function" && - arguments[0].constructor.name === "Object" - ) { - arguments[0].spherical = true; - } + this.exec(callback); - if ( - arguments[1] != null && - typeof arguments[1].constructor === "function" && - arguments[1].constructor.name === "Object" - ) { - arguments[1].spherical = true; - } + return this; +}; - Query.base.circle.apply(this, arguments); - }; +/** + * Specifies this query as a `countDocuments()` query. Behaves like `count()`, + * except it always does a full collection scan when passed an empty filter `{}`. + * + * There are also minor differences in how `countDocuments()` handles + * [`$where` and a couple geospatial operators](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). + * versus `count()`. + * + * Passing a `callback` executes the query. + * + * This function triggers the following middleware. + * + * - `countDocuments()` + * + * ####Example: + * + * const countQuery = model.where({ 'color': 'black' }).countDocuments(); + * + * query.countDocuments({ color: 'black' }).count(callback); + * + * query.countDocuments({ color: 'black' }, callback); + * + * query.where('color', 'black').countDocuments(function(err, count) { + * if (err) return handleError(err); + * console.log('there are %d kittens', count); + * }); + * + * The `countDocuments()` function is similar to `count()`, but there are a + * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). + * Below are the operators that `count()` supports but `countDocuments()` does not, + * and the suggested replacement: + * + * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/) + * - `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center) + * - `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere) + * + * @param {Object} [filter] mongodb selector + * @param {Object} [options] + * @param {Function} [callback] optional params are (error, count) + * @return {Query} this + * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments + * @api public + */ - /** - * Determines if field selection has been made. - * - * @method selected - * @memberOf Query - * @instance - * @return {Boolean} - * @api public - */ - - /** - * Determines if inclusive field selection has been made. - * - * query.selectedInclusively() // false - * query.select('name') - * query.selectedInclusively() // true - * - * @method selectedInclusively - * @memberOf Query - * @instance - * @return {Boolean} - * @api public - */ - - Query.prototype.selectedInclusively = function selectedInclusively() { - return isInclusive(this._fields); - }; +Query.prototype.countDocuments = function(conditions, options, callback) { + this.op = 'countDocuments'; + this._validateOp(); + if (typeof conditions === 'function') { + callback = conditions; + conditions = undefined; + options = undefined; + } + if (typeof options === 'function') { + callback = options; + options = undefined; + } - /** - * Determines if exclusive field selection has been made. - * - * query.selectedExclusively() // false - * query.select('-name') - * query.selectedExclusively() // true - * query.selectedInclusively() // false - * - * @method selectedExclusively - * @memberOf Query - * @instance - * @return {Boolean} - * @api public - */ - - Query.prototype.selectedExclusively = function selectedExclusively() { - return isExclusive(this._fields); - }; + conditions = utils.toObject(conditions); - /** - * The model this query is associated with. - * - * #### Example: - * - * const q = MyModel.find(); - * q.model === MyModel; // true - * - * @api public - * @property model - * @memberOf Query - * @instance - */ - - Query.prototype.model; - - /*! - * Export - */ - - module.exports = Query; - - /***/ - }, + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } - /***/ 5299: /***/ ( - __unused_webpack_module, - exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies - */ - - const checkEmbeddedDiscriminatorKeyProjection = __nccwpck_require__(1762); - const get = __nccwpck_require__(8730); - const getDiscriminatorByValue = __nccwpck_require__(8689); - const isDefiningProjection = __nccwpck_require__(1903); - const clone = __nccwpck_require__(5092); - - /*! - * Prepare a set of path options for query population. - * - * @param {Query} query - * @param {Object} options - * @return {Array} - */ - - exports.preparePopulationOptions = function preparePopulationOptions( - query, - options - ) { - const _populate = query.options.populate; - const pop = Object.keys(_populate).reduce( - (vals, key) => vals.concat([_populate[key]]), - [] - ); + if (typeof options === 'object' && options != null) { + this.setOptions(options); + } - // lean options should trickle through all queries - if (options.lean != null) { - pop - .filter((p) => get(p, "options.lean") == null) - .forEach(makeLean(options.lean)); - } + if (!callback) { + return this; + } - pop.forEach((opts) => { - opts._localModel = query.model; - }); + this.exec(callback); - return pop; - }; + return this; +}; - /*! - * Prepare a set of path options for query population. This is the MongooseQuery - * version - * - * @param {Query} query - * @param {Object} options - * @return {Array} - */ - - exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ( - query, - options - ) { - const _populate = query._mongooseOptions.populate; - const pop = Object.keys(_populate).reduce( - (vals, key) => vals.concat([_populate[key]]), - [] - ); +/** + * Thunk around distinct() + * + * @param {Function} [callback] + * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ + * @api private + */ - // lean options should trickle through all queries - if (options.lean != null) { - pop - .filter((p) => get(p, "options.lean") == null) - .forEach(makeLean(options.lean)); - } +Query.prototype.__distinct = wrapThunk(function __distinct(callback) { + this._castConditions(); - const session = get(query, "options.session", null); - if (session != null) { - pop.forEach((path) => { - if (path.options == null) { - path.options = { session: session }; - return; - } - if (!("session" in path.options)) { - path.options.session = session; - } - }); - } + if (this.error()) { + callback(this.error()); + return null; + } - const projection = query._fieldsForExec(); - pop.forEach((p) => { - p._queryProjection = projection; - }); - pop.forEach((opts) => { - opts._localModel = query.model; - }); + applyGlobalMaxTimeMS(this.options, this.model); - return pop; - }; + const options = this._optionsForExec(); - /*! - * If the document is a mapped discriminator type, it returns a model instance for that type, otherwise, - * it returns an instance of the given model. - * - * @param {Model} model - * @param {Object} doc - * @param {Object} fields - * - * @return {Document} - */ - exports.createModel = function createModel( - model, - doc, - fields, - userProvidedFields, - options - ) { - model.hooks.execPreSync("createModel", doc); - const discriminatorMapping = model.schema - ? model.schema.discriminatorMapping - : null; - - const key = - discriminatorMapping && discriminatorMapping.isRoot - ? discriminatorMapping.key - : null; - - const value = doc[key]; - if (key && value && model.discriminators) { - const discriminator = - model.discriminators[value] || - getDiscriminatorByValue(model.discriminators, value); - if (discriminator) { - const _fields = clone(userProvidedFields); - exports.applyPaths(_fields, discriminator.schema); - return new discriminator(undefined, _fields, true); - } - } - if (typeof options === "undefined") { - options = {}; - options.defaults = true; - } - return new model(undefined, fields, { - skipId: true, - isNew: false, - willInit: true, - defaults: options.defaults, - }); - }; + // don't pass in the conditions because we already merged them in + this._collection.collection. + distinct(this._distinct, this._conditions, options, callback); +}); - /*! - * ignore - */ +/** + * Declares or executes a distinct() operation. + * + * Passing a `callback` executes the query. + * + * This function does not trigger any middleware. + * + * ####Example + * + * distinct(field, conditions, callback) + * distinct(field, conditions) + * distinct(field, callback) + * distinct(field) + * distinct(callback) + * distinct() + * + * @param {String} [field] + * @param {Object|Query} [filter] + * @param {Function} [callback] optional params are (error, arr) + * @return {Query} this + * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ + * @api public + */ - exports.applyPaths = function applyPaths(fields, schema) { - // determine if query is selecting or excluding fields - let exclude; - let keys; - let keyIndex; +Query.prototype.distinct = function(field, conditions, callback) { + this.op = 'distinct'; + this._validateOp(); + if (!callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = undefined; + } else if (typeof field === 'function') { + callback = field; + field = undefined; + conditions = undefined; + } + } - if (fields) { - keys = Object.keys(fields); - keyIndex = keys.length; + conditions = utils.toObject(conditions); - while (keyIndex--) { - if (keys[keyIndex][0] === "+") { - continue; - } - const field = fields[keys[keyIndex]]; - // Skip `$meta` and `$slice` - if (!isDefiningProjection(field)) { - continue; - } - exclude = !field; - break; - } - } + if (mquery.canMerge(conditions)) { + this.merge(conditions); - // if selecting, apply default schematype select:true fields - // if excluding, apply schematype select:false fields + prepareDiscriminatorCriteria(this); + } else if (conditions != null) { + this.error(new ObjectParameterError(conditions, 'filter', 'distinct')); + } - const selected = []; - const excluded = []; - const stack = []; + if (field != null) { + this._distinct = field; + } - analyzeSchema(schema); + if (callback != null) { + this.exec(callback); + } - switch (exclude) { - case true: - for (const fieldName of excluded) { - fields[fieldName] = 0; - } - break; - case false: - if ( - schema && - schema.paths["_id"] && - schema.paths["_id"].options && - schema.paths["_id"].options.select === false - ) { - fields._id = 0; - } + return this; +}; - for (const fieldName of selected) { - fields[fieldName] = fields[fieldName] || 1; - } - break; - case undefined: - if (fields == null) { - break; - } - // Any leftover plus paths must in the schema, so delete them (gh-7017) - for (const key of Object.keys(fields || {})) { - if (key.startsWith("+")) { - delete fields[key]; - } - } +/** + * Sets the sort order + * + * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. + * + * If a string is passed, it must be a space delimited list of path names. The + * sort order of each path is ascending unless the path name is prefixed with `-` + * which will be treated as descending. + * + * ####Example + * + * // sort by "field" ascending and "test" descending + * query.sort({ field: 'asc', test: -1 }); + * + * // equivalent + * query.sort('field -test'); + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object|String} arg + * @return {Query} this + * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/ + * @api public + */ - // user didn't specify fields, implies returning all fields. - // only need to apply excluded fields and delete any plus paths - for (const fieldName of excluded) { - fields[fieldName] = 0; - } - break; - } +Query.prototype.sort = function(arg) { + if (arguments.length > 1) { + throw new Error('sort() only takes 1 Argument'); + } - function analyzeSchema(schema, prefix) { - prefix || (prefix = ""); + return Query.base.sort.call(this, arg); +}; - // avoid recursion - if (stack.indexOf(schema) !== -1) { - return []; - } - stack.push(schema); - - const addedPaths = []; - schema.eachPath(function (path, type) { - if (prefix) path = prefix + "." + path; - - let addedPath = analyzePath(path, type); - // arrays - if ( - addedPath == null && - type.$isMongooseArray && - !type.$isMongooseDocumentArray - ) { - addedPath = analyzePath(path, type.caster); - } - if (addedPath != null) { - addedPaths.push(addedPath); - } - - // nested schemas - if (type.schema) { - const _addedPaths = analyzeSchema(type.schema, path); - - // Special case: if discriminator key is the only field that would - // be projected in, remove it. - if (exclude === false) { - checkEmbeddedDiscriminatorKeyProjection( - fields, - path, - type.schema, - selected, - _addedPaths - ); - } - } - }); +/** + * Declare and/or execute this query as a remove() operation. `remove()` is + * deprecated, you should use [`deleteOne()`](#query_Query-deleteOne) + * or [`deleteMany()`](#query_Query-deleteMany) instead. + * + * This function does not trigger any middleware + * + * ####Example + * + * Character.remove({ name: /Stark/ }, callback); + * + * This function calls the MongoDB driver's [`Collection#remove()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove). + * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an + * object that contains 3 properties: + * + * - `ok`: `1` if no errors occurred + * - `deletedCount`: the number of documents deleted + * - `n`: the number of documents deleted. Equal to `deletedCount`. + * + * ####Example + * + * const res = await Character.remove({ name: /Stark/ }); + * // Number of docs deleted + * res.deletedCount; + * + * ####Note + * + * Calling `remove()` creates a [Mongoose query](./queries.html), and a query + * does not execute until you either pass a callback, call [`Query#then()`](#query_Query-then), + * or call [`Query#exec()`](#query_Query-exec). + * + * // not executed + * const query = Character.remove({ name: /Stark/ }); + * + * // executed + * Character.remove({ name: /Stark/ }, callback); + * Character.remove({ name: /Stark/ }).remove(callback); + * + * // executed without a callback + * Character.exec(); + * + * @param {Object|Query} [filter] mongodb selector + * @param {Function} [callback] optional params are (error, mongooseDeleteResult) + * @return {Query} this + * @deprecated + * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult + * @see MongoDB driver remove http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove + * @api public + */ - stack.pop(); - return addedPaths; - } +Query.prototype.remove = function(filter, callback) { + this.op = 'remove'; + if (typeof filter === 'function') { + callback = filter; + filter = null; + } - function analyzePath(path, type) { - const plusPath = "+" + path; - const hasPlusPath = fields && plusPath in fields; - if (hasPlusPath) { - // forced inclusion - delete fields[plusPath]; - } + filter = utils.toObject(filter); - if (typeof type.selected !== "boolean") return; + if (mquery.canMerge(filter)) { + this.merge(filter); - if (hasPlusPath) { - // forced inclusion - delete fields[plusPath]; + prepareDiscriminatorCriteria(this); + } else if (filter != null) { + this.error(new ObjectParameterError(filter, 'filter', 'remove')); + } - // if there are other fields being included, add this one - // if no other included fields, leave this out (implied inclusion) - if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) { - fields[path] = 1; - } + if (!callback) { + return Query.base.remove.call(this); + } - return; - } + this.exec(callback); + return this; +}; - // check for parent exclusions - const pieces = path.split("."); - let cur = ""; - for (let i = 0; i < pieces.length; ++i) { - cur += cur.length ? "." + pieces[i] : pieces[i]; - if (excluded.indexOf(cur) !== -1) { - return; - } - } +/*! + * ignore + */ - // Special case: if user has included a parent path of a discriminator key, - // don't explicitly project in the discriminator key because that will - // project out everything else under the parent path - if (!exclude && get(type, "options.$skipDiscriminatorCheck", false)) { - let cur = ""; - for (let i = 0; i < pieces.length; ++i) { - cur += (cur.length === 0 ? "" : ".") + pieces[i]; - const projection = - get(fields, cur, false) || get(fields, cur + ".$", false); - if (projection && typeof projection !== "object") { - return; - } - } - } +Query.prototype._remove = wrapThunk(function(callback) { + this._castConditions(); - (type.selected ? selected : excluded).push(path); - return path; - } - }; + if (this.error() != null) { + callback(this.error()); + return this; + } - /*! - * Set each path query option to lean - * - * @param {Object} option - */ - - function makeLean(val) { - return function (option) { - option.options || (option.options = {}); - - if (val != null && Array.isArray(val.virtuals)) { - val = Object.assign({}, val); - val.virtuals = val.virtuals - .filter( - (path) => - typeof path === "string" && path.startsWith(option.path + ".") - ) - .map((path) => path.slice(option.path.length + 1)); - } + callback = _wrapThunkCallback(this, callback); - option.options.lean = val; - }; - } + return Query.base.remove.call(this, helpers.handleDeleteWriteOpResult(callback)); +}); - /*! - * Handle the `WriteOpResult` from the server - */ +/** + * Declare and/or execute this query as a `deleteOne()` operation. Works like + * remove, except it deletes at most one document regardless of the `single` + * option. + * + * This function triggers `deleteOne` middleware. + * + * ####Example + * + * await Character.deleteOne({ name: 'Eddard Stark' }); + * + * // Using callbacks: + * Character.deleteOne({ name: 'Eddard Stark' }, callback); + * + * This function calls the MongoDB driver's [`Collection#deleteOne()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne). + * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an + * object that contains 3 properties: + * + * - `ok`: `1` if no errors occurred + * - `deletedCount`: the number of documents deleted + * - `n`: the number of documents deleted. Equal to `deletedCount`. + * + * ####Example + * + * const res = await Character.deleteOne({ name: 'Eddard Stark' }); + * // `1` if MongoDB deleted a doc, `0` if no docs matched the filter `{ name: ... }` + * res.deletedCount; + * + * @param {Object|Query} [filter] mongodb selector + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] optional params are (error, mongooseDeleteResult) + * @return {Query} this + * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult + * @see MongoDB Driver deleteOne http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne + * @api public + */ - exports.handleDeleteWriteOpResult = function handleDeleteWriteOpResult( - callback - ) { - return function _handleDeleteWriteOpResult(error, res) { - if (error) { - return callback(error); - } - const mongooseResult = Object.assign({}, res.result); - if (get(res, "result.n", null) != null) { - mongooseResult.deletedCount = res.result.n; - } - if (res.deletedCount != null) { - mongooseResult.deletedCount = res.deletedCount; - } - return callback(null, mongooseResult); - }; - }; +Query.prototype.deleteOne = function(filter, options, callback) { + this.op = 'deleteOne'; + if (typeof filter === 'function') { + callback = filter; + filter = null; + options = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } else { + this.setOptions(options); + } - /***/ - }, + filter = utils.toObject(filter); - /***/ 7606: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const Kareem = __nccwpck_require__(716); - const MongooseError = __nccwpck_require__(5953); - const SchemaType = __nccwpck_require__(5660); - const SchemaTypeOptions = __nccwpck_require__(7544); - const VirtualOptions = __nccwpck_require__(5727); - const VirtualType = __nccwpck_require__(1423); - const addAutoId = __nccwpck_require__(9115); - const arrayParentSymbol = __nccwpck_require__(3240).arrayParentSymbol; - const get = __nccwpck_require__(8730); - const getConstructorName = __nccwpck_require__(7323); - const getIndexes = __nccwpck_require__(8373); - const merge = __nccwpck_require__(2830); - const mpath = __nccwpck_require__(8586); - const readPref = __nccwpck_require__(2324).get().ReadPreference; - const setupTimestamps = __nccwpck_require__(3151); - const util = __nccwpck_require__(1669); - const utils = __nccwpck_require__(9232); - const validateRef = __nccwpck_require__(5458); - - let MongooseTypes; - - const queryHooks = __nccwpck_require__(7378).middlewareFunctions; - const documentHooks = __nccwpck_require__(5373).middlewareFunctions; - const hookNames = queryHooks - .concat(documentHooks) - .reduce((s, hook) => s.add(hook), new Set()); - - let id = 0; - - /** - * Schema constructor. - * - * ####Example: - * - * const child = new Schema({ name: String }); - * const schema = new Schema({ name: String, age: Number, children: [child] }); - * const Tree = mongoose.model('Tree', schema); - * - * // setting schema options - * new Schema({ name: String }, { _id: false, autoIndex: false }) - * - * ####Options: - * - * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option) - * - [autoCreate](/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option) - * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true - * - [bufferTimeoutMS](/docs/guide.html#bufferTimeoutMS): number - defaults to 10000 (10 seconds). If `bufferCommands` is enabled, the amount of time Mongoose will wait for connectivity to be restablished before erroring out. - * - [capped](/docs/guide.html#capped): bool - defaults to false - * - [collection](/docs/guide.html#collection): string - no default - * - [discriminatorKey](/docs/guide.html#discriminatorKey): string - defaults to `__t` - * - [id](/docs/guide.html#id): bool - defaults to true - * - [_id](/docs/guide.html#_id): bool - defaults to true - * - [minimize](/docs/guide.html#minimize): bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true - * - [read](/docs/guide.html#read): string - * - [writeConcern](/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://docs.mongodb.com/manual/reference/write-concern/) - * - [shardKey](/docs/guide.html#shardKey): object - defaults to `null` - * - [strict](/docs/guide.html#strict): bool - defaults to true - * - [strictQuery](/docs/guide.html#strictQuery): bool - defaults to false - * - [toJSON](/docs/guide.html#toJSON) - object - no default - * - [toObject](/docs/guide.html#toObject) - object - no default - * - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type' - * - [typePojoToMixed](/docs/guide.html#typePojoToMixed) - boolean - defaults to true. Determines whether a type set to a POJO becomes a Mixed path or a Subdocument - * - [useNestedStrict](/docs/guide.html#useNestedStrict) - boolean - defaults to false - * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true` - * - [versionKey](/docs/guide.html#versionKey): string or object - defaults to "__v" - * - [optimisticConcurrency](/docs/guide.html#optimisticConcurrency): bool - defaults to false. Set to true to enable [optimistic concurrency](https://thecodebarbarian.com/whats-new-in-mongoose-5-10-optimistic-concurrency.html). - * - [collation](/docs/guide.html#collation): object - defaults to null (which means use no collation) - * - [selectPopulatedPaths](/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true` - * - [skipVersioning](/docs/guide.html#skipVersioning): object - paths to exclude from versioning - * - [timestamps](/docs/guide.html#timestamps): object or boolean - defaults to `false`. If true, Mongoose adds `createdAt` and `updatedAt` properties to your schema and manages those properties for you. - * - [storeSubdocValidationError](/docs/guide.html#storeSubdocValidationError): boolean - Defaults to true. If false, Mongoose will wrap validation errors in single nested document subpaths into a single validation error on the single nested subdoc's path. - * - * ####Options for Nested Schemas: - * - `excludeIndexes`: bool - defaults to `false`. If `true`, skip building indexes on this schema's paths. - * - * ####Note: - * - * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._ - * - * @param {Object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas - * @param {Object} [options] - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `init`: Emitted after the schema is compiled into a `Model`. - * @api public - */ - - function Schema(obj, options) { - if (!(this instanceof Schema)) { - return new Schema(obj, options); - } - - this.obj = obj; - this.paths = {}; - this.aliases = {}; - this.subpaths = {}; - this.virtuals = {}; - this.singleNestedPaths = {}; - this.nested = {}; - this.inherits = {}; - this.callQueue = []; - this._indexes = []; - this.methods = {}; - this.methodOptions = {}; - this.statics = {}; - this.tree = {}; - this.query = {}; - this.childSchemas = []; - this.plugins = []; - // For internal debugging. Do not use this to try to save a schema in MDB. - this.$id = ++id; - this.mapPaths = []; + if (mquery.canMerge(filter)) { + this.merge(filter); - this.s = { - hooks: new Kareem(), - }; + prepareDiscriminatorCriteria(this); + } else if (filter != null) { + this.error(new ObjectParameterError(filter, 'filter', 'deleteOne')); + } - this.options = this.defaultOptions(options); + if (!callback) { + return Query.base.deleteOne.call(this); + } - // build paths - if (Array.isArray(obj)) { - for (const definition of obj) { - this.add(definition); - } - } else if (obj) { - this.add(obj); - } + this.exec.call(this, callback); - // check if _id's value is a subdocument (gh-2276) - const _idSubDoc = obj && obj._id && utils.isObject(obj._id); + return this; +}; - // ensure the documents get an auto _id unless disabled - const auto_id = - !this.paths["_id"] && - !this.options.noId && - this.options._id && - !_idSubDoc; +/*! + * Internal thunk for `deleteOne()` + */ - if (auto_id) { - addAutoId(this); - } +Query.prototype._deleteOne = wrapThunk(function(callback) { + this._castConditions(); - this.setupTimestamp(this.options.timestamps); - } + if (this.error() != null) { + callback(this.error()); + return this; + } - /*! - * Create virtual properties with alias field - */ - function aliasFields(schema, paths) { - paths = paths || Object.keys(schema.paths); - for (const path of paths) { - const options = get(schema.paths[path], "options"); - if (options == null) { - continue; - } + callback = _wrapThunkCallback(this, callback); - const prop = schema.paths[path].path; - const alias = options.alias; + return Query.base.deleteOne.call(this, helpers.handleDeleteWriteOpResult(callback)); +}); - if (!alias) { - continue; - } +/** + * Declare and/or execute this query as a `deleteMany()` operation. Works like + * remove, except it deletes _every_ document that matches `filter` in the + * collection, regardless of the value of `single`. + * + * This function triggers `deleteMany` middleware. + * + * ####Example + * + * await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }); + * + * // Using callbacks: + * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, callback); + * + * This function calls the MongoDB driver's [`Collection#deleteMany()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany). + * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an + * object that contains 3 properties: + * + * - `ok`: `1` if no errors occurred + * - `deletedCount`: the number of documents deleted + * - `n`: the number of documents deleted. Equal to `deletedCount`. + * + * ####Example + * + * const res = await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }); + * // `0` if no docs matched the filter, number of docs deleted otherwise + * res.deletedCount; + * + * @param {Object|Query} [filter] mongodb selector + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) + * @param {Function} [callback] optional params are (error, mongooseDeleteResult) + * @return {Query} this + * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult + * @see MongoDB Driver deleteMany http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany + * @api public + */ - if (typeof alias !== "string") { - throw new Error( - "Invalid value for alias option on " + prop + ", got " + alias - ); - } +Query.prototype.deleteMany = function(filter, options, callback) { + this.op = 'deleteMany'; + if (typeof filter === 'function') { + callback = filter; + filter = null; + options = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } else { + this.setOptions(options); + } - schema.aliases[alias] = prop; + filter = utils.toObject(filter); - schema - .virtual(alias) - .get( - (function (p) { - return function () { - if (typeof this.get === "function") { - return this.get(p); - } - return this[p]; - }; - })(prop) - ) - .set( - (function (p) { - return function (v) { - return this.$set(p, v); - }; - })(prop) - ); - } - } + if (mquery.canMerge(filter)) { + this.merge(filter); - /*! - * Inherit from EventEmitter. - */ - Schema.prototype = Object.create(EventEmitter.prototype); - Schema.prototype.constructor = Schema; - Schema.prototype.instanceOfSchema = true; + prepareDiscriminatorCriteria(this); + } else if (filter != null) { + this.error(new ObjectParameterError(filter, 'filter', 'deleteMany')); + } - /*! - * ignore - */ + if (!callback) { + return Query.base.deleteMany.call(this); + } - Object.defineProperty(Schema.prototype, "$schemaType", { - configurable: false, - enumerable: false, - writable: true, - }); + this.exec.call(this, callback); - /** - * Array of child schemas (from document arrays and single nested subdocs) - * and their corresponding compiled models. Each element of the array is - * an object with 2 properties: `schema` and `model`. - * - * This property is typically only useful for plugin authors and advanced users. - * You do not need to interact with this property at all to use mongoose. - * - * @api public - * @property childSchemas - * @memberOf Schema - * @instance - */ - - Object.defineProperty(Schema.prototype, "childSchemas", { - configurable: false, - enumerable: true, - writable: true, - }); + return this; +}; - /** - * The original object passed to the schema constructor - * - * ####Example: - * - * const schema = new Schema({ a: String }).add({ b: String }); - * schema.obj; // { a: String } - * - * @api public - * @property obj - * @memberOf Schema - * @instance - */ - - Schema.prototype.obj; - - /** - * The paths defined on this schema. The keys are the top-level paths - * in this schema, and the values are instances of the SchemaType class. - * - * ####Example: - * const schema = new Schema({ name: String }, { _id: false }); - * schema.paths; // { name: SchemaString { ... } } - * - * schema.add({ age: Number }); - * schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } } - * - * @api public - * @property paths - * @memberOf Schema - * @instance - */ - - Schema.prototype.paths; - - /** - * Schema as a tree - * - * ####Example: - * { - * '_id' : ObjectId - * , 'nested' : { - * 'key' : String - * } - * } - * - * @api private - * @property tree - * @memberOf Schema - * @instance - */ - - Schema.prototype.tree; - - /** - * Returns a deep copy of the schema - * - * ####Example: - * - * const schema = new Schema({ name: String }); - * const clone = schema.clone(); - * clone === schema; // false - * clone.path('name'); // SchemaString { ... } - * - * @return {Schema} the cloned schema - * @api public - * @memberOf Schema - * @instance - */ - - Schema.prototype.clone = function () { - const Constructor = this.base == null ? Schema : this.base.Schema; - - const s = new Constructor({}, this._userProvidedOptions); - s.base = this.base; - s.obj = this.obj; - s.options = utils.clone(this.options); - s.callQueue = this.callQueue.map(function (f) { - return f; - }); - s.methods = utils.clone(this.methods); - s.methodOptions = utils.clone(this.methodOptions); - s.statics = utils.clone(this.statics); - s.query = utils.clone(this.query); - s.plugins = Array.prototype.slice.call(this.plugins); - s._indexes = utils.clone(this._indexes); - s.s.hooks = this.s.hooks.clone(); +/*! + * Internal thunk around `deleteMany()` + */ - s.tree = utils.clone(this.tree); - s.paths = utils.clone(this.paths); - s.nested = utils.clone(this.nested); - s.subpaths = utils.clone(this.subpaths); - s.singleNestedPaths = utils.clone(this.singleNestedPaths); - s.childSchemas = gatherChildSchemas(s); +Query.prototype._deleteMany = wrapThunk(function(callback) { + this._castConditions(); - s.virtuals = utils.clone(this.virtuals); - s.$globalPluginsApplied = this.$globalPluginsApplied; - s.$isRootDiscriminator = this.$isRootDiscriminator; - s.$implicitlyCreated = this.$implicitlyCreated; - s.mapPaths = [].concat(this.mapPaths); + if (this.error() != null) { + callback(this.error()); + return this; + } - if (this.discriminatorMapping != null) { - s.discriminatorMapping = Object.assign({}, this.discriminatorMapping); - } - if (this.discriminators != null) { - s.discriminators = Object.assign({}, this.discriminators); - } + callback = _wrapThunkCallback(this, callback); - s.aliases = Object.assign({}, this.aliases); + return Query.base.deleteMany.call(this, helpers.handleDeleteWriteOpResult(callback)); +}); - // Bubble up `init` for backwards compat - s.on("init", (v) => this.emit("init", v)); +/*! + * hydrates a document + * + * @param {Model} model + * @param {Document} doc + * @param {Object} res 3rd parameter to callback + * @param {Object} fields + * @param {Query} self + * @param {Array} [pop] array of paths used in population + * @param {Function} callback + */ - return s; - }; +function completeOne(model, doc, res, options, fields, userProvidedFields, pop, callback) { + const opts = pop ? + { populated: pop } + : undefined; - /** - * Returns a new schema that has the picked `paths` from this schema. - * - * This method is analagous to [Lodash's `pick()` function](https://lodash.com/docs/4.17.15#pick) for Mongoose schemas. - * - * ####Example: - * - * const schema = Schema({ name: String, age: Number }); - * // Creates a new schema with the same `name` path as `schema`, - * // but no `age` path. - * const newSchema = schema.pick(['name']); - * - * newSchema.path('name'); // SchemaString { ... } - * newSchema.path('age'); // undefined - * - * @param {Array} paths list of paths to pick - * @param {Object} [options] options to pass to the schema constructor. Defaults to `this.options` if not set. - * @return {Schema} - * @api public - */ - - Schema.prototype.pick = function (paths, options) { - const newSchema = new Schema({}, options || this.options); - if (!Array.isArray(paths)) { - throw new MongooseError( - "Schema#pick() only accepts an array argument, " + - 'got "' + - typeof paths + - '"' - ); - } + if (options.rawResult && doc == null) { + _init(null); + return null; + } - for (const path of paths) { - if (this.nested[path]) { - newSchema.add({ [path]: get(this.tree, path) }); - } else { - const schematype = this.path(path); - if (schematype == null) { - throw new MongooseError( - "Path `" + path + "` is not in the schema" - ); - } - newSchema.add({ [path]: schematype }); - } - } + const casted = helpers.createModel(model, doc, fields, userProvidedFields, options); + try { + casted.$init(doc, opts, _init); + } catch (error) { + _init(error); + } - return newSchema; - }; + function _init(err) { + if (err) { + return immediate(() => callback(err)); + } - /** - * Returns default options for this schema, merged with `options`. - * - * @param {Object} options - * @return {Object} - * @api private - */ - - Schema.prototype.defaultOptions = function (options) { - if (options && options.safe === false) { - options.safe = { w: 0 }; - } - - if (options && options.safe && options.safe.w === 0) { - // if you turn off safe writes, then versioning goes off as well - options.versionKey = false; - } - - this._userProvidedOptions = options == null ? {} : utils.clone(options); - - const baseOptions = get(this, "base.options", {}); - options = utils.options( - { - strict: "strict" in baseOptions ? baseOptions.strict : true, - strictQuery: - "strictQuery" in baseOptions ? baseOptions.strictQuery : false, - bufferCommands: true, - capped: false, // { size, max, autoIndexId } - versionKey: "__v", - optimisticConcurrency: false, - discriminatorKey: "__t", - minimize: true, - autoIndex: null, - shardKey: null, - read: null, - validateBeforeSave: true, - // the following are only applied at construction time - noId: false, // deprecated, use { _id: false } - _id: true, - noVirtualId: false, // deprecated, use { id: false } - id: true, - typeKey: "type", - typePojoToMixed: - "typePojoToMixed" in baseOptions - ? baseOptions.typePojoToMixed - : true, - }, - utils.clone(options) - ); - if (options.read) { - options.read = readPref(options.read); + if (options.rawResult) { + if (doc && casted) { + if (options.session != null) { + casted.$session(options.session); } + res.value = casted; + } else { + res.value = null; + } + return immediate(() => callback(null, res)); + } + if (options.session != null) { + casted.$session(options.session); + } + immediate(() => callback(null, casted)); + } +} - if (options.optimisticConcurrency && !options.versionKey) { - throw new MongooseError( - "Must set `versionKey` if using `optimisticConcurrency`" - ); - } +/*! + * If the model is a discriminator type and not root, then add the key & value to the criteria. + */ - return options; - }; +function prepareDiscriminatorCriteria(query) { + if (!query || !query.model || !query.model.schema) { + return; + } - /** - * Adds key path / schema type pairs to this schema. - * - * ####Example: - * - * const ToySchema = new Schema(); - * ToySchema.add({ name: 'string', color: 'string', price: 'number' }); - * - * const TurboManSchema = new Schema(); - * // You can also `add()` another schema and copy over all paths, virtuals, - * // getters, setters, indexes, methods, and statics. - * TurboManSchema.add(ToySchema).add({ year: Number }); - * - * @param {Object|Schema} obj plain object with paths to add, or another schema - * @param {String} [prefix] path to prefix the newly added paths with - * @return {Schema} the Schema instance - * @api public - */ - - Schema.prototype.add = function add(obj, prefix) { - if (obj instanceof Schema || (obj != null && obj.instanceOfSchema)) { - merge(this, obj); + const schema = query.model.schema; - return this; - } + if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) { + query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value; + } +} - // Special case: setting top-level `_id` to false should convert to disabling - // the `_id` option. This behavior never worked before 5.4.11 but numerous - // codebases use it (see gh-7516, gh-7512). - if (obj._id === false && prefix == null) { - this.options._id = false; - } +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. + * + * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found + * document (if any) to the callback. The query executes if + * `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndUpdate()` + * + * ####Available options + * + * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()` + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. + * - `setDefaultsOnInsert`: `true` by default. If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. + * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * + * ####Callback Signature + * function(error, doc) { + * // error: any errors that occurred + * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` + * } + * + * ####Examples + * + * query.findOneAndUpdate(conditions, update, options, callback) // executes + * query.findOneAndUpdate(conditions, update, options) // returns Query + * query.findOneAndUpdate(conditions, update, callback) // executes + * query.findOneAndUpdate(conditions, update) // returns Query + * query.findOneAndUpdate(update, callback) // returns Query + * query.findOneAndUpdate(update) // returns Query + * query.findOneAndUpdate(callback) // executes + * query.findOneAndUpdate() // returns Query + * + * @method findOneAndUpdate + * @memberOf Query + * @instance + * @param {Object|Query} [filter] + * @param {Object} [doc] + * @param {Object} [options] + * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. + * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. + * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. + * @param {Function} [callback] optional params are (error, doc), _unless_ `rawResult` is used, in which case params are (error, writeOpResult) + * @see Tutorial /docs/tutorials/findoneandupdate.html + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @return {Query} this + * @api public + */ - prefix = prefix || ""; - // avoid prototype pollution - if ( - prefix === "__proto__." || - prefix === "constructor." || - prefix === "prototype." - ) { - return this; - } +Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) { + this.op = 'findOneAndUpdate'; + this._validateOp(); + this._validate(); + + switch (arguments.length) { + case 3: + if (typeof options === 'function') { + callback = options; + options = {}; + } + break; + case 2: + if (typeof doc === 'function') { + callback = doc; + doc = criteria; + criteria = undefined; + } + options = undefined; + break; + case 1: + if (typeof criteria === 'function') { + callback = criteria; + criteria = options = doc = undefined; + } else { + doc = criteria; + criteria = options = undefined; + } + } - const keys = Object.keys(obj); + if (mquery.canMerge(criteria)) { + this.merge(criteria); + } - for (const key of keys) { - const fullPath = prefix + key; - - if (obj[key] == null) { - throw new TypeError( - "Invalid value for schema path `" + - fullPath + - '`, got value "' + - obj[key] + - '"' - ); - } - // Retain `_id: false` but don't set it as a path, re: gh-8274. - if (key === "_id" && obj[key] === false) { - continue; - } - if ( - obj[key] instanceof VirtualType || - get(obj[key], "constructor.name", null) === "VirtualType" - ) { - this.virtual(obj[key]); - continue; - } + // apply doc + if (doc) { + this._mergeUpdate(doc); + } - if ( - Array.isArray(obj[key]) && - obj[key].length === 1 && - obj[key][0] == null - ) { - throw new TypeError( - "Invalid value for schema Array path `" + - fullPath + - '`, got value "' + - obj[key][0] + - '"' - ); - } + options = options ? utils.clone(options) : {}; - if ( - !(utils.isPOJO(obj[key]) || obj[key] instanceof SchemaTypeOptions) - ) { - // Special-case: Non-options definitely a path so leaf at this node - // Examples: Schema instances, SchemaType instances - if (prefix) { - this.nested[prefix.substr(0, prefix.length - 1)] = true; - } - this.path(prefix + key, obj[key]); - } else if (Object.keys(obj[key]).length < 1) { - // Special-case: {} always interpreted as Mixed path so leaf at this node - if (prefix) { - this.nested[prefix.substr(0, prefix.length - 1)] = true; - } - this.path(fullPath, obj[key]); // mixed type - } else if ( - !obj[key][this.options.typeKey] || - (this.options.typeKey === "type" && obj[key].type.type) - ) { - // Special-case: POJO with no bona-fide type key - interpret as tree of deep paths so recurse - // nested object { last: { name: String }} - this.nested[fullPath] = true; - this.add(obj[key], fullPath + "."); - } else { - // There IS a bona-fide type key that may also be a POJO - if ( - !this.options.typePojoToMixed && - utils.isPOJO(obj[key][this.options.typeKey]) - ) { - // If a POJO is the value of a type key, make it a subdocument - if (prefix) { - this.nested[prefix.substr(0, prefix.length - 1)] = true; - } - // Propage `typePojoToMixed` to implicitly created schemas - const opts = { typePojoToMixed: false }; - const _schema = new Schema(obj[key][this.options.typeKey], opts); - const schemaWrappedPath = Object.assign({}, obj[key], { - [this.options.typeKey]: _schema, - }); - this.path(prefix + key, schemaWrappedPath); - } else { - // Either the type is non-POJO or we interpret it as Mixed anyway - if (prefix) { - this.nested[prefix.substr(0, prefix.length - 1)] = true; - } - this.path(prefix + key, obj[key]); - } - } - } + if (options.projection) { + this.select(options.projection); + delete options.projection; + } + if (options.fields) { + this.select(options.fields); + delete options.fields; + } - const addedKeys = Object.keys(obj).map((key) => - prefix ? prefix + key : key - ); - aliasFields(this, addedKeys); - return this; - }; - /** - * Reserved document keys. - * - * Keys in this object are names that are rejected in schema declarations - * because they conflict with Mongoose functionality. If you create a schema - * using `new Schema()` with one of these property names, Mongoose will throw - * an error. - * - * - _posts - * - _pres - * - collection - * - emit - * - errors - * - get - * - init - * - isModified - * - isNew - * - listeners - * - modelName - * - on - * - once - * - populated - * - prototype - * - remove - * - removeListener - * - save - * - schema - * - toObject - * - validate - * - * _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on. - * - * const schema = new Schema(..); - * schema.methods.init = function () {} // potentially breaking - */ - - Schema.reserved = Object.create(null); - Schema.prototype.reserved = Schema.reserved; - const reserved = Schema.reserved; - // Core object - reserved["prototype"] = - // EventEmitter - reserved.emit = - reserved.listeners = - reserved.on = - reserved.removeListener = - // document properties and functions - reserved.collection = - reserved.errors = - reserved.get = - reserved.init = - reserved.isModified = - reserved.isNew = - reserved.populated = - reserved.remove = - reserved.save = - reserved.toObject = - reserved.validate = - 1; - - /** - * Gets/sets schema paths. - * - * Sets a path (if arity 2) - * Gets a path (if arity 1) - * - * ####Example - * - * schema.path('name') // returns a SchemaType - * schema.path('name', Number) // changes the schemaType of `name` to Number - * - * @param {String} path - * @param {Object} constructor - * @api public - */ - - Schema.prototype.path = function (path, obj) { - // Convert to '.$' to check subpaths re: gh-6405 - const cleanPath = _pathToPositionalSyntax(path); - if (obj === undefined) { - let schematype = _getPath(this, path, cleanPath); - if (schematype != null) { - return schematype; - } + const returnOriginal = get(this, 'model.base.options.returnOriginal'); + if (options.new == null && options.returnDocument == null && options.returnOriginal == null && returnOriginal != null) { + options.returnOriginal = returnOriginal; + } - // Look for maps - const mapPath = getMapPath(this, path); - if (mapPath != null) { - return mapPath; - } + this.setOptions(options); - // Look if a parent of this path is mixed - schematype = this.hasMixedParent(cleanPath); - if (schematype != null) { - return schematype; - } + if (!callback) { + return this; + } - // subpaths? - return /\.\d+\.?.*$/.test(path) - ? getPositionalPath(this, path) - : undefined; - } + this.exec(callback); - // some path names conflict with document methods - const firstPieceOfPath = path.split(".")[0]; - if (reserved[firstPieceOfPath]) { - throw new Error( - "`" + firstPieceOfPath + "` may not be used as a schema pathname" - ); - } + return this; +}; - if ( - typeof obj === "object" && - utils.hasUserDefinedProperty(obj, "ref") - ) { - validateRef(obj.ref, path); - } +/*! + * Thunk around findOneAndUpdate() + * + * @param {Function} [callback] + * @api private + */ - // update the tree - const subpaths = path.split(/\./); - const last = subpaths.pop(); - let branch = this.tree; - let fullPath = ""; +Query.prototype._findOneAndUpdate = wrapThunk(function(callback) { + if (this.error() != null) { + return callback(this.error()); + } - for (const sub of subpaths) { - fullPath = fullPath += (fullPath.length > 0 ? "." : "") + sub; - if (!branch[sub]) { - this.nested[fullPath] = true; - branch[sub] = {}; - } - if (typeof branch[sub] !== "object") { - const msg = - "Cannot set nested path `" + - path + - "`. " + - "Parent path `" + - fullPath + - "` already set to type " + - branch[sub].name + - "."; - throw new Error(msg); - } - branch = branch[sub]; - } - - branch[last] = utils.clone(obj); - - this.paths[path] = this.interpretAsType(path, obj, this.options); - const schemaType = this.paths[path]; - - if (schemaType.$isSchemaMap) { - // Maps can have arbitrary keys, so `$*` is internal shorthand for "any key" - // The '$' is to imply this path should never be stored in MongoDB so we - // can easily build a regexp out of this path, and '*' to imply "any key." - const mapPath = path + ".$*"; - let _mapType = { type: {} }; - if (utils.hasUserDefinedProperty(obj, "of")) { - const isInlineSchema = - utils.isPOJO(obj.of) && - Object.keys(obj.of).length > 0 && - !utils.hasUserDefinedProperty(obj.of, this.options.typeKey); - _mapType = isInlineSchema ? new Schema(obj.of) : obj.of; - } - if (utils.hasUserDefinedProperty(obj, "ref")) { - _mapType = { type: _mapType, ref: obj.ref }; - } + this._findAndModify('update', callback); +}); - this.paths[mapPath] = this.interpretAsType( - mapPath, - _mapType, - this.options - ); - this.mapPaths.push(this.paths[mapPath]); - schemaType.$__schemaType = this.paths[mapPath]; - } +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. + * + * Finds a matching document, removes it, passing the found document (if any) to + * the callback. Executes if `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndRemove()` + * + * ####Available options + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * + * ####Callback Signature + * function(error, doc) { + * // error: any errors that occurred + * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` + * } + * + * ####Examples + * + * A.where().findOneAndRemove(conditions, options, callback) // executes + * A.where().findOneAndRemove(conditions, options) // return Query + * A.where().findOneAndRemove(conditions, callback) // executes + * A.where().findOneAndRemove(conditions) // returns Query + * A.where().findOneAndRemove(callback) // executes + * A.where().findOneAndRemove() // returns Query + * + * @method findOneAndRemove + * @memberOf Query + * @instance + * @param {Object} [conditions] + * @param {Object} [options] + * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Function} [callback] optional params are (error, document) + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ - if (schemaType.$isSingleNested) { - for (const key of Object.keys(schemaType.schema.paths)) { - this.singleNestedPaths[path + "." + key] = - schemaType.schema.paths[key]; - } - for (const key of Object.keys(schemaType.schema.singleNestedPaths)) { - this.singleNestedPaths[path + "." + key] = - schemaType.schema.singleNestedPaths[key]; - } - for (const key of Object.keys(schemaType.schema.subpaths)) { - this.singleNestedPaths[path + "." + key] = - schemaType.schema.subpaths[key]; - } - for (const key of Object.keys(schemaType.schema.nested)) { - this.singleNestedPaths[path + "." + key] = "nested"; - } +Query.prototype.findOneAndRemove = function(conditions, options, callback) { + this.op = 'findOneAndRemove'; + this._validateOp(); + this._validate(); + + switch (arguments.length) { + case 2: + if (typeof options === 'function') { + callback = options; + options = {}; + } + break; + case 1: + if (typeof conditions === 'function') { + callback = conditions; + conditions = undefined; + options = undefined; + } + break; + } - Object.defineProperty(schemaType.schema, "base", { - configurable: true, - enumerable: false, - writable: false, - value: this.base, - }); + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } - schemaType.caster.base = this.base; - this.childSchemas.push({ - schema: schemaType.schema, - model: schemaType.caster, - }); - } else if (schemaType.$isMongooseDocumentArray) { - Object.defineProperty(schemaType.schema, "base", { - configurable: true, - enumerable: false, - writable: false, - value: this.base, - }); + options && this.setOptions(options); - schemaType.casterConstructor.base = this.base; - this.childSchemas.push({ - schema: schemaType.schema, - model: schemaType.casterConstructor, - }); - } + if (!callback) { + return this; + } - if ( - schemaType.$isMongooseArray && - schemaType.caster instanceof SchemaType - ) { - let arrayPath = path; - let _schemaType = schemaType; - - const toAdd = []; - while (_schemaType.$isMongooseArray) { - arrayPath = arrayPath + ".$"; - - // Skip arrays of document arrays - if (_schemaType.$isMongooseDocumentArray) { - _schemaType.$embeddedSchemaType._arrayPath = arrayPath; - _schemaType.$embeddedSchemaType._arrayParentPath = path; - _schemaType = _schemaType.$embeddedSchemaType.clone(); - } else { - _schemaType.caster._arrayPath = arrayPath; - _schemaType.caster._arrayParentPath = path; - _schemaType = _schemaType.caster.clone(); - } + this.exec(callback); - _schemaType.path = arrayPath; - toAdd.push(_schemaType); - } + return this; +}; - for (const _schemaType of toAdd) { - this.subpaths[_schemaType.path] = _schemaType; - } - } +/** + * Issues a MongoDB [findOneAndDelete](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndDelete/) command. + * + * Finds a matching document, removes it, and passes the found document (if any) + * to the callback. Executes if `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndDelete()` + * + * This function differs slightly from `Model.findOneAndRemove()` in that + * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/), + * as opposed to a `findOneAndDelete()` command. For most mongoose use cases, + * this distinction is purely pedantic. You should use `findOneAndDelete()` + * unless you have a good reason not to. + * + * ####Available options + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * + * ####Callback Signature + * function(error, doc) { + * // error: any errors that occurred + * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` + * } + * + * ####Examples + * + * A.where().findOneAndDelete(conditions, options, callback) // executes + * A.where().findOneAndDelete(conditions, options) // return Query + * A.where().findOneAndDelete(conditions, callback) // executes + * A.where().findOneAndDelete(conditions) // returns Query + * A.where().findOneAndDelete(callback) // executes + * A.where().findOneAndDelete() // returns Query + * + * @method findOneAndDelete + * @memberOf Query + * @param {Object} [conditions] + * @param {Object} [options] + * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Function} [callback] optional params are (error, document) + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ - if (schemaType.$isMongooseDocumentArray) { - for (const key of Object.keys(schemaType.schema.paths)) { - const _schemaType = schemaType.schema.paths[key]; - this.subpaths[path + "." + key] = _schemaType; - if (typeof _schemaType === "object" && _schemaType != null) { - _schemaType.$isUnderneathDocArray = true; - } - } - for (const key of Object.keys(schemaType.schema.subpaths)) { - const _schemaType = schemaType.schema.subpaths[key]; - this.subpaths[path + "." + key] = _schemaType; - if (typeof _schemaType === "object" && _schemaType != null) { - _schemaType.$isUnderneathDocArray = true; - } - } - for (const key of Object.keys(schemaType.schema.singleNestedPaths)) { - const _schemaType = schemaType.schema.singleNestedPaths[key]; - this.subpaths[path + "." + key] = _schemaType; - if (typeof _schemaType === "object" && _schemaType != null) { - _schemaType.$isUnderneathDocArray = true; - } - } - } +Query.prototype.findOneAndDelete = function(conditions, options, callback) { + this.op = 'findOneAndDelete'; + this._validateOp(); + this._validate(); + + switch (arguments.length) { + case 2: + if (typeof options === 'function') { + callback = options; + options = {}; + } + break; + case 1: + if (typeof conditions === 'function') { + callback = conditions; + conditions = undefined; + options = undefined; + } + break; + } - return this; - }; + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } - /*! - * ignore - */ - - function gatherChildSchemas(schema) { - const childSchemas = []; - - for (const path of Object.keys(schema.paths)) { - const schematype = schema.paths[path]; - if ( - schematype.$isMongooseDocumentArray || - schematype.$isSingleNested - ) { - childSchemas.push({ - schema: schematype.schema, - model: schematype.caster, - }); - } - } + options && this.setOptions(options); - return childSchemas; - } + if (!callback) { + return this; + } - /*! - * ignore - */ + this.exec(callback); - function _getPath(schema, path, cleanPath) { - if (schema.paths.hasOwnProperty(path)) { - return schema.paths[path]; - } - if (schema.subpaths.hasOwnProperty(cleanPath)) { - return schema.subpaths[cleanPath]; - } - if ( - schema.singleNestedPaths.hasOwnProperty(cleanPath) && - typeof schema.singleNestedPaths[cleanPath] === "object" - ) { - return schema.singleNestedPaths[cleanPath]; - } + return this; +}; - return null; - } +/*! + * Thunk around findOneAndDelete() + * + * @param {Function} [callback] + * @return {Query} this + * @api private + */ +Query.prototype._findOneAndDelete = wrapThunk(function(callback) { + this._castConditions(); - /*! - * ignore - */ + if (this.error() != null) { + callback(this.error()); + return null; + } - function _pathToPositionalSyntax(path) { - if (!/\.\d+/.test(path)) { - return path; - } - return path.replace(/\.\d+\./g, ".$.").replace(/\.\d+$/, ".$"); - } + const filter = this._conditions; + const options = this._optionsForExec(); + let fields = null; - /*! - * ignore - */ + if (this._fields != null) { + options.projection = this._castFields(utils.clone(this._fields)); + fields = options.projection; + if (fields instanceof Error) { + callback(fields); + return null; + } + } - function getMapPath(schema, path) { - if (schema.mapPaths.length === 0) { - return null; - } - for (const val of schema.mapPaths) { - const _path = val.path; - const re = new RegExp( - "^" + _path.replace(/\.\$\*/g, "\\.[^.]+") + "$" - ); - if (re.test(path)) { - return schema.paths[_path]; - } - } + this._collection.collection.findOneAndDelete(filter, options, _wrapThunkCallback(this, (err, res) => { + if (err) { + return callback(err); + } - return null; - } + const doc = res.value; - /** - * The Mongoose instance this schema is associated with - * - * @property base - * @api private - */ + return this._completeOne(doc, res, callback); + })); +}); - Object.defineProperty(Schema.prototype, "base", { - configurable: true, - enumerable: false, - writable: true, - value: null, - }); +/** + * Issues a MongoDB [findOneAndReplace](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/) command. + * + * Finds a matching document, removes it, and passes the found document (if any) + * to the callback. Executes if `callback` is passed. + * + * This function triggers the following middleware. + * + * - `findOneAndReplace()` + * + * ####Available options + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 + * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * + * ####Callback Signature + * function(error, doc) { + * // error: any errors that occurred + * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` + * } + * + * ####Examples + * + * A.where().findOneAndReplace(filter, replacement, options, callback); // executes + * A.where().findOneAndReplace(filter, replacement, options); // return Query + * A.where().findOneAndReplace(filter, replacement, callback); // executes + * A.where().findOneAndReplace(filter); // returns Query + * A.where().findOneAndReplace(callback); // executes + * A.where().findOneAndReplace(); // returns Query + * + * @method findOneAndReplace + * @memberOf Query + * @param {Object} [filter] + * @param {Object} [replacement] + * @param {Object} [options] + * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. + * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). + * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. + * @param {Function} [callback] optional params are (error, document) + * @return {Query} this + * @api public + */ - /** - * Converts type arguments into Mongoose Types. - * - * @param {String} path - * @param {Object} obj constructor - * @api private - */ - - Schema.prototype.interpretAsType = function (path, obj, options) { - if (obj instanceof SchemaType) { - if (obj.path === path) { - return obj; - } - const clone = obj.clone(); - clone.path = path; - return clone; - } - - // If this schema has an associated Mongoose object, use the Mongoose object's - // copy of SchemaTypes re: gh-7158 gh-6933 - const MongooseTypes = - this.base != null ? this.base.Schema.Types : Schema.Types; - - if (!utils.isPOJO(obj) && !(obj instanceof SchemaTypeOptions)) { - const constructorName = utils.getFunctionName(obj.constructor); - if (constructorName !== "Object") { - const oldObj = obj; - obj = {}; - obj[options.typeKey] = oldObj; - } - } +Query.prototype.findOneAndReplace = function(filter, replacement, options, callback) { + this.op = 'findOneAndReplace'; + this._validateOp(); + this._validate(); + + switch (arguments.length) { + case 3: + if (typeof options === 'function') { + callback = options; + options = void 0; + } + break; + case 2: + if (typeof replacement === 'function') { + callback = replacement; + replacement = void 0; + } + break; + case 1: + if (typeof filter === 'function') { + callback = filter; + filter = void 0; + replacement = void 0; + options = void 0; + } + break; + } - // Get the type making sure to allow keys named "type" - // and default to mixed if not specified. - // { type: { type: String, default: 'freshcut' } } - let type = - obj[options.typeKey] && (options.typeKey !== "type" || !obj.type.type) - ? obj[options.typeKey] - : {}; - let name; + if (mquery.canMerge(filter)) { + this.merge(filter); + } - if (utils.isPOJO(type) || type === "mixed") { - return new MongooseTypes.Mixed(path, obj); - } + if (replacement != null) { + if (hasDollarKeys(replacement)) { + throw new Error('The replacement document must not contain atomic operators.'); + } + this._mergeUpdate(replacement); + } - if ( - Array.isArray(type) || - type === Array || - type === "array" || - type === MongooseTypes.Array - ) { - // if it was specified through { type } look for `cast` - let cast = - type === Array || type === "array" ? obj.cast || obj.of : type[0]; - - if (cast && cast.instanceOfSchema) { - if (!(cast instanceof Schema)) { - throw new TypeError( - "Schema for array path `" + - path + - "` is from a different copy of the Mongoose module. Please make sure you're using the same version " + - "of Mongoose everywhere with `npm list mongoose`." - ); - } - return new MongooseTypes.DocumentArray(path, cast, obj); - } - if ( - cast && - cast[options.typeKey] && - cast[options.typeKey].instanceOfSchema - ) { - if (!(cast[options.typeKey] instanceof Schema)) { - throw new TypeError( - "Schema for array path `" + - path + - "` is from a different copy of the Mongoose module. Please make sure you're using the same version " + - "of Mongoose everywhere with `npm list mongoose`." - ); - } - return new MongooseTypes.DocumentArray( - path, - cast[options.typeKey], - obj, - cast - ); - } + options = options || {}; - if (Array.isArray(cast)) { - return new MongooseTypes.Array( - path, - this.interpretAsType(path, cast, options), - obj - ); - } + const returnOriginal = get(this, 'model.base.options.returnOriginal'); + if (options.new == null && options.returnDocument == null && options.returnOriginal == null && returnOriginal != null) { + options.returnOriginal = returnOriginal; + } + this.setOptions(options); + this.setOptions({ overwrite: true }); - if (typeof cast === "string") { - cast = - MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)]; - } else if ( - cast && - (!cast[options.typeKey] || - (options.typeKey === "type" && cast.type.type)) && - utils.isPOJO(cast) - ) { - if (Object.keys(cast).length) { - // The `minimize` and `typeKey` options propagate to child schemas - // declared inline, like `{ arr: [{ val: { $type: String } }] }`. - // See gh-3560 - const childSchemaOptions = { minimize: options.minimize }; - if (options.typeKey) { - childSchemaOptions.typeKey = options.typeKey; - } - // propagate 'strict' option to child schema - if (options.hasOwnProperty("strict")) { - childSchemaOptions.strict = options.strict; - } - if (options.hasOwnProperty("typePojoToMixed")) { - childSchemaOptions.typePojoToMixed = options.typePojoToMixed; - } + if (!callback) { + return this; + } - if (this._userProvidedOptions.hasOwnProperty("_id")) { - childSchemaOptions._id = this._userProvidedOptions._id; - } else if ( - Schema.Types.DocumentArray.defaultOptions && - Schema.Types.DocumentArray.defaultOptions._id != null - ) { - childSchemaOptions._id = - Schema.Types.DocumentArray.defaultOptions._id; - } + this.exec(callback); - const childSchema = new Schema(cast, childSchemaOptions); - childSchema.$implicitlyCreated = true; - return new MongooseTypes.DocumentArray(path, childSchema, obj); - } else { - // Special case: empty object becomes mixed - return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj); - } - } + return this; +}; - if (cast) { - type = - cast[options.typeKey] && - (options.typeKey !== "type" || !cast.type.type) - ? cast[options.typeKey] - : cast; +/*! + * Thunk around findOneAndReplace() + * + * @param {Function} [callback] + * @return {Query} this + * @api private + */ +Query.prototype._findOneAndReplace = wrapThunk(function(callback) { + this._castConditions(); - name = - typeof type === "string" - ? type - : type.schemaName || utils.getFunctionName(type); + if (this.error() != null) { + callback(this.error()); + return null; + } - // For Jest 26+, see #10296 - if (name === "ClockDate") { - name = "Date"; - } + const filter = this._conditions; + const options = this._optionsForExec(); + convertNewToReturnDocument(options); + let fields = null; + + let castedDoc = new this.model(this._update, null, true); + this._update = castedDoc; + + this._applyPaths(); + if (this._fields != null) { + options.projection = this._castFields(utils.clone(this._fields)); + fields = options.projection; + if (fields instanceof Error) { + callback(fields); + return null; + } + } - if (!MongooseTypes.hasOwnProperty(name)) { - throw new TypeError( - "Invalid schema configuration: " + - `\`${name}\` is not a valid type within the array \`${path}\`.` + - "See http://bit.ly/mongoose-schematypes for a list of valid schema types." - ); - } - } + castedDoc.$validate(err => { + if (err != null) { + return callback(err); + } - return new MongooseTypes.Array( - path, - cast || MongooseTypes.Mixed, - obj, - options - ); - } + if (castedDoc.toBSON) { + castedDoc = castedDoc.toBSON(); + } - if (type && type.instanceOfSchema) { - return new MongooseTypes.Embedded(type, path, obj); - } + this._collection.collection.findOneAndReplace(filter, castedDoc, options, _wrapThunkCallback(this, (err, res) => { + if (err) { + return callback(err); + } - if (Buffer.isBuffer(type)) { - name = "Buffer"; - } else if (typeof type === "function" || typeof type === "object") { - name = type.schemaName || utils.getFunctionName(type); - } else { - name = type == null ? "" + type : type.toString(); - } + const doc = res.value; - if (name) { - name = name.charAt(0).toUpperCase() + name.substring(1); - } - // Special case re: gh-7049 because the bson `ObjectID` class' capitalization - // doesn't line up with Mongoose's. - if (name === "ObjectID") { - name = "ObjectId"; - } - // For Jest 26+, see #10296 - if (name === "ClockDate") { - name = "Date"; - } + return this._completeOne(doc, res, callback); + })); + }); +}); - if (MongooseTypes[name] == null) { - throw new TypeError( - `Invalid schema configuration: \`${name}\` is not ` + - `a valid type at path \`${path}\`. See ` + - "http://bit.ly/mongoose-schematypes for a list of valid schema types." - ); - } +/*! + * Support the `new` option as an alternative to `returnOriginal` for backwards + * compat. + */ - return new MongooseTypes[name](path, obj); - }; +function convertNewToReturnDocument(options) { + if ('new' in options) { + options.returnDocument = options['new'] ? 'after' : 'before'; + delete options['new']; + } + if ('returnOriginal' in options) { + options.returnDocument = options['returnOriginal'] ? 'before' : 'after'; + delete options['returnOriginal']; + } + // Temporary since driver 4.0.0-beta does not support `returnDocument` + if (typeof options.returnDocument === 'string') { + options.returnOriginal = options.returnDocument === 'before'; + } +} - /** - * Iterates the schemas paths similar to Array#forEach. - * - * The callback is passed the pathname and the schemaType instance. - * - * ####Example: - * - * const userSchema = new Schema({ name: String, registeredAt: Date }); - * userSchema.eachPath((pathname, schematype) => { - * // Prints twice: - * // name SchemaString { ... } - * // registeredAt SchemaDate { ... } - * console.log(pathname, schematype); - * }); - * - * @param {Function} fn callback function - * @return {Schema} this - * @api public - */ - - Schema.prototype.eachPath = function (fn) { - const keys = Object.keys(this.paths); - const len = keys.length; +/*! + * Thunk around findOneAndRemove() + * + * @param {Function} [callback] + * @return {Query} this + * @api private + */ +Query.prototype._findOneAndRemove = wrapThunk(function(callback) { + if (this.error() != null) { + callback(this.error()); + return; + } - for (let i = 0; i < len; ++i) { - fn(keys[i], this.paths[keys[i]]); - } + this._findAndModify('remove', callback); +}); - return this; - }; +/*! + * Get options from query opts, falling back to the base mongoose object. + */ - /** - * Returns an Array of path strings that are required by this schema. - * - * ####Example: - * const s = new Schema({ - * name: { type: String, required: true }, - * age: { type: String, required: true }, - * notes: String - * }); - * s.requiredPaths(); // [ 'age', 'name' ] - * - * @api public - * @param {Boolean} invalidate refresh the cache - * @return {Array} - */ - - Schema.prototype.requiredPaths = function requiredPaths(invalidate) { - if (this._requiredpaths && !invalidate) { - return this._requiredpaths; - } - - const paths = Object.keys(this.paths); - let i = paths.length; - const ret = []; - - while (i--) { - const path = paths[i]; - if (this.paths[path].isRequired) { - ret.push(path); - } - } - this._requiredpaths = ret; - return this._requiredpaths; - }; +function _getOption(query, option, def) { + const opts = query._optionsForExec(query.model); - /** - * Returns indexes from fields and schema-level indexes (cached). - * - * @api private - * @return {Array} - */ + if (option in opts) { + return opts[option]; + } + if (option in query.model.base.options) { + return query.model.base.options[option]; + } + return def; +} - Schema.prototype.indexedPaths = function indexedPaths() { - if (this._indexedpaths) { - return this._indexedpaths; - } - this._indexedpaths = this.indexes(); - return this._indexedpaths; - }; +/*! + * Override mquery.prototype._findAndModify to provide casting etc. + * + * @param {String} type - either "remove" or "update" + * @param {Function} callback + * @api private + */ - /** - * Returns the pathType of `path` for this schema. - * - * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path. - * - * ####Example: - * const s = new Schema({ name: String, nested: { foo: String } }); - * s.virtual('foo').get(() => 42); - * s.pathType('name'); // "real" - * s.pathType('nested'); // "nested" - * s.pathType('foo'); // "virtual" - * s.pathType('fail'); // "adhocOrUndefined" - * - * @param {String} path - * @return {String} - * @api public - */ - - Schema.prototype.pathType = function (path) { - // Convert to '.$' to check subpaths re: gh-6405 - const cleanPath = _pathToPositionalSyntax(path); - - if (this.paths.hasOwnProperty(path)) { - return "real"; - } - if (this.virtuals.hasOwnProperty(path)) { - return "virtual"; - } - if (this.nested.hasOwnProperty(path)) { - return "nested"; - } - if ( - this.subpaths.hasOwnProperty(cleanPath) || - this.subpaths.hasOwnProperty(path) - ) { - return "real"; - } +Query.prototype._findAndModify = function(type, callback) { + if (typeof callback !== 'function') { + throw new Error('Expected callback in _findAndModify'); + } - const singleNestedPath = - this.singleNestedPaths.hasOwnProperty(cleanPath) || - this.singleNestedPaths.hasOwnProperty(path); - if (singleNestedPath) { - return singleNestedPath === "nested" ? "nested" : "real"; - } + const model = this.model; + const schema = model.schema; + const _this = this; + let fields; - // Look for maps - const mapPath = getMapPath(this, path); - if (mapPath != null) { - return "real"; - } + const castedQuery = castQuery(this); + if (castedQuery instanceof Error) { + return callback(castedQuery); + } - if (/\.\d+\.|\.\d+$/.test(path)) { - return getPositionalPathType(this, path); - } - return "adhocOrUndefined"; - }; + _castArrayFilters(this); - /** - * Returns true iff this path is a child of a mixed schema. - * - * @param {String} path - * @return {Boolean} - * @api private - */ - - Schema.prototype.hasMixedParent = function (path) { - const subpaths = path.split(/\./g); - path = ""; - for (let i = 0; i < subpaths.length; ++i) { - path = i > 0 ? path + "." + subpaths[i] : subpaths[i]; - if ( - this.paths.hasOwnProperty(path) && - this.paths[path] instanceof MongooseTypes.Mixed - ) { - return this.paths[path]; - } - } + const opts = this._optionsForExec(model); - return null; - }; + if ('strict' in opts) { + this._mongooseOptions.strict = opts.strict; + } - /** - * Setup updatedAt and createdAt timestamps to documents if enabled - * - * @param {Boolean|Object} timestamps timestamps options - * @api private - */ - Schema.prototype.setupTimestamp = function (timestamps) { - return setupTimestamps(this, timestamps); - }; + const isOverwriting = this.options.overwrite && !hasDollarKeys(this._update); + if (isOverwriting) { + this._update = new this.model(this._update, null, true); + } - /*! - * ignore. Deprecated re: #6405 - */ + if (type === 'remove') { + opts.remove = true; + } else { + if (!('new' in opts) && !('returnOriginal' in opts) && !('returnDocument' in opts)) { + opts.new = false; + } + if (!('upsert' in opts)) { + opts.upsert = false; + } + if (opts.upsert || opts['new']) { + opts.remove = false; + } - function getPositionalPathType(self, path) { - const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); - if (subpaths.length < 2) { - return self.paths.hasOwnProperty(subpaths[0]) - ? self.paths[subpaths[0]] - : "adhocOrUndefined"; + if (!isOverwriting) { + this._update = castDoc(this, opts.overwrite); + const _opts = Object.assign({}, opts, { + setDefaultsOnInsert: this._mongooseOptions.setDefaultsOnInsert + }); + this._update = setDefaultsOnInsert(this._conditions, schema, this._update, _opts); + if (!this._update || Object.keys(this._update).length === 0) { + if (opts.upsert) { + // still need to do the upsert to empty doc + const doc = utils.clone(castedQuery); + delete doc._id; + this._update = { $set: doc }; + } else { + this._executionStack = null; + this.findOne(callback); + return this; } - - let val = self.path(subpaths[0]); - let isNested = false; - if (!val) { - return "adhocOrUndefined"; + } else if (this._update instanceof Error) { + return callback(this._update); + } else { + // In order to make MongoDB 2.6 happy (see + // https://jira.mongodb.org/browse/SERVER-12266 and related issues) + // if we have an actual update document but $set is empty, junk the $set. + if (this._update.$set && Object.keys(this._update.$set).length === 0) { + delete this._update.$set; } + } + } - const last = subpaths.length - 1; + if (Array.isArray(opts.arrayFilters)) { + opts.arrayFilters = removeUnusedArrayFilters(this._update, opts.arrayFilters); + } + } - for (let i = 1; i < subpaths.length; ++i) { - isNested = false; - const subpath = subpaths[i]; + this._applyPaths(); - if (i === last && val && !/\D/.test(subpath)) { - if (val.$isMongooseDocumentArray) { - val = val.$embeddedSchemaType; - } else if (val instanceof MongooseTypes.Array) { - // StringSchema, NumberSchema, etc - val = val.caster; - } else { - val = undefined; - } - break; - } + if (this._fields) { + fields = utils.clone(this._fields); + opts.projection = this._castFields(fields); + if (opts.projection instanceof Error) { + return callback(opts.projection); + } + } - // ignore if its just a position segment: path.0.subpath - if (!/\D/.test(subpath)) { - // Nested array - if (val instanceof MongooseTypes.Array && i !== last) { - val = val.caster; - } - continue; - } + if (opts.sort) convertSortToArray(opts); - if (!(val && val.schema)) { - val = undefined; - break; - } + const cb = function(err, doc, res) { + if (err) { + return callback(err); + } - const type = val.schema.pathType(subpath); - isNested = type === "nested"; - val = val.schema.path(subpath); - } + _this._completeOne(doc, res, callback); + }; - self.subpaths[path] = val; - if (val) { - return "real"; - } - if (isNested) { - return "nested"; - } - return "adhocOrUndefined"; - } + const runValidators = _getOption(this, 'runValidators', false); - /*! - * ignore - */ + // Bypass mquery + const collection = _this._collection.collection; + convertNewToReturnDocument(opts); - function getPositionalPath(self, path) { - getPositionalPathType(self, path); - return self.subpaths[path]; - } + if (type === 'remove') { + collection.findOneAndDelete(castedQuery, opts, _wrapThunkCallback(_this, function(error, res) { + return cb(error, res ? res.value : res, res); + })); - /** - * Adds a method call to the queue. - * - * ####Example: - * - * schema.methods.print = function() { console.log(this); }; - * schema.queue('print', []); // Print the doc every one is instantiated - * - * const Model = mongoose.model('Test', schema); - * new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }' - * - * @param {String} name name of the document method to call later - * @param {Array} args arguments to pass to the method - * @api public - */ + return this; + } - Schema.prototype.queue = function (name, args) { - this.callQueue.push([name, args]); - return this; - }; + // honors legacy overwrite option for backward compatibility + const updateMethod = isOverwriting ? 'findOneAndReplace' : 'findOneAndUpdate'; - /** - * Defines a pre hook for the model. - * - * ####Example - * - * const toySchema = new Schema({ name: String, created: Date }); - * - * toySchema.pre('save', function(next) { - * if (!this.created) this.created = new Date; - * next(); - * }); - * - * toySchema.pre('validate', function(next) { - * if (this.name !== 'Woody') this.name = 'Woody'; - * next(); - * }); - * - * // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`. - * toySchema.pre(/^find/, function(next) { - * console.log(this.getFilter()); - * }); - * - * // Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`. - * toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) { - * console.log(this.getFilter()); - * }); - * - * toySchema.pre('deleteOne', function() { - * // Runs when you call `Toy.deleteOne()` - * }); - * - * toySchema.pre('deleteOne', { document: true }, function() { - * // Runs when you call `doc.deleteOne()` - * }); - * - * @param {String|RegExp} The method name or regular expression to match method name - * @param {Object} [options] - * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. For example, set `options.document` to `true` to apply this hook to `Document#deleteOne()` rather than `Query#deleteOne()`. - * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware. - * @param {Function} callback - * @api public - */ - - Schema.prototype.pre = function (name) { - if (name instanceof RegExp) { - const remainingArgs = Array.prototype.slice.call(arguments, 1); - for (const fn of hookNames) { - if (name.test(fn)) { - this.pre.apply(this, [fn].concat(remainingArgs)); - } - } - return this; - } - if (Array.isArray(name)) { - const remainingArgs = Array.prototype.slice.call(arguments, 1); - for (const el of name) { - this.pre.apply(this, [el].concat(remainingArgs)); - } - return this; - } - this.s.hooks.pre.apply(this.s.hooks, arguments); - return this; - }; + if (runValidators) { + this.validate(this._update, opts, isOverwriting, error => { + if (error) { + return callback(error); + } + if (this._update && this._update.toBSON) { + this._update = this._update.toBSON(); + } - /** - * Defines a post hook for the document - * - * const schema = new Schema(..); - * schema.post('save', function (doc) { - * console.log('this fired after a document was saved'); - * }); - * - * schema.post('find', function(docs) { - * console.log('this fired after you ran a find query'); - * }); - * - * schema.post(/Many$/, function(res) { - * console.log('this fired after you ran `updateMany()` or `deleteMany()`); - * }); - * - * const Model = mongoose.model('Model', schema); - * - * const m = new Model(..); - * m.save(function(err) { - * console.log('this fires after the `post` hook'); - * }); - * - * m.find(function(err, docs) { - * console.log('this fires after the post find hook'); - * }); - * - * @param {String|RegExp} The method name or regular expression to match method name - * @param {Object} [options] - * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. - * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware. - * @param {Function} fn callback - * @see middleware http://mongoosejs.com/docs/middleware.html - * @see kareem http://npmjs.org/package/kareem - * @api public - */ - - Schema.prototype.post = function (name) { - if (name instanceof RegExp) { - const remainingArgs = Array.prototype.slice.call(arguments, 1); - for (const fn of hookNames) { - if (name.test(fn)) { - this.post.apply(this, [fn].concat(remainingArgs)); - } - } - return this; - } - if (Array.isArray(name)) { - const remainingArgs = Array.prototype.slice.call(arguments, 1); - for (const el of name) { - this.post.apply(this, [el].concat(remainingArgs)); - } - return this; - } - this.s.hooks.post.apply(this.s.hooks, arguments); - return this; - }; + collection[updateMethod](castedQuery, this._update, opts, _wrapThunkCallback(_this, function(error, res) { + return cb(error, res ? res.value : res, res); + })); + }); + } else { + if (this._update && this._update.toBSON) { + this._update = this._update.toBSON(); + } + collection[updateMethod](castedQuery, this._update, opts, _wrapThunkCallback(_this, function(error, res) { + return cb(error, res ? res.value : res, res); + })); + } - /** - * Registers a plugin for this schema. - * - * ####Example: - * - * const s = new Schema({ name: String }); - * s.plugin(schema => console.log(schema.path('name').path)); - * mongoose.model('Test', s); // Prints 'name' - * - * @param {Function} plugin callback - * @param {Object} [opts] - * @see plugins - * @api public - */ - - Schema.prototype.plugin = function (fn, opts) { - if (typeof fn !== "function") { - throw new Error( - "First param to `schema.plugin()` must be a function, " + - 'got "' + - typeof fn + - '"' - ); - } + return this; +}; - if (opts && opts.deduplicate) { - for (const plugin of this.plugins) { - if (plugin.fn === fn) { - return this; - } - } - } - this.plugins.push({ fn: fn, opts: opts }); +/*! + * ignore + */ - fn(this, opts); - return this; - }; +function _completeOneLean(doc, res, opts, callback) { + if (opts.rawResult) { + return callback(null, res); + } + return callback(null, doc); +} - /** - * Adds an instance method to documents constructed from Models compiled from this schema. - * - * ####Example - * - * const schema = kittySchema = new Schema(..); - * - * schema.method('meow', function () { - * console.log('meeeeeoooooooooooow'); - * }) - * - * const Kitty = mongoose.model('Kitty', schema); - * - * const fizz = new Kitty; - * fizz.meow(); // meeeeeooooooooooooow - * - * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. - * - * schema.method({ - * purr: function () {} - * , scratch: function () {} - * }); - * - * // later - * fizz.purr(); - * fizz.scratch(); - * - * NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](/docs/guide.html#methods) - * - * @param {String|Object} method name - * @param {Function} [fn] - * @api public - */ - - Schema.prototype.method = function (name, fn, options) { - if (typeof name !== "string") { - for (const i in name) { - this.methods[i] = name[i]; - this.methodOptions[i] = utils.clone(options); - } - } else { - this.methods[name] = fn; - this.methodOptions[name] = utils.clone(options); - } - return this; - }; +/*! + * Override mquery.prototype._mergeUpdate to handle mongoose objects in + * updates. + * + * @param {Object} doc + * @api private + */ + +Query.prototype._mergeUpdate = function(doc) { + if (doc == null || (typeof doc === 'object' && Object.keys(doc).length === 0)) { + return; + } + + if (!this._update) { + this._update = Array.isArray(doc) ? [] : {}; + } + if (doc instanceof Query) { + if (Array.isArray(this._update)) { + throw new Error('Cannot mix array and object updates'); + } + if (doc._update) { + utils.mergeClone(this._update, doc._update); + } + } else if (Array.isArray(doc)) { + if (!Array.isArray(this._update)) { + throw new Error('Cannot mix array and object updates'); + } + this._update = this._update.concat(doc); + } else { + if (Array.isArray(this._update)) { + throw new Error('Cannot mix array and object updates'); + } + utils.mergeClone(this._update, doc); + } +}; - /** - * Adds static "class" methods to Models compiled from this schema. - * - * ####Example - * - * const schema = new Schema(..); - * // Equivalent to `schema.statics.findByName = function(name) {}`; - * schema.static('findByName', function(name) { - * return this.find({ name: name }); - * }); - * - * const Drink = mongoose.model('Drink', schema); - * await Drink.findByName('LaCroix'); - * - * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics. - * - * @param {String|Object} name - * @param {Function} [fn] - * @api public - * @see Statics /docs/guide.html#statics - */ - - Schema.prototype.static = function (name, fn) { - if (typeof name !== "string") { - for (const i in name) { - this.statics[i] = name[i]; - } - } else { - this.statics[name] = fn; - } - return this; - }; +/*! + * The mongodb driver 1.3.23 only supports the nested array sort + * syntax. We must convert it or sorting findAndModify will not work. + */ - /** - * Defines an index (most likely compound) for this schema. - * - * ####Example - * - * schema.index({ first: 1, last: -1 }) - * - * @param {Object} fields - * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex) - * @param {String | number} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link. - * @api public - */ +function convertSortToArray(opts) { + if (Array.isArray(opts.sort)) { + return; + } + if (!utils.isObject(opts.sort)) { + return; + } - Schema.prototype.index = function (fields, options) { - fields || (fields = {}); - options || (options = {}); + const sort = []; - if (options.expires) { - utils.expires(options); - } + for (const key in opts.sort) { + if (utils.object.hasOwnProperty(opts.sort, key)) { + sort.push([key, opts.sort[key]]); + } + } - this._indexes.push([fields, options]); - return this; - }; + opts.sort = sort; +} - /** - * Sets a schema option. - * - * ####Example - * - * schema.set('strict'); // 'true' by default - * schema.set('strict', false); // Sets 'strict' to false - * schema.set('strict'); // 'false' - * - * @param {String} key option name - * @param {Object} [value] if not passed, the current option value is returned - * @see Schema ./ - * @api public - */ - - Schema.prototype.set = function (key, value, _tags) { - if (arguments.length === 1) { - return this.options[key]; - } - - switch (key) { - case "read": - this.options[key] = readPref(value, _tags); - this._userProvidedOptions[key] = this.options[key]; - break; - case "safe": - setSafe(this.options, value); - this._userProvidedOptions[key] = this.options[key]; - break; - case "timestamps": - this.setupTimestamp(value); - this.options[key] = value; - this._userProvidedOptions[key] = this.options[key]; - break; - case "_id": - this.options[key] = value; - this._userProvidedOptions[key] = this.options[key]; - - if (value && !this.paths["_id"]) { - addAutoId(this); - } else if ( - !value && - this.paths["_id"] != null && - this.paths["_id"].auto - ) { - this.remove("_id"); - } - break; - default: - this.options[key] = value; - this._userProvidedOptions[key] = this.options[key]; - break; - } +/*! + * ignore + */ - return this; - }; +function _updateThunk(op, callback) { + this._castConditions(); - /*! - * ignore - */ - - const safeDeprecationWarning = - "Mongoose: The `safe` option for schemas is " + - "deprecated. Use the `writeConcern` option instead: " + - "http://bit.ly/mongoose-write-concern"; - - const setSafe = util.deprecate(function setSafe(options, value) { - options.safe = value === false ? { w: 0 } : value; - }, safeDeprecationWarning); - - /** - * Gets a schema option. - * - * ####Example: - * - * schema.get('strict'); // true - * schema.set('strict', false); - * schema.get('strict'); // false - * - * @param {String} key option name - * @api public - * @return {Any} the option's value - */ - - Schema.prototype.get = function (key) { - return this.options[key]; - }; + _castArrayFilters(this); - /** - * The allowed index types - * - * @receiver Schema - * @static indexTypes - * @api public - */ + if (this.error() != null) { + callback(this.error()); + return null; + } - const indexTypes = "2d 2dsphere hashed text".split(" "); + callback = _wrapThunkCallback(this, callback); - Object.defineProperty(Schema, "indexTypes", { - get: function () { - return indexTypes; - }, - set: function () { - throw new Error("Cannot overwrite Schema.indexTypes"); - }, - }); + const castedQuery = this._conditions; + const options = this._optionsForExec(this.model); - /** - * Returns a list of indexes that this schema declares, via `schema.index()` or by `index: true` in a path's options. - * Indexes are expressed as an array `[spec, options]`. - * - * ####Example: - * - * const userSchema = new Schema({ - * email: { type: String, required: true, unique: true }, - * registeredAt: { type: Date, index: true } - * }); - * - * // [ [ { email: 1 }, { unique: true, background: true } ], - * // [ { registeredAt: 1 }, { background: true } ] ] - * userSchema.indexes(); - * - * [Plugins](/docs/plugins.html) can use the return value of this function to modify a schema's indexes. - * For example, the below plugin makes every index unique by default. - * - * function myPlugin(schema) { - * for (const index of schema.indexes()) { - * if (index[1].unique === undefined) { - * index[1].unique = true; - * } - * } - * } - * - * @api public - * @return {Array} list of indexes defined in the schema - */ - - Schema.prototype.indexes = function () { - return getIndexes(this); - }; + this._update = utils.clone(this._update, options); + const isOverwriting = this.options.overwrite && !hasDollarKeys(this._update); + if (isOverwriting) { + if (op === 'updateOne' || op === 'updateMany') { + return callback(new MongooseError('The MongoDB server disallows ' + + 'overwriting documents using `' + op + '`. See: ' + + 'https://mongoosejs.com/docs/deprecations.html#update')); + } + this._update = new this.model(this._update, null, true); + } else { + this._update = castDoc(this, options.overwrite); - /** - * Creates a virtual type with the given name. - * - * @param {String} name - * @param {Object} [options] - * @param {String|Model} [options.ref] model name or model instance. Marks this as a [populate virtual](populate.html#populate-virtuals). - * @param {String|Function} [options.localField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information. - * @param {String|Function} [options.foreignField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information. - * @param {Boolean|Function} [options.justOne=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), will be a single doc or `null`. Otherwise, the populate virtual will be an array. - * @param {Boolean} [options.count=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), this populate virtual will contain the number of documents rather than the documents themselves when you `populate()`. - * @param {Function|null} [options.get=null] Adds a [getter](/docs/tutorials/getters-setters.html) to this virtual to transform the populated doc. - * @return {VirtualType} - */ - - Schema.prototype.virtual = function (name, options) { - if ( - name instanceof VirtualType || - getConstructorName(name) === "VirtualType" - ) { - return this.virtual(name.path, name.options); - } + if (this._update instanceof Error) { + callback(this._update); + return null; + } - options = new VirtualOptions(options); + if (this._update == null || Object.keys(this._update).length === 0) { + callback(null, { acknowledged: false }); + return null; + } - if (utils.hasUserDefinedProperty(options, ["ref", "refPath"])) { - if (options.localField == null) { - throw new Error("Reference virtuals require `localField` option"); - } + const _opts = Object.assign({}, options, { + setDefaultsOnInsert: this._mongooseOptions.setDefaultsOnInsert + }); + this._update = setDefaultsOnInsert(this._conditions, this.model.schema, + this._update, _opts); + } - if (options.foreignField == null) { - throw new Error("Reference virtuals require `foreignField` option"); - } + if (Array.isArray(options.arrayFilters)) { + options.arrayFilters = removeUnusedArrayFilters(this._update, options.arrayFilters); + } - this.pre("init", function (obj) { - if (mpath.has(name, obj)) { - const _v = mpath.get(name, obj); - if (!this.$$populatedVirtuals) { - this.$$populatedVirtuals = {}; - } + const runValidators = _getOption(this, 'runValidators', false); + if (runValidators) { + this.validate(this._update, options, isOverwriting, err => { + if (err) { + return callback(err); + } - if (options.justOne || options.count) { - this.$$populatedVirtuals[name] = Array.isArray(_v) ? _v[0] : _v; - } else { - this.$$populatedVirtuals[name] = Array.isArray(_v) - ? _v - : _v == null - ? [] - : [_v]; - } + if (this._update.toBSON) { + this._update = this._update.toBSON(); + } + this._collection[op](castedQuery, this._update, options, callback); + }); + return null; + } - mpath.unset(name, obj); - } - }); + if (this._update.toBSON) { + this._update = this._update.toBSON(); + } - const virtual = this.virtual(name); - virtual.options = options; + this._collection[op](castedQuery, this._update, options, callback); + return null; +} - virtual.set(function (_v) { - if (!this.$$populatedVirtuals) { - this.$$populatedVirtuals = {}; - } +/*! + * Mongoose calls this function internally to validate the query if + * `runValidators` is set + * + * @param {Object} castedDoc the update, after casting + * @param {Object} options the options from `_optionsForExec()` + * @param {Function} callback + * @api private + */ - if (options.justOne || options.count) { - this.$$populatedVirtuals[name] = Array.isArray(_v) ? _v[0] : _v; +Query.prototype.validate = function validate(castedDoc, options, isOverwriting, callback) { + return promiseOrCallback(callback, cb => { + try { + if (isOverwriting) { + castedDoc.$validate(cb); + } else { + updateValidators(this, this.model.schema, castedDoc, options, cb); + } + } catch (err) { + immediate(function() { + cb(err); + }); + } + }); +}; - if (typeof this.$$populatedVirtuals[name] !== "object") { - this.$$populatedVirtuals[name] = options.count ? _v : null; - } - } else { - this.$$populatedVirtuals[name] = Array.isArray(_v) - ? _v - : _v == null - ? [] - : [_v]; - - this.$$populatedVirtuals[name] = this.$$populatedVirtuals[ - name - ].filter(function (doc) { - return doc && typeof doc === "object"; - }); - } - }); +/*! + * Internal thunk for .update() + * + * @param {Function} callback + * @see Model.update #model_Model.update + * @api private + */ +Query.prototype._execUpdate = wrapThunk(function(callback) { + return _updateThunk.call(this, 'update', callback); +}); - if (typeof options.get === "function") { - virtual.get(options.get); - } +/*! + * Internal thunk for .updateMany() + * + * @param {Function} callback + * @see Model.update #model_Model.update + * @api private + */ +Query.prototype._updateMany = wrapThunk(function(callback) { + return _updateThunk.call(this, 'updateMany', callback); +}); - return virtual; - } +/*! + * Internal thunk for .updateOne() + * + * @param {Function} callback + * @see Model.update #model_Model.update + * @api private + */ +Query.prototype._updateOne = wrapThunk(function(callback) { + return _updateThunk.call(this, 'updateOne', callback); +}); - const virtuals = this.virtuals; - const parts = name.split("."); +/*! + * Internal thunk for .replaceOne() + * + * @param {Function} callback + * @see Model.replaceOne #model_Model.replaceOne + * @api private + */ +Query.prototype._replaceOne = wrapThunk(function(callback) { + return _updateThunk.call(this, 'replaceOne', callback); +}); - if (this.pathType(name) === "real") { - throw new Error( - 'Virtual path "' + - name + - '"' + - " conflicts with a real path in the schema" - ); - } +/** + * Declare and/or execute this query as an update() operation. + * + * _All paths passed that are not [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operations will become `$set` ops._ + * + * This function triggers the following middleware. + * + * - `update()` + * + * ####Example + * + * Model.where({ _id: id }).update({ title: 'words' }) + * + * // becomes + * + * Model.where({ _id: id }).update({ $set: { title: 'words' }}) + * + * ####Valid options: + * + * - `upsert` (boolean) whether to create the doc if it doesn't match (false) + * - `multi` (boolean) whether multiple documents should be updated (false) + * - `runValidators` (boolean) if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. + * - `setDefaultsOnInsert` (boolean) `true` by default. If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. + * - `strict` (boolean) overrides the `strict` option for this update + * - `read` + * - `writeConcern` + * + * ####Note + * + * Passing an empty object `{}` as the doc will result in a no-op. The update operation will be ignored and the callback executed without sending the command to MongoDB. + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback, we must first call update() and then execute it by using the `exec()` method. + * + * const q = Model.where({ _id: id }); + * q.update({ $set: { name: 'bob' }}).update(); // not executed + * + * q.update({ $set: { name: 'bob' }}).exec(); // executed + * + * // keys that are not [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) ops become `$set`. + * // this executes the same command as the previous example. + * q.update({ name: 'bob' }).exec(); + * + * // multi updates + * Model.where() + * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) + * + * // more multi updates + * Model.where() + * .setOptions({ multi: true }) + * .update({ $set: { arr: [] }}, callback) + * + * // single update by default + * Model.where({ email: 'address@example.com' }) + * .update({ $inc: { counter: 1 }}, callback) + * + * API summary + * + * update(filter, doc, options, cb) // executes + * update(filter, doc, options) + * update(filter, doc, cb) // executes + * update(filter, doc) + * update(doc, cb) // executes + * update(doc) + * update(cb) // executes + * update(true) // executes + * update() + * + * @param {Object} [filter] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. + * @param {Function} [callback] params are (error, writeOpResult) + * @return {Query} this + * @see Model.update #model_Model.update + * @see Query docs https://mongoosejs.com/docs/queries.html + * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output + * @api public + */ - virtuals[name] = parts.reduce(function (mem, part, i) { - mem[part] || - (mem[part] = - i === parts.length - 1 ? new VirtualType(options, name) : {}); - return mem[part]; - }, this.tree); - - // Workaround for gh-8198: if virtual is under document array, make a fake - // virtual. See gh-8210 - let cur = parts[0]; - for (let i = 0; i < parts.length - 1; ++i) { - if ( - this.paths[cur] != null && - this.paths[cur].$isMongooseDocumentArray - ) { - const remnant = parts.slice(i + 1).join("."); - const v = this.paths[cur].schema.virtual(remnant); - v.get((v, virtual, doc) => { - const parent = doc.__parentArray[arrayParentSymbol]; - const path = cur + "." + doc.__index + "." + remnant; - return parent.get(path); - }); - break; - } +Query.prototype.update = function(conditions, doc, options, callback) { + if (typeof options === 'function') { + // .update(conditions, doc, callback) + callback = options; + options = null; + } else if (typeof doc === 'function') { + // .update(doc, callback); + callback = doc; + doc = conditions; + conditions = {}; + options = null; + } else if (typeof conditions === 'function') { + // .update(callback) + callback = conditions; + conditions = undefined; + doc = undefined; + options = undefined; + } else if (typeof conditions === 'object' && !doc && !options && !callback) { + // .update(doc) + doc = conditions; + conditions = undefined; + options = undefined; + callback = undefined; + } - cur += "." + parts[i + 1]; - } + return _update(this, 'update', conditions, doc, options, callback); +}; - return virtuals[name]; - }; +/** + * Declare and/or execute this query as an updateMany() operation. Same as + * `update()`, except MongoDB will update _all_ documents that match + * `filter` (as opposed to just the first one) regardless of the value of + * the `multi` option. + * + * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')` + * and `post('updateMany')` instead. + * + * ####Example: + * const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true }); + * res.n; // Number of documents matched + * res.nModified; // Number of documents modified + * + * This function triggers the following middleware. + * + * - `updateMany()` + * + * @param {Object} [filter] + * @param {Object|Array} [update] the update command + * @param {Object} [options] + * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. + * @param {Function} [callback] params are (error, writeOpResult) + * @return {Query} this + * @see Model.update #model_Model.update + * @see Query docs https://mongoosejs.com/docs/queries.html + * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output + * @api public + */ - /** - * Returns the virtual type with the given `name`. - * - * @param {String} name - * @return {VirtualType} - */ +Query.prototype.updateMany = function(conditions, doc, options, callback) { + if (typeof options === 'function') { + // .update(conditions, doc, callback) + callback = options; + options = null; + } else if (typeof doc === 'function') { + // .update(doc, callback); + callback = doc; + doc = conditions; + conditions = {}; + options = null; + } else if (typeof conditions === 'function') { + // .update(callback) + callback = conditions; + conditions = undefined; + doc = undefined; + options = undefined; + } else if (typeof conditions === 'object' && !doc && !options && !callback) { + // .update(doc) + doc = conditions; + conditions = undefined; + options = undefined; + callback = undefined; + } - Schema.prototype.virtualpath = function (name) { - return this.virtuals.hasOwnProperty(name) ? this.virtuals[name] : null; - }; + return _update(this, 'updateMany', conditions, doc, options, callback); +}; - /** - * Removes the given `path` (or [`paths`]). - * - * ####Example: - * - * const schema = new Schema({ name: String, age: Number }); - * schema.remove('name'); - * schema.path('name'); // Undefined - * schema.path('age'); // SchemaNumber { ... } - * - * @param {String|Array} path - * @return {Schema} the Schema instance - * @api public - */ - Schema.prototype.remove = function (path) { - if (typeof path === "string") { - path = [path]; - } - if (Array.isArray(path)) { - path.forEach(function (name) { - if (this.path(name) == null && !this.nested[name]) { - return; - } - if (this.nested[name]) { - const allKeys = Object.keys(this.paths).concat( - Object.keys(this.nested) - ); - for (const path of allKeys) { - if (path.startsWith(name + ".")) { - delete this.paths[path]; - delete this.nested[path]; - _deletePath(this, path); - } - } +/** + * Declare and/or execute this query as an updateOne() operation. Same as + * `update()`, except it does not support the `multi` option. + * + * - MongoDB will update _only_ the first document that matches `filter` regardless of the value of the `multi` option. + * - Use `replaceOne()` if you want to overwrite an entire document rather than using [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators like `$set`. + * + * **Note** updateOne will _not_ fire update middleware. Use `pre('updateOne')` + * and `post('updateOne')` instead. + * + * ####Example: + * const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' }); + * res.n; // Number of documents matched + * res.nModified; // Number of documents modified + * + * This function triggers the following middleware. + * + * - `updateOne()` + * + * @param {Object} [filter] + * @param {Object|Array} [update] the update command + * @param {Object} [options] + * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. + * @param {Function} [callback] params are (error, writeOpResult) + * @return {Query} this + * @see Model.update #model_Model.update + * @see Query docs https://mongoosejs.com/docs/queries.html + * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output + * @api public + */ - delete this.nested[name]; - _deletePath(this, name); - return; - } +Query.prototype.updateOne = function(conditions, doc, options, callback) { + if (typeof options === 'function') { + // .update(conditions, doc, callback) + callback = options; + options = null; + } else if (typeof doc === 'function') { + // .update(doc, callback); + callback = doc; + doc = conditions; + conditions = {}; + options = null; + } else if (typeof conditions === 'function') { + // .update(callback) + callback = conditions; + conditions = undefined; + doc = undefined; + options = undefined; + } else if (typeof conditions === 'object' && !doc && !options && !callback) { + // .update(doc) + doc = conditions; + conditions = undefined; + options = undefined; + callback = undefined; + } - delete this.paths[name]; - _deletePath(this, name); - }, this); - } - return this; - }; + return _update(this, 'updateOne', conditions, doc, options, callback); +}; - /*! - * ignore - */ +/** + * Declare and/or execute this query as a replaceOne() operation. Same as + * `update()`, except MongoDB will replace the existing document and will + * not accept any [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators (`$set`, etc.) + * + * **Note** replaceOne will _not_ fire update middleware. Use `pre('replaceOne')` + * and `post('replaceOne')` instead. + * + * ####Example: + * const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' }); + * res.n; // Number of documents matched + * res.nModified; // Number of documents modified + * + * This function triggers the following middleware. + * + * - `replaceOne()` + * + * @param {Object} [filter] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document + * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) + * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. + * @param {Function} [callback] params are (error, writeOpResult) + * @return {Query} this + * @see Model.update #model_Model.update + * @see Query docs https://mongoosejs.com/docs/queries.html + * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ + * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult + * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output + * @api public + */ - function _deletePath(schema, name) { - const pieces = name.split("."); - const last = pieces.pop(); +Query.prototype.replaceOne = function(conditions, doc, options, callback) { + if (typeof options === 'function') { + // .update(conditions, doc, callback) + callback = options; + options = null; + } else if (typeof doc === 'function') { + // .update(doc, callback); + callback = doc; + doc = conditions; + conditions = {}; + options = null; + } else if (typeof conditions === 'function') { + // .update(callback) + callback = conditions; + conditions = undefined; + doc = undefined; + options = undefined; + } else if (typeof conditions === 'object' && !doc && !options && !callback) { + // .update(doc) + doc = conditions; + conditions = undefined; + options = undefined; + callback = undefined; + } - let branch = schema.tree; + this.setOptions({ overwrite: true }); + return _update(this, 'replaceOne', conditions, doc, options, callback); +}; - for (const piece of pieces) { - branch = branch[piece]; - } - - delete branch[last]; - } - - /** - * Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static), - * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions) - * to schema [virtuals](/docs/guide.html#virtuals), - * [statics](/docs/guide.html#statics), and - * [methods](/docs/guide.html#methods). - * - * ####Example: - * - * ```javascript - * const md5 = require('md5'); - * const userSchema = new Schema({ email: String }); - * class UserClass { - * // `gravatarImage` becomes a virtual - * get gravatarImage() { - * const hash = md5(this.email.toLowerCase()); - * return `https://www.gravatar.com/avatar/${hash}`; - * } - * - * // `getProfileUrl()` becomes a document method - * getProfileUrl() { - * return `https://mysite.com/${this.email}`; - * } - * - * // `findByEmail()` becomes a static - * static findByEmail(email) { - * return this.findOne({ email }); - * } - * } - * - * // `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method, - * // and a `findByEmail()` static - * userSchema.loadClass(UserClass); - * ``` - * - * @param {Function} model - * @param {Boolean} [virtualsOnly] if truthy, only pulls virtuals from the class, not methods or statics - */ - Schema.prototype.loadClass = function (model, virtualsOnly) { - if ( - model === Object.prototype || - model === Function.prototype || - model.prototype.hasOwnProperty("$isMongooseModelPrototype") - ) { - return this; - } +/*! + * Internal helper for update, updateMany, updateOne, replaceOne + */ - this.loadClass(Object.getPrototypeOf(model), virtualsOnly); +function _update(query, op, filter, doc, options, callback) { + // make sure we don't send in the whole Document to merge() + query.op = op; + query._validateOp(); + filter = utils.toObject(filter); + doc = doc || {}; + + // strict is an option used in the update checking, make sure it gets set + if (options != null) { + if ('strict' in options) { + query._mongooseOptions.strict = options.strict; + } + } - // Add static methods - if (!virtualsOnly) { - Object.getOwnPropertyNames(model).forEach(function (name) { - if (name.match(/^(length|name|prototype|constructor|__proto__)$/)) { - return; - } - const prop = Object.getOwnPropertyDescriptor(model, name); - if (prop.hasOwnProperty("value")) { - this.static(name, prop.value); - } - }, this); - } + if (!(filter instanceof Query) && + filter != null && + filter.toString() !== '[object Object]') { + query.error(new ObjectParameterError(filter, 'filter', op)); + } else { + query.merge(filter); + } - // Add methods and virtuals - Object.getOwnPropertyNames(model.prototype).forEach(function (name) { - if (name.match(/^(constructor)$/)) { - return; - } - const method = Object.getOwnPropertyDescriptor(model.prototype, name); - if (!virtualsOnly) { - if (typeof method.value === "function") { - this.method(name, method.value); - } - } - if (typeof method.get === "function") { - if (this.virtuals[name]) { - this.virtuals[name].getters = []; - } - this.virtual(name).get(method.get); - } - if (typeof method.set === "function") { - if (this.virtuals[name]) { - this.virtuals[name].setters = []; - } - this.virtual(name).set(method.set); - } - }, this); + if (utils.isObject(options)) { + query.setOptions(options); + } - return this; - }; + query._mergeUpdate(doc); - /*! - * ignore - */ + // Hooks + if (callback) { + query.exec(callback); - Schema.prototype._getSchema = function (path) { - const _this = this; - const pathschema = _this.path(path); - const resultPath = []; - - if (pathschema) { - pathschema.$fullPath = path; - return pathschema; - } - - function search(parts, schema) { - let p = parts.length + 1; - let foundschema; - let trypath; - - while (p--) { - trypath = parts.slice(0, p).join("."); - foundschema = schema.path(trypath); - if (foundschema) { - resultPath.push(trypath); - - if (foundschema.caster) { - // array of Mixed? - if (foundschema.caster instanceof MongooseTypes.Mixed) { - foundschema.caster.$fullPath = resultPath.join("."); - return foundschema.caster; - } + return query; + } - // Now that we found the array, we need to check if there - // are remaining document paths to look up for casting. - // Also we need to handle array.$.path since schema.path - // doesn't work for that. - // If there is no foundschema.schema we are dealing with - // a path like array.$ - if (p !== parts.length) { - if (foundschema.schema) { - let ret; - if (parts[p] === "$" || isArrayFilter(parts[p])) { - if (p + 1 === parts.length) { - // comments.$ - return foundschema; - } - // comments.$.comments.$.title - ret = search(parts.slice(p + 1), foundschema.schema); - if (ret) { - ret.$isUnderneathDocArray = - ret.$isUnderneathDocArray || - !foundschema.schema.$isSingleNested; - } - return ret; - } - // this is the last path of the selector - ret = search(parts.slice(p), foundschema.schema); - if (ret) { - ret.$isUnderneathDocArray = - ret.$isUnderneathDocArray || - !foundschema.schema.$isSingleNested; - } - return ret; - } - } - } else if (foundschema.$isSchemaMap) { - if (p + 1 >= parts.length) { - return foundschema; - } - const ret = search( - parts.slice(p + 1), - foundschema.$__schemaType.schema - ); - return ret; - } + return Query.base[op].call(query, filter, void 0, options, callback); +} - foundschema.$fullPath = resultPath.join("."); +/** + * Runs a function `fn` and treats the return value of `fn` as the new value + * for the query to resolve to. + * + * Any functions you pass to `transform()` will run **after** any post hooks. + * + * ####Example: + * + * const res = await MyModel.findOne().transform(res => { + * // Sets a `loadedAt` property on the doc that tells you the time the + * // document was loaded. + * return res == null ? + * res : + * Object.assign(res, { loadedAt: new Date() }); + * }); + * + * @method transform + * @memberOf Query + * @instance + * @param {Function} fn function to run to transform the query result + * @return {Query} this + */ - return foundschema; - } - } - } +Query.prototype.transform = function(fn) { + this._transforms.push(fn); + return this; +}; - // look for arrays - const parts = path.split("."); - for (let i = 0; i < parts.length; ++i) { - if (parts[i] === "$" || isArrayFilter(parts[i])) { - // Re: gh-5628, because `schema.path()` doesn't take $ into account. - parts[i] = "0"; - } - } - return search(parts, _this); - }; +/** + * Make this query throw an error if no documents match the given `filter`. + * This is handy for integrating with async/await, because `orFail()` saves you + * an extra `if` statement to check if no document was found. + * + * ####Example: + * + * // Throws if no doc returned + * await Model.findOne({ foo: 'bar' }).orFail(); + * + * // Throws if no document was updated + * await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail(); + * + * // Throws "No docs found!" error if no docs match `{ foo: 'bar' }` + * await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!')); + * + * // Throws "Not found" error if no document was found + * await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }). + * orFail(() => Error('Not found')); + * + * @method orFail + * @memberOf Query + * @instance + * @param {Function|Error} [err] optional error to throw if no docs match `filter`. If not specified, `orFail()` will throw a `DocumentNotFoundError` + * @return {Query} this + */ - /*! - * ignore - */ +Query.prototype.orFail = function(err) { + this.transform(res => { + switch (this.op) { + case 'find': + if (res.length === 0) { + throw _orFailError(err, this); + } + break; + case 'findOne': + if (res == null) { + throw _orFailError(err, this); + } + break; + case 'replaceOne': + case 'update': + case 'updateMany': + case 'updateOne': + if (get(res, 'modifiedCount') === 0) { + throw _orFailError(err, this); + } + break; + case 'findOneAndDelete': + case 'findOneAndRemove': + if (get(res, 'lastErrorObject.n') === 0) { + throw _orFailError(err, this); + } + break; + case 'findOneAndUpdate': + case 'findOneAndReplace': + if (get(res, 'lastErrorObject.updatedExisting') === false) { + throw _orFailError(err, this); + } + break; + case 'deleteMany': + case 'deleteOne': + case 'remove': + if (res.deletedCount === 0) { + throw _orFailError(err, this); + } + break; + default: + break; + } - Schema.prototype._getPathType = function (path) { - const _this = this; - const pathschema = _this.path(path); + return res; + }); + return this; +}; - if (pathschema) { - return "real"; - } +/*! + * Get the error to throw for `orFail()` + */ - function search(parts, schema) { - let p = parts.length + 1, - foundschema, - trypath; +function _orFailError(err, query) { + if (typeof err === 'function') { + err = err.call(query); + } - while (p--) { - trypath = parts.slice(0, p).join("."); - foundschema = schema.path(trypath); - if (foundschema) { - if (foundschema.caster) { - // array of Mixed? - if (foundschema.caster instanceof MongooseTypes.Mixed) { - return { schema: foundschema, pathType: "mixed" }; - } + if (err == null) { + err = new DocumentNotFoundError(query.getQuery(), query.model.modelName); + } - // Now that we found the array, we need to check if there - // are remaining document paths to look up for casting. - // Also we need to handle array.$.path since schema.path - // doesn't work for that. - // If there is no foundschema.schema we are dealing with - // a path like array.$ - if (p !== parts.length && foundschema.schema) { - if (parts[p] === "$" || isArrayFilter(parts[p])) { - if (p === parts.length - 1) { - return { schema: foundschema, pathType: "nested" }; - } - // comments.$.comments.$.title - return search(parts.slice(p + 1), foundschema.schema); - } - // this is the last path of the selector - return search(parts.slice(p), foundschema.schema); - } - return { - schema: foundschema, - pathType: foundschema.$isSingleNested ? "nested" : "array", - }; - } - return { schema: foundschema, pathType: "real" }; - } else if (p === parts.length && schema.nested[trypath]) { - return { schema: schema, pathType: "nested" }; - } - } - return { schema: foundschema || schema, pathType: "undefined" }; - } + return err; +} - // look for arrays - return search(path.split("."), _this); - }; +/** + * Executes the query + * + * ####Examples: + * + * const promise = query.exec(); + * const promise = query.exec('update'); + * + * query.exec(callback); + * query.exec('find', callback); + * + * @param {String|Function} [operation] + * @param {Function} [callback] optional params depend on the function being called + * @return {Promise} + * @api public + */ - /*! - * ignore - */ - - function isArrayFilter(piece) { - return piece.startsWith("$[") && piece.endsWith("]"); - } - - /*! - * Module exports. - */ - - module.exports = exports = Schema; - - // require down here because of reference issues - - /** - * The various built-in Mongoose Schema Types. - * - * ####Example: - * - * const mongoose = require('mongoose'); - * const ObjectId = mongoose.Schema.Types.ObjectId; - * - * ####Types: - * - * - [String](/docs/schematypes.html#strings) - * - [Number](/docs/schematypes.html#numbers) - * - [Boolean](/docs/schematypes.html#booleans) | Bool - * - [Array](/docs/schematypes.html#arrays) - * - [Buffer](/docs/schematypes.html#buffers) - * - [Date](/docs/schematypes.html#dates) - * - [ObjectId](/docs/schematypes.html#objectids) | Oid - * - [Mixed](/docs/schematypes.html#mixed) - * - * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema. - * - * const Mixed = mongoose.Schema.Types.Mixed; - * new mongoose.Schema({ _user: Mixed }) - * - * @api public - */ - - Schema.Types = MongooseTypes = __nccwpck_require__(2987); - - /*! - * ignore - */ - - exports.ObjectId = MongooseTypes.ObjectId; - - /***/ - }, +Query.prototype.exec = function exec(op, callback) { + const _this = this; + // Ensure that `exec()` is the first thing that shows up in + // the stack when cast errors happen. + const castError = new CastError(); + + if (typeof op === 'function') { + callback = op; + op = null; + } else if (typeof op === 'string') { + this.op = op; + } - /***/ 4257: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const CastError = __nccwpck_require__(2798); - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const ObjectExpectedError = __nccwpck_require__(2293); - const SchemaSingleNestedOptions = __nccwpck_require__(5815); - const SchemaType = __nccwpck_require__(5660); - const $exists = __nccwpck_require__(1426); - const castToNumber = __nccwpck_require__(9446) /* .castToNumber */.W; - const discriminator = __nccwpck_require__(1462); - const geospatial = __nccwpck_require__(5061); - const get = __nccwpck_require__(8730); - const getConstructor = __nccwpck_require__(1449); - const handleIdOption = __nccwpck_require__(8965); - const internalToObjectOptions = - __nccwpck_require__(5684) /* .internalToObjectOptions */.h; - - let Subdocument; - - module.exports = SingleNestedPath; - - /** - * Single nested subdocument SchemaType constructor. - * - * @param {Schema} schema - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - - function SingleNestedPath(schema, path, options) { - schema = handleIdOption(schema, options); - - this.caster = _createConstructor(schema); - this.caster.path = path; - this.caster.prototype.$basePath = path; - this.schema = schema; - this.$isSingleNested = true; - SchemaType.call(this, path, options, "Embedded"); - } - - /*! - * ignore - */ - - SingleNestedPath.prototype = Object.create(SchemaType.prototype); - SingleNestedPath.prototype.constructor = SingleNestedPath; - SingleNestedPath.prototype.OptionsConstructor = SchemaSingleNestedOptions; - - /*! - * ignore - */ - - function _createConstructor(schema, baseClass) { - // lazy load - Subdocument || (Subdocument = __nccwpck_require__(7302)); - - const _embedded = function SingleNested(value, path, parent) { - const _this = this; - - this.$__parent = parent; - Subdocument.apply(this, arguments); - - this.$session(this.ownerDocument().$session()); - - if (parent) { - parent.on("save", function () { - _this.emit("save", _this); - _this.constructor.emit("save", _this); - }); + if (this.op == null) { + throw new Error('Query must have `op` before executing'); + } + this._validateOp(); - parent.on("isNew", function (val) { - _this.isNew = val; - _this.emit("isNew", val); - _this.constructor.emit("isNew", val); - }); - } - }; + callback = this.model.$handleCallbackError(callback); - const proto = - baseClass != null ? baseClass.prototype : Subdocument.prototype; - _embedded.prototype = Object.create(proto); - _embedded.prototype.$__setSchema(schema); - _embedded.prototype.constructor = _embedded; - _embedded.schema = schema; - _embedded.$isSingleNested = true; - _embedded.events = new EventEmitter(); - _embedded.prototype.toBSON = function () { - return this.toObject(internalToObjectOptions); - }; + return promiseOrCallback(callback, (cb) => { + cb = this.model.$wrapCallback(cb); - // apply methods - for (const i in schema.methods) { - _embedded.prototype[i] = schema.methods[i]; - } + if (!_this.op) { + cb(); + return; + } - // apply statics - for (const i in schema.statics) { - _embedded[i] = schema.statics[i]; + this._hooks.execPre('exec', this, [], (error) => { + if (error != null) { + return cb(_cleanCastErrorStack(castError, error)); + } + let thunk = '_' + this.op; + if (this.op === 'update') { + thunk = '_execUpdate'; + } else if (this.op === 'distinct') { + thunk = '__distinct'; + } + this[thunk].call(this, (error, res) => { + if (error) { + return cb(_cleanCastErrorStack(castError, error)); } - for (const i in EventEmitter.prototype) { - _embedded[i] = EventEmitter.prototype[i]; - } + this._hooks.execPost('exec', this, [], {}, (error) => { + if (error) { + return cb(_cleanCastErrorStack(castError, error)); + } - return _embedded; - } + cb(null, res); + }); + }); + }); + }, this.model.events); +}; - /*! - * Special case for when users use a common location schema to represent - * locations for use with $geoWithin. - * https://docs.mongodb.org/manual/reference/operator/query/geoWithin/ - * - * @param {Object} val - * @api private - */ +/*! + * ignore + */ - SingleNestedPath.prototype.$conditionalHandlers.$geoWithin = - function handle$geoWithin(val) { - return { $geometry: this.castForQuery(val.$geometry) }; - }; +function _cleanCastErrorStack(castError, error) { + if (error instanceof CastError) { + castError.copy(error); + return castError; + } - /*! - * ignore - */ - - SingleNestedPath.prototype.$conditionalHandlers.$near = - SingleNestedPath.prototype.$conditionalHandlers.$nearSphere = - geospatial.cast$near; - - SingleNestedPath.prototype.$conditionalHandlers.$within = - SingleNestedPath.prototype.$conditionalHandlers.$geoWithin = - geospatial.cast$within; - - SingleNestedPath.prototype.$conditionalHandlers.$geoIntersects = - geospatial.cast$geoIntersects; - - SingleNestedPath.prototype.$conditionalHandlers.$minDistance = - castToNumber; - SingleNestedPath.prototype.$conditionalHandlers.$maxDistance = - castToNumber; - - SingleNestedPath.prototype.$conditionalHandlers.$exists = $exists; - - /** - * Casts contents - * - * @param {Object} value - * @api private - */ - - SingleNestedPath.prototype.cast = function ( - val, - doc, - init, - priorVal, - options - ) { - if (val && val.$isSingleNested && val.parent === doc) { - return val; - } + return error; +} - if (val != null && (typeof val !== "object" || Array.isArray(val))) { - throw new ObjectExpectedError(this.path, val); - } +/*! + * ignore + */ - const Constructor = getConstructor(this.caster, val); +function _wrapThunkCallback(query, cb) { + return function(error, res) { + if (error != null) { + return cb(error); + } - let subdoc; + for (const fn of query._transforms) { + try { + res = fn(res); + } catch (error) { + return cb(error); + } + } - // Only pull relevant selected paths and pull out the base path - const parentSelected = get(doc, "$__.selected", {}); - const path = this.path; - const selected = Object.keys(parentSelected).reduce((obj, key) => { - if (key.startsWith(path + ".")) { - obj[key.substr(path.length + 1)] = parentSelected[key]; - } - return obj; - }, {}); - options = Object.assign({}, options, { priorDoc: priorVal }); - if (init) { - subdoc = new Constructor(void 0, selected, doc); - subdoc.init(val); - } else { - if (Object.keys(val).length === 0) { - return new Constructor({}, selected, doc, undefined, options); - } + return cb(null, res); + }; +} - return new Constructor(val, selected, doc, undefined, options); - } +/** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + * + * More about [`then()` in JavaScript](https://masteringjs.io/tutorials/fundamentals/then). + * + * @param {Function} [resolve] + * @param {Function} [reject] + * @return {Promise} + * @api public + */ - return subdoc; - }; +Query.prototype.then = function(resolve, reject) { + return this.exec().then(resolve, reject); +}; - /** - * Casts contents for query - * - * @param {string} [$conditional] optional query operator (like `$eq` or `$in`) - * @param {any} value - * @api private - */ - - SingleNestedPath.prototype.castForQuery = function ( - $conditional, - val, - options - ) { - let handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) { - throw new Error("Can't use " + $conditional); - } - return handler.call(this, val); - } - val = $conditional; - if (val == null) { - return val; - } +/** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + * Like `.then()`, but only takes a rejection handler. + * + * More about [Promise `catch()` in JavaScript](https://masteringjs.io/tutorials/fundamentals/catch). + * + * @param {Function} [reject] + * @return {Promise} + * @api public + */ - if (this.options.runSetters) { - val = this._applySetters(val); - } +Query.prototype.catch = function(reject) { + return this.exec().then(null, reject); +}; - const Constructor = getConstructor(this.caster, val); - const overrideStrict = - options != null && options.strict != null ? options.strict : void 0; +/** + * Add pre [middleware](/docs/middleware.html) to this query instance. Doesn't affect + * other queries. + * + * ####Example: + * + * const q1 = Question.find({ answer: 42 }); + * q1.pre(function middleware() { + * console.log(this.getFilter()); + * }); + * await q1.exec(); // Prints "{ answer: 42 }" + * + * // Doesn't print anything, because `middleware()` is only + * // registered on `q1`. + * await Question.find({ answer: 42 }); + * + * @param {Function} fn + * @return {Promise} + * @api public + */ - try { - val = new Constructor(val, overrideStrict); - } catch (error) { - // Make sure we always wrap in a CastError (gh-6803) - if (!(error instanceof CastError)) { - throw new CastError("Embedded", val, this.path, error, this); - } - throw error; - } - return val; - }; +Query.prototype.pre = function(fn) { + this._hooks.pre('exec', fn); + return this; +}; - /** - * Async validation on this single nested doc. - * - * @api private - */ - - SingleNestedPath.prototype.doValidate = function ( - value, - fn, - scope, - options - ) { - const Constructor = getConstructor(this.caster, value); - - if (options && options.skipSchemaValidators) { - if (!(value instanceof Constructor)) { - value = new Constructor(value, null, scope); - } - return value.validate(fn); - } +/** + * Add post [middleware](/docs/middleware.html) to this query instance. Doesn't affect + * other queries. + * + * ####Example: + * + * const q1 = Question.find({ answer: 42 }); + * q1.post(function middleware() { + * console.log(this.getFilter()); + * }); + * await q1.exec(); // Prints "{ answer: 42 }" + * + * // Doesn't print anything, because `middleware()` is only + * // registered on `q1`. + * await Question.find({ answer: 42 }); + * + * @param {Function} fn + * @return {Promise} + * @api public + */ - SchemaType.prototype.doValidate.call( - this, - value, - function (error) { - if (error) { - return fn(error); - } - if (!value) { - return fn(null); - } +Query.prototype.post = function(fn) { + this._hooks.post('exec', fn); + return this; +}; - value.validate(fn); - }, - scope, - options - ); - }; +/*! + * Casts obj for an update command. + * + * @param {Object} obj + * @return {Object} obj after casting its values + * @api private + */ - /** - * Synchronously validate this single nested doc - * - * @api private - */ - - SingleNestedPath.prototype.doValidateSync = function ( - value, - scope, - options - ) { - if (!options || !options.skipSchemaValidators) { - const schemaTypeError = SchemaType.prototype.doValidateSync.call( - this, - value, - scope - ); - if (schemaTypeError) { - return schemaTypeError; - } - } - if (!value) { - return; - } - return value.validateSync(); - }; +Query.prototype._castUpdate = function _castUpdate(obj, overwrite) { + let schema = this.schema; + + const discriminatorKey = schema.options.discriminatorKey; + const baseSchema = schema._baseSchema ? schema._baseSchema : schema; + if (this._mongooseOptions.overwriteDiscriminatorKey && + obj[discriminatorKey] != null && + baseSchema.discriminators) { + const _schema = baseSchema.discriminators[obj[discriminatorKey]]; + if (_schema != null) { + schema = _schema; + } + } - /** - * Adds a discriminator to this single nested subdocument. - * - * ####Example: - * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' }); - * const schema = Schema({ shape: shapeSchema }); - * - * const singleNestedPath = parentSchema.path('shape'); - * singleNestedPath.discriminator('Circle', Schema({ radius: Number })); - * - * @param {String} name - * @param {Schema} schema fields to add to the schema for instances of this sub-class - * @param {String} [value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. - * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model - * @see discriminators /docs/discriminators.html - * @api public - */ - - SingleNestedPath.prototype.discriminator = function ( - name, - schema, - value - ) { - schema = discriminator(this.caster, name, schema, value); - - this.caster.discriminators[name] = _createConstructor( - schema, - this.caster - ); + let upsert; + if ('upsert' in this.options) { + upsert = this.options.upsert; + } - return this.caster.discriminators[name]; - }; + const filter = this._conditions; + if (schema != null && + utils.hasUserDefinedProperty(filter, schema.options.discriminatorKey) && + typeof filter[schema.options.discriminatorKey] !== 'object' && + schema.discriminators != null) { + const discriminatorValue = filter[schema.options.discriminatorKey]; + const byValue = getDiscriminatorByValue(this.model.discriminators, discriminatorValue); + schema = schema.discriminators[discriminatorValue] || + (byValue && byValue.schema) || + schema; + } - /** - * Sets a default option for all SingleNestedPath instances. - * - * ####Example: - * - * // Make all numbers have option `min` equal to 0. - * mongoose.Schema.Embedded.set('required', true); - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - - SingleNestedPath.defaultOptions = {}; - - SingleNestedPath.set = SchemaType.set; - - /*! - * ignore - */ - - SingleNestedPath.prototype.clone = function () { - const options = Object.assign({}, this.options); - const schematype = new this.constructor( - this.schema, - this.path, - options - ); - schematype.validators = this.validators.slice(); - if (this.requiredValidator !== undefined) { - schematype.requiredValidator = this.requiredValidator; - } - schematype.caster.discriminators = Object.assign( - {}, - this.caster.discriminators - ); - return schematype; - }; + return castUpdate(schema, obj, { + overwrite: overwrite, + strict: this._mongooseOptions.strict, + upsert: upsert, + arrayFilters: this.options.arrayFilters + }, this, this._conditions); +}; + +/*! + * castQuery + * @api private + */ - /***/ - }, +function castQuery(query) { + try { + return query.cast(query.model); + } catch (err) { + return err; + } +} - /***/ 6090: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const $exists = __nccwpck_require__(1426); - const $type = __nccwpck_require__(4093); - const MongooseError = __nccwpck_require__(5953); - const SchemaArrayOptions = __nccwpck_require__(7391); - const SchemaType = __nccwpck_require__(5660); - const CastError = SchemaType.CastError; - const Mixed = __nccwpck_require__(7495); - const arrayDepth = __nccwpck_require__(8906); - const cast = __nccwpck_require__(8874); - const get = __nccwpck_require__(8730); - const isOperator = __nccwpck_require__(3342); - const util = __nccwpck_require__(1669); - const utils = __nccwpck_require__(9232); - const castToNumber = __nccwpck_require__(9446) /* .castToNumber */.W; - const geospatial = __nccwpck_require__(5061); - const getDiscriminatorByValue = __nccwpck_require__(8689); - - let MongooseArray; - let EmbeddedDoc; - - const isNestedArraySymbol = Symbol("mongoose#isNestedArray"); - const emptyOpts = Object.freeze({}); - - /** - * Array SchemaType constructor - * - * @param {String} key - * @param {SchemaType} cast - * @param {Object} options - * @inherits SchemaType - * @api public - */ - - function SchemaArray(key, cast, options, schemaOptions) { - // lazy load - EmbeddedDoc || (EmbeddedDoc = __nccwpck_require__(3000).Embedded); - - let typeKey = "type"; - if (schemaOptions && schemaOptions.typeKey) { - typeKey = schemaOptions.typeKey; - } - this.schemaOptions = schemaOptions; - - if (cast) { - let castOptions = {}; - - if (utils.isPOJO(cast)) { - if (cast[typeKey]) { - // support { type: Woot } - castOptions = utils.clone(cast); // do not alter user arguments - delete castOptions[typeKey]; - cast = cast[typeKey]; - } else { - cast = Mixed; - } - } +/*! + * castDoc + * @api private + */ - if ( - options != null && - options.ref != null && - castOptions.ref == null - ) { - castOptions.ref = options.ref; - } +function castDoc(query, overwrite) { + try { + return query._castUpdate(query._update, overwrite); + } catch (err) { + return err; + } +} - if (cast === Object) { - cast = Mixed; - } +/** + * Specifies paths which should be populated with other documents. + * + * ####Example: + * + * let book = await Book.findOne().populate('authors'); + * book.title; // 'Node.js in Action' + * book.authors[0].name; // 'TJ Holowaychuk' + * book.authors[1].name; // 'Nathan Rajlich' + * + * let books = await Book.find().populate({ + * path: 'authors', + * // `match` and `sort` apply to the Author model, + * // not the Book model. These options do not affect + * // which documents are in `books`, just the order and + * // contents of each book document's `authors`. + * match: { name: new RegExp('.*h.*', 'i') }, + * sort: { name: -1 } + * }); + * books[0].title; // 'Node.js in Action' + * // Each book's `authors` are sorted by name, descending. + * books[0].authors[0].name; // 'TJ Holowaychuk' + * books[0].authors[1].name; // 'Marc Harter' + * + * books[1].title; // 'Professional AngularJS' + * // Empty array, no authors' name has the letter 'h' + * books[1].authors; // [] + * + * Paths are populated after the query executes and a response is received. A + * separate query is then executed for each path specified for population. After + * a response for each query has also been returned, the results are passed to + * the callback. + * + * @param {Object|String} path either the path to populate or an object specifying all parameters + * @param {Object|String} [select] Field selection for the population query + * @param {Model} [model] The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field. + * @param {Object} [match] Conditions for the population query + * @param {Object} [options] Options for the population query (sort, etc) + * @param {String} [options.path=null] The path to populate. + * @param {boolean} [options.retainNullValues=false] by default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries. + * @param {boolean} [options.getters=false] if true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options). + * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them. + * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object. + * @param {Function} [options.transform=null] Function that Mongoose will call on every populated document that allows you to transform the populated document. + * @param {Object} [options.options=null] Additional options like `limit` and `lean`. + * @see population ./populate.html + * @see Query#select #query_Query-select + * @see Model.populate #model_Model.populate + * @return {Query} this + * @api public + */ - // support { type: 'String' } - const name = - typeof cast === "string" ? cast : utils.getFunctionName(cast); +Query.prototype.populate = function() { + // Bail when given no truthy arguments + if (!Array.from(arguments).some(Boolean)) { + return this; + } - const Types = __nccwpck_require__(2987); - const caster = Types.hasOwnProperty(name) ? Types[name] : cast; + const res = utils.populate.apply(null, arguments); - this.casterConstructor = caster; + // Propagate readConcern and readPreference and lean from parent query, + // unless one already specified + if (this.options != null) { + const readConcern = this.options.readConcern; + const readPref = this.options.readPreference; - if (this.casterConstructor instanceof SchemaArray) { - this.casterConstructor[isNestedArraySymbol] = true; - } + for (const populateOptions of res) { + if (readConcern != null && get(populateOptions, 'options.readConcern') == null) { + populateOptions.options = populateOptions.options || {}; + populateOptions.options.readConcern = readConcern; + } + if (readPref != null && get(populateOptions, 'options.readPreference') == null) { + populateOptions.options = populateOptions.options || {}; + populateOptions.options.readPreference = readPref; + } + } + } - if ( - typeof caster === "function" && - !caster.$isArraySubdocument && - !caster.$isSchemaMap - ) { - const path = this.caster instanceof EmbeddedDoc ? null : key; - this.caster = new caster(path, castOptions); - } else { - this.caster = caster; - if (!(this.caster instanceof EmbeddedDoc)) { - this.caster.path = key; - } - } + const opts = this._mongooseOptions; - this.$embeddedSchemaType = this.caster; - } + if (opts.lean != null) { + const lean = opts.lean; + for (const populateOptions of res) { + if (get(populateOptions, 'options.lean') == null) { + populateOptions.options = populateOptions.options || {}; + populateOptions.options.lean = lean; + } + } + } - this.$isMongooseArray = true; + if (!utils.isObject(opts.populate)) { + opts.populate = {}; + } - SchemaType.call(this, key, options, "Array"); + const pop = opts.populate; - let defaultArr; - let fn; + for (const populateOptions of res) { + const path = populateOptions.path; + if (pop[path] && pop[path].populate && populateOptions.populate) { + populateOptions.populate = pop[path].populate.concat(populateOptions.populate); + } - if (this.defaultValue != null) { - defaultArr = this.defaultValue; - fn = typeof defaultArr === "function"; - } + pop[populateOptions.path] = populateOptions; + } + return this; +}; - if (!("defaultValue" in this) || this.defaultValue !== void 0) { - const defaultFn = function () { - let arr = []; - if (fn) { - arr = defaultArr.call(this); - } else if (defaultArr != null) { - arr = arr.concat(defaultArr); - } - // Leave it up to `cast()` to convert the array - return arr; - }; - defaultFn.$runBeforeSetters = !fn; - this.default(defaultFn); - } - } - - /** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ - SchemaArray.schemaName = "Array"; - - /** - * Options for all arrays. - * - * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting. - * - * @static options - * @api public - */ - - SchemaArray.options = { castNonArrays: true }; - - /*! - * ignore - */ - - SchemaArray.defaultOptions = {}; - - /** - * Sets a default option for all Array instances. - * - * ####Example: - * - * // Make all Array instances have `required` of true by default. - * mongoose.Schema.Array.set('required', true); - * - * const User = mongoose.model('User', new Schema({ test: Array })); - * new User({ }).validateSync().errors.test.message; // Path `test` is required. - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @api public - */ - SchemaArray.set = SchemaType.set; - - /*! - * Inherits from SchemaType. - */ - SchemaArray.prototype = Object.create(SchemaType.prototype); - SchemaArray.prototype.constructor = SchemaArray; - SchemaArray.prototype.OptionsConstructor = SchemaArrayOptions; - - /*! - * ignore - */ - - SchemaArray._checkRequired = SchemaType.prototype.checkRequired; - - /** - * Override the function the required validator uses to check whether an array - * passes the `required` check. - * - * ####Example: - * - * // Require non-empty array to pass `required` check - * mongoose.Schema.Types.Array.checkRequired(v => Array.isArray(v) && v.length); - * - * const M = mongoose.model({ arr: { type: Array, required: true } }); - * new M({ arr: [] }).validateSync(); // `null`, validation fails! - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @api public - */ - - SchemaArray.checkRequired = SchemaType.checkRequired; - - /** - * Check if the given value satisfies the `required` validator. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - - SchemaArray.prototype.checkRequired = function checkRequired(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - - // `require('util').inherits()` does **not** copy static properties, and - // plugins like mongoose-float use `inherits()` for pre-ES6. - const _checkRequired = - typeof this.constructor.checkRequired == "function" - ? this.constructor.checkRequired() - : SchemaArray.checkRequired(); - - return _checkRequired(value); - }; +/** + * Gets a list of paths to be populated by this query + * + * ####Example: + * bookSchema.pre('findOne', function() { + * let keys = this.getPopulatedPaths(); // ['author'] + * }); + * ... + * Book.findOne({}).populate('author'); + * + * ####Example: + * // Deep populate + * const q = L1.find().populate({ + * path: 'level2', + * populate: { path: 'level3' } + * }); + * q.getPopulatedPaths(); // ['level2', 'level2.level3'] + * + * @return {Array} an array of strings representing populated paths + * @api public + */ - /** - * Adds an enum validator if this is an array of strings or numbers. Equivalent to - * `SchemaString.prototype.enum()` or `SchemaNumber.prototype.enum()` - * - * @param {String|Object} [args...] enumeration values - * @return {SchemaArray} this - */ +Query.prototype.getPopulatedPaths = function getPopulatedPaths() { + const obj = this._mongooseOptions.populate || {}; + const ret = Object.keys(obj); + for (const path of Object.keys(obj)) { + const pop = obj[path]; + if (!Array.isArray(pop.populate)) { + continue; + } + _getPopulatedPaths(ret, pop.populate, path + '.'); + } + return ret; +}; - SchemaArray.prototype.enum = function () { - let arr = this; - while (true) { - const instance = get(arr, "caster.instance"); - if (instance === "Array") { - arr = arr.caster; - continue; - } - if (instance !== "String" && instance !== "Number") { - throw new Error( - "`enum` can only be set on an array of strings or numbers " + - ", not " + - instance - ); - } - break; - } +/*! + * ignore + */ - let enumArray = arguments; - if (!Array.isArray(arguments) && utils.isObject(arguments)) { - enumArray = utils.object.vals(enumArray); - } +function _getPopulatedPaths(list, arr, prefix) { + for (const pop of arr) { + list.push(prefix + pop.path); + if (!Array.isArray(pop.populate)) { + continue; + } + _getPopulatedPaths(list, pop.populate, prefix + pop.path + '.'); + } +} - arr.caster.enum.apply(arr.caster, enumArray); - return this; - }; +/** + * Casts this query to the schema of `model` + * + * ####Note + * + * If `obj` is present, it is cast instead of this query. + * + * @param {Model} [model] the model to cast to. If not set, defaults to `this.model` + * @param {Object} [obj] + * @return {Object} + * @api public + */ - /** - * Overrides the getters application for the population special-case - * - * @param {Object} value - * @param {Object} scope - * @api private - */ - - SchemaArray.prototype.applyGetters = function (value, scope) { - if (scope != null && scope.$__ != null && scope.populated(this.path)) { - // means the object id was populated - return value; - } +Query.prototype.cast = function(model, obj) { + obj || (obj = this._conditions); - const ret = SchemaType.prototype.applyGetters.call(this, value, scope); - if (Array.isArray(ret)) { - const len = ret.length; - for (let i = 0; i < len; ++i) { - ret[i] = this.caster.applyGetters(ret[i], scope); - } - } - return ret; - }; + model = model || this.model; + const discriminatorKey = model.schema.options.discriminatorKey; + if (obj != null && + obj.hasOwnProperty(discriminatorKey)) { + model = getDiscriminatorByValue(model.discriminators, obj[discriminatorKey]) || model; + } - SchemaArray.prototype._applySetters = function ( - value, - scope, - init, - priorVal - ) { - if ( - this.casterConstructor.$isMongooseArray && - SchemaArray.options.castNonArrays && - !this[isNestedArraySymbol] - ) { - // Check nesting levels and wrap in array if necessary - let depth = 0; - let arr = this; - while ( - arr != null && - arr.$isMongooseArray && - !arr.$isMongooseDocumentArray - ) { - ++depth; - arr = arr.casterConstructor; - } + try { + return cast(model.schema, obj, { + upsert: this.options && this.options.upsert, + strict: (this.options && 'strict' in this.options) ? + this.options.strict : + get(model, 'schema.options.strict', null), + strictQuery: (this.options && 'strictQuery' in this.options) ? + this.options.strictQuery : + (this.options && 'strict' in this.options) ? + this.options.strict : + get(model, 'schema.options.strictQuery', null) + }, this); + } catch (err) { + // CastError, assign model + if (typeof err.setModel === 'function') { + err.setModel(model); + } + throw err; + } +}; - // No need to wrap empty arrays - if (value != null && value.length > 0) { - const valueDepth = arrayDepth(value); - if ( - valueDepth.min === valueDepth.max && - valueDepth.max < depth && - valueDepth.containsNonArrayItem - ) { - for (let i = valueDepth.max; i < depth; ++i) { - value = [value]; - } - } - } - } +/** + * Casts selected field arguments for field selection with mongo 2.2 + * + * query.select({ ids: { $elemMatch: { $in: [hexString] }}) + * + * @param {Object} fields + * @see https://github.com/Automattic/mongoose/issues/1091 + * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/ + * @api private + */ - return SchemaType.prototype._applySetters.call( - this, - value, - scope, - init, - priorVal - ); - }; +Query.prototype._castFields = function _castFields(fields) { + let selected, + elemMatchKeys, + keys, + key, + out, + i; + + if (fields) { + keys = Object.keys(fields); + elemMatchKeys = []; + i = keys.length; + + // collect $elemMatch args + while (i--) { + key = keys[i]; + if (fields[key].$elemMatch) { + selected || (selected = {}); + selected[key] = fields[key]; + elemMatchKeys.push(key); + } + } + } - /** - * Casts values for set(). - * - * @param {Object} value - * @param {Document} doc document that triggers the casting - * @param {Boolean} init whether this is an initialization cast - * @api private - */ - - SchemaArray.prototype.cast = function (value, doc, init, prev, options) { - // lazy load - MongooseArray || (MongooseArray = __nccwpck_require__(3000).Array); - - let i; - let l; - - if (Array.isArray(value)) { - const len = value.length; - if (!len && doc) { - const indexes = doc.schema.indexedPaths(); - - const arrayPath = this.path; - for (i = 0, l = indexes.length; i < l; ++i) { - const pathIndex = indexes[i][0][arrayPath]; - if (pathIndex === "2dsphere" || pathIndex === "2d") { - return; - } - } + if (selected) { + // they passed $elemMatch, cast em + try { + out = this.cast(this.model, selected); + } catch (err) { + return err; + } - // Special case: if this index is on the parent of what looks like - // GeoJSON, skip setting the default to empty array re: #1668, #3233 - const arrayGeojsonPath = this.path.endsWith(".coordinates") - ? this.path.substr(0, this.path.lastIndexOf(".")) - : null; - if (arrayGeojsonPath != null) { - for (i = 0, l = indexes.length; i < l; ++i) { - const pathIndex = indexes[i][0][arrayGeojsonPath]; - if (pathIndex === "2dsphere") { - return; - } - } - } - } + // apply the casted field args + i = elemMatchKeys.length; + while (i--) { + key = elemMatchKeys[i]; + fields[key] = out[key]; + } + } - options = options || emptyOpts; + return fields; +}; - value = MongooseArray( - value, - options.path || this._arrayPath || this.path, - doc, - this - ); +/** + * Applies schematype selected options to this query. + * @api private + */ - if ( - init && - doc != null && - doc.$__ != null && - doc.populated(this.path) - ) { - return value; - } +Query.prototype._applyPaths = function applyPaths() { + this._fields = this._fields || {}; + helpers.applyPaths(this._fields, this.model.schema); - const caster = this.caster; - const isMongooseArray = caster.$isMongooseArray; - const isArrayOfNumbers = caster.instance === "Number"; - if (caster && this.casterConstructor !== Mixed) { - try { - for (i = 0; i < len; i++) { - // Special case: number arrays disallow undefined. - // Re: gh-840 - // See commit 1298fe92d2c790a90594bd08199e45a4a09162a6 - if (isArrayOfNumbers && value[i] === void 0) { - throw new MongooseError( - "Mongoose number arrays disallow storing undefined" - ); - } - const opts = {}; - // Perf: creating `arrayPath` is expensive for large arrays. - // We only need `arrayPath` if this is a nested array, so - // skip if possible. - if (isMongooseArray) { - if (options.arrayPath != null) { - opts.arrayPathIndex = i; - } else if (caster._arrayParentPath != null) { - opts.arrayPathIndex = i; - } - } - value[i] = caster.applySetters( - value[i], - doc, - init, - void 0, - opts - ); - } - } catch (e) { - // rethrow - throw new CastError( - "[" + e.kind + "]", - util.inspect(value), - this.path + "." + i, - e, - this - ); - } - } + let _selectPopulatedPaths = true; - return value; - } + if ('selectPopulatedPaths' in this.model.base.options) { + _selectPopulatedPaths = this.model.base.options.selectPopulatedPaths; + } + if ('selectPopulatedPaths' in this.model.schema.options) { + _selectPopulatedPaths = this.model.schema.options.selectPopulatedPaths; + } - if (init || SchemaArray.options.castNonArrays) { - // gh-2442: if we're loading this from the db and its not an array, mark - // the whole array as modified. - if (!!doc && !!init) { - doc.markModified(this.path); - } - return this.cast([value], doc, init); - } + if (_selectPopulatedPaths) { + selectPopulatedFields(this._fields, this._userProvidedFields, this._mongooseOptions.populate); + } +}; - throw new CastError( - "Array", - util.inspect(value), - this.path, - null, - this - ); - }; +/** + * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html). + * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function. + * + * The `.cursor()` function triggers pre find hooks, but **not** post find hooks. + * + * ####Example + * + * // There are 2 ways to use a cursor. First, as a stream: + * Thing. + * find({ name: /^hello/ }). + * cursor(). + * on('data', function(doc) { console.log(doc); }). + * on('end', function() { console.log('Done!'); }); + * + * // Or you can use `.next()` to manually get the next doc in the stream. + * // `.next()` returns a promise, so you can use promises or callbacks. + * const cursor = Thing.find({ name: /^hello/ }).cursor(); + * cursor.next(function(error, doc) { + * console.log(doc); + * }); + * + * // Because `.next()` returns a promise, you can use co + * // to easily iterate through all documents without loading them + * // all into memory. + * const cursor = Thing.find({ name: /^hello/ }).cursor(); + * for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) { + * console.log(doc); + * } + * + * ####Valid options + * + * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data` and returned by `.next()`. + * + * @return {QueryCursor} + * @param {Object} [options] + * @see QueryCursor + * @api public + */ - /*! - * ignore - */ +Query.prototype.cursor = function cursor(opts) { + this._applyPaths(); + this._fields = this._castFields(this._fields); + this.setOptions({ projection: this._fieldsForExec() }); + if (opts) { + this.setOptions(opts); + } - SchemaArray.prototype._castForPopulate = function _castForPopulate( - value, - doc - ) { - // lazy load - MongooseArray || (MongooseArray = __nccwpck_require__(3000).Array); + const options = Object.assign({}, this._optionsForExec(), { + projection: this.projection() + }); + try { + this.cast(this.model); + } catch (err) { + return (new QueryCursor(this, options))._markError(err); + } - if (Array.isArray(value)) { - let i; - const len = value.length; + return new QueryCursor(this, options); +}; - const caster = this.caster; - if (caster && this.casterConstructor !== Mixed) { - try { - for (i = 0; i < len; i++) { - const opts = {}; - // Perf: creating `arrayPath` is expensive for large arrays. - // We only need `arrayPath` if this is a nested array, so - // skip if possible. - if ( - caster.$isMongooseArray && - caster._arrayParentPath != null - ) { - opts.arrayPathIndex = i; - } +// the rest of these are basically to support older Mongoose syntax with mquery - value[i] = caster.cast(value[i], doc, false, void 0, opts); - } - } catch (e) { - // rethrow - throw new CastError( - "[" + e.kind + "]", - util.inspect(value), - this.path + "." + i, - e, - this - ); - } - } +/** + * _DEPRECATED_ Alias of `maxScan` + * + * @deprecated + * @see maxScan #query_Query-maxScan + * @method maxscan + * @memberOf Query + * @instance + */ - return value; - } +Query.prototype.maxscan = Query.base.maxScan; - throw new CastError( - "Array", - util.inspect(value), - this.path, - null, - this - ); - }; +/** + * Sets the tailable option (for use with capped collections). + * + * ####Example + * + * query.tailable(); // true + * query.tailable(true); + * query.tailable(false); + * + * // Set both `tailable` and `awaitData` options + * query.tailable({ awaitData: true }); + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Boolean} bool defaults to true + * @param {Object} [opts] options to set + * @param {Boolean} [opts.awaitData] false by default. Set to true to keep the cursor open even if there's no data. + * @param {Number} [opts.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 + * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/ + * @api public + */ - /*! - * Ignore - */ - - SchemaArray.prototype.discriminator = function (name, schema) { - let arr = this; - while (arr.$isMongooseArray && !arr.$isMongooseDocumentArray) { - arr = arr.casterConstructor; - if (arr == null || typeof arr === "function") { - throw new MongooseError( - "You can only add an embedded discriminator on " + - "a document array, " + - this.path + - " is a plain array" - ); - } - } - return arr.discriminator(name, schema); - }; +Query.prototype.tailable = function(val, opts) { + // we need to support the tailable({ awaitData : true }) as well as the + // tailable(true, {awaitData :true}) syntax that mquery does not support + if (val != null && typeof val.constructor === 'function' && val.constructor.name === 'Object') { + opts = val; + val = true; + } - /*! - * ignore - */ - - SchemaArray.prototype.clone = function () { - const options = Object.assign({}, this.options); - const schematype = new this.constructor( - this.path, - this.caster, - options, - this.schemaOptions - ); - schematype.validators = this.validators.slice(); - if (this.requiredValidator !== undefined) { - schematype.requiredValidator = this.requiredValidator; - } - return schematype; - }; + if (val === undefined) { + val = true; + } - /** - * Casts values for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ + if (opts && typeof opts === 'object') { + for (const key of Object.keys(opts)) { + if (key === 'awaitData' || key === 'awaitdata') { // backwards compat, see gh-10875 + // For backwards compatibility + this.options['awaitData'] = !!opts[key]; + } else { + this.options[key] = opts[key]; + } + } + } - SchemaArray.prototype.castForQuery = function ($conditional, value) { - let handler; - let val; + return Query.base.tailable.call(this, val); +}; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; +/** + * Declares an intersects query for `geometry()`. + * + * ####Example + * + * query.where('path').intersects().geometry({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * query.where('path').intersects({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * ####NOTE: + * + * **MUST** be used after `where()`. + * + * ####NOTE: + * + * In Mongoose 3.7, `intersects` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). + * + * @method intersects + * @memberOf Query + * @instance + * @param {Object} [arg] + * @return {Query} this + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/ + * @api public + */ - if (!handler) { - throw new Error("Can't use " + $conditional + " with Array."); - } +/** + * Specifies a `$geometry` condition + * + * ####Example + * + * const polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] + * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) + * + * // or + * const polyB = [[ 0, 0 ], [ 1, 1 ]] + * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) + * + * // or + * const polyC = [ 0, 0 ] + * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) + * + * // or + * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) + * + * The argument is assigned to the most recent path passed to `where()`. + * + * ####NOTE: + * + * `geometry()` **must** come after either `intersects()` or `within()`. + * + * The `object` argument must contain `type` and `coordinates` properties. + * - type {String} + * - coordinates {Array} + * + * @method geometry + * @memberOf Query + * @instance + * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. + * @return {Query} this + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ - val = handler.call(this, value); - } else { - val = $conditional; - let Constructor = this.casterConstructor; - - if ( - val && - Constructor.discriminators && - Constructor.schema && - Constructor.schema.options && - Constructor.schema.options.discriminatorKey - ) { - if ( - typeof val[Constructor.schema.options.discriminatorKey] === - "string" && - Constructor.discriminators[ - val[Constructor.schema.options.discriminatorKey] - ] - ) { - Constructor = - Constructor.discriminators[ - val[Constructor.schema.options.discriminatorKey] - ]; - } else { - const constructorByValue = getDiscriminatorByValue( - Constructor.discriminators, - val[Constructor.schema.options.discriminatorKey] - ); - if (constructorByValue) { - Constructor = constructorByValue; - } - } - } +/** + * Specifies a `$near` or `$nearSphere` condition + * + * These operators return documents sorted by distance. + * + * ####Example + * + * query.where('loc').near({ center: [10, 10] }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); + * query.near('loc', { center: [10, 10], maxDistance: 5 }); + * + * @method near + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Object} val + * @return {Query} this + * @see $near http://docs.mongodb.org/manual/reference/operator/near/ + * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ + * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ - const proto = this.casterConstructor.prototype; - let method = proto && (proto.castForQuery || proto.cast); - if (!method && Constructor.castForQuery) { - method = Constructor.castForQuery; - } - const caster = this.caster; +/*! + * Overwriting mquery is needed to support a couple different near() forms found in older + * versions of mongoose + * near([1,1]) + * near(1,1) + * near(field, [1,2]) + * near(field, 1, 2) + * In addition to all of the normal forms supported by mquery + */ - if (Array.isArray(val)) { - this.setters.reverse().forEach((setter) => { - val = setter.call(this, val, this); - }); - val = val.map(function (v) { - if (utils.isObject(v) && v.$elemMatch) { - return v; - } - if (method) { - v = method.call(caster, v); - return v; - } - if (v != null) { - v = new Constructor(v); - return v; - } - return v; - }); - } else if (method) { - val = method.call(caster, val); - } else if (val != null) { - val = new Constructor(val); - } - } +Query.prototype.near = function() { + const params = []; + const sphere = this._mongooseOptions.nearSphere; + + // TODO refactor + + if (arguments.length === 1) { + if (Array.isArray(arguments[0])) { + params.push({ center: arguments[0], spherical: sphere }); + } else if (typeof arguments[0] === 'string') { + // just passing a path + params.push(arguments[0]); + } else if (utils.isObject(arguments[0])) { + if (typeof arguments[0].spherical !== 'boolean') { + arguments[0].spherical = sphere; + } + params.push(arguments[0]); + } else { + throw new TypeError('invalid argument'); + } + } else if (arguments.length === 2) { + if (typeof arguments[0] === 'number' && typeof arguments[1] === 'number') { + params.push({ center: [arguments[0], arguments[1]], spherical: sphere }); + } else if (typeof arguments[0] === 'string' && Array.isArray(arguments[1])) { + params.push(arguments[0]); + params.push({ center: arguments[1], spherical: sphere }); + } else if (typeof arguments[0] === 'string' && utils.isObject(arguments[1])) { + params.push(arguments[0]); + if (typeof arguments[1].spherical !== 'boolean') { + arguments[1].spherical = sphere; + } + params.push(arguments[1]); + } else { + throw new TypeError('invalid argument'); + } + } else if (arguments.length === 3) { + if (typeof arguments[0] === 'string' && typeof arguments[1] === 'number' + && typeof arguments[2] === 'number') { + params.push(arguments[0]); + params.push({ center: [arguments[1], arguments[2]], spherical: sphere }); + } else { + throw new TypeError('invalid argument'); + } + } else { + throw new TypeError('invalid argument'); + } - return val; - }; + return Query.base.near.apply(this, params); +}; - function cast$all(val) { - if (!Array.isArray(val)) { - val = [val]; - } +/** + * _DEPRECATED_ Specifies a `$nearSphere` condition + * + * ####Example + * + * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); + * + * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`. + * + * ####Example + * + * query.where('loc').near({ center: [10, 10], spherical: true }); + * + * @deprecated + * @see near() #query_Query-near + * @see $near http://docs.mongodb.org/manual/reference/operator/near/ + * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ + * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ + */ - val = val.map(function (v) { - if (utils.isObject(v)) { - const o = {}; - o[this.path] = v; - return cast(this.casterConstructor.schema, o)[this.path]; - } - return v; - }, this); +Query.prototype.nearSphere = function() { + this._mongooseOptions.nearSphere = true; + this.near.apply(this, arguments); + return this; +}; + +/** + * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js) + * This function *only* works for `find()` queries. + * You do not need to call this function explicitly, the JavaScript runtime + * will call it for you. + * + * ####Example + * + * for await (const doc of Model.aggregate([{ $sort: { name: 1 } }])) { + * console.log(doc.name); + * } + * + * Node.js 10.x supports async iterators natively without any flags. You can + * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). + * + * **Note:** This function is not if `Symbol.asyncIterator` is undefined. If + * `Symbol.asyncIterator` is undefined, that means your Node.js version does not + * support async iterators. + * + * @method Symbol.asyncIterator + * @memberOf Query + * @instance + * @api public + */ - return this.castForQuery(val); - } +if (Symbol.asyncIterator != null) { + Query.prototype[Symbol.asyncIterator] = function() { + return this.cursor().transformNull()._transformForAsyncIterator(); + }; +} - function cast$elemMatch(val) { - const keys = Object.keys(val); - const numKeys = keys.length; - for (let i = 0; i < numKeys; ++i) { - const key = keys[i]; - const value = val[key]; - if (isOperator(key) && value != null) { - val[key] = this.castForQuery(key, value); - } - } +/** + * Specifies a `$polygon` condition + * + * ####Example + * + * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) + * query.polygon('loc', [10,20], [13, 25], [7,15]) + * + * @method polygon + * @memberOf Query + * @instance + * @param {String|Array} [path] + * @param {Array|Object} [coordinatePairs...] + * @return {Query} this + * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ - // Is this an embedded discriminator and is the discriminator key set? - // If so, use the discriminator schema. See gh-7449 - const discriminatorKey = get( - this, - "casterConstructor.schema.options.discriminatorKey" - ); - const discriminators = get( - this, - "casterConstructor.schema.discriminators", - {} - ); - if ( - discriminatorKey != null && - val[discriminatorKey] != null && - discriminators[val[discriminatorKey]] != null - ) { - return cast(discriminators[val[discriminatorKey]], val); - } +/** + * Specifies a `$box` condition + * + * ####Example + * + * const lowerLeft = [40.73083, -73.99756] + * const upperRight= [40.741404, -73.988135] + * + * query.where('loc').within().box(lowerLeft, upperRight) + * query.box({ ll : lowerLeft, ur : upperRight }) + * + * @method box + * @memberOf Query + * @instance + * @see $box http://docs.mongodb.org/manual/reference/operator/box/ + * @see within() Query#within #query_Query-within + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @param {Object} val + * @param [Array] Upper Right Coords + * @return {Query} this + * @api public + */ - return cast(this.casterConstructor.schema, val); - } +/*! + * this is needed to support the mongoose syntax of: + * box(field, { ll : [x,y], ur : [x2,y2] }) + * box({ ll : [x,y], ur : [x2,y2] }) + */ - const handle = (SchemaArray.prototype.$conditionalHandlers = {}); +Query.prototype.box = function(ll, ur) { + if (!Array.isArray(ll) && utils.isObject(ll)) { + ur = ll.ur; + ll = ll.ll; + } + return Query.base.box.call(this, ll, ur); +}; - handle.$all = cast$all; - handle.$options = String; - handle.$elemMatch = cast$elemMatch; - handle.$geoIntersects = geospatial.cast$geoIntersects; - handle.$or = createLogicalQueryOperatorHandler("$or"); - handle.$and = createLogicalQueryOperatorHandler("$and"); - handle.$nor = createLogicalQueryOperatorHandler("$nor"); +/** + * Specifies a `$center` or `$centerSphere` condition. + * + * ####Example + * + * const area = { center: [50, 50], radius: 10, unique: true } + * query.where('loc').within().circle(area) + * // alternatively + * query.circle('loc', area); + * + * // spherical calculations + * const area = { center: [50, 50], radius: 10, unique: true, spherical: true } + * query.where('loc').within().circle(area) + * // alternatively + * query.circle('loc', area); + * + * @method circle + * @memberOf Query + * @instance + * @param {String} [path] + * @param {Object} area + * @return {Query} this + * @see $center http://docs.mongodb.org/manual/reference/operator/center/ + * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ + * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/geoWithin/ + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ - function createLogicalQueryOperatorHandler(op) { - return function logicalQueryOperatorHandler(val) { - if (!Array.isArray(val)) { - throw new TypeError("conditional " + op + " requires an array"); - } +/** + * _DEPRECATED_ Alias for [circle](#query_Query-circle) + * + * **Deprecated.** Use [circle](#query_Query-circle) instead. + * + * @deprecated + * @method center + * @memberOf Query + * @instance + * @api public + */ - const ret = []; - for (const obj of val) { - ret.push(cast(this.casterConstructor.schema, obj)); - } +Query.prototype.center = Query.base.circle; - return ret; - }; - } +/** + * _DEPRECATED_ Specifies a `$centerSphere` condition + * + * **Deprecated.** Use [circle](#query_Query-circle) instead. + * + * ####Example + * + * const area = { center: [50, 50], radius: 10 }; + * query.where('loc').within().centerSphere(area); + * + * @deprecated + * @param {String} [path] + * @param {Object} val + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ + * @api public + */ - handle.$near = handle.$nearSphere = geospatial.cast$near; +Query.prototype.centerSphere = function() { + if (arguments[0] != null && typeof arguments[0].constructor === 'function' && arguments[0].constructor.name === 'Object') { + arguments[0].spherical = true; + } - handle.$within = handle.$geoWithin = geospatial.cast$within; + if (arguments[1] != null && typeof arguments[1].constructor === 'function' && arguments[1].constructor.name === 'Object') { + arguments[1].spherical = true; + } - handle.$size = handle.$minDistance = handle.$maxDistance = castToNumber; + Query.base.circle.apply(this, arguments); +}; - handle.$exists = $exists; - handle.$type = $type; +/** + * Determines if field selection has been made. + * + * @method selected + * @memberOf Query + * @instance + * @return {Boolean} + * @api public + */ - handle.$eq = - handle.$gt = - handle.$gte = - handle.$lt = - handle.$lte = - handle.$ne = - handle.$regex = - SchemaArray.prototype.castForQuery; +/** + * Determines if inclusive field selection has been made. + * + * query.selectedInclusively() // false + * query.select('name') + * query.selectedInclusively() // true + * + * @method selectedInclusively + * @memberOf Query + * @instance + * @return {Boolean} + * @api public + */ - // `$in` is special because you can also include an empty array in the query - // like `$in: [1, []]`, see gh-5913 - handle.$nin = SchemaType.prototype.$conditionalHandlers.$nin; - handle.$in = SchemaType.prototype.$conditionalHandlers.$in; +Query.prototype.selectedInclusively = function selectedInclusively() { + return isInclusive(this._fields); +}; - /*! - * Module exports. - */ +/** + * Determines if exclusive field selection has been made. + * + * query.selectedExclusively() // false + * query.select('-name') + * query.selectedExclusively() // true + * query.selectedInclusively() // false + * + * @method selectedExclusively + * @memberOf Query + * @instance + * @return {Boolean} + * @api public + */ - module.exports = SchemaArray; +Query.prototype.selectedExclusively = function selectedExclusively() { + return isExclusive(this._fields); +}; - /***/ - }, +/** + * The model this query is associated with. + * + * #### Example: + * + * const q = MyModel.find(); + * q.model === MyModel; // true + * + * @api public + * @property model + * @memberOf Query + * @instance + */ - /***/ 2900: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const CastError = __nccwpck_require__(2798); - const SchemaType = __nccwpck_require__(5660); - const castBoolean = __nccwpck_require__(66); - const utils = __nccwpck_require__(9232); - - /** - * Boolean SchemaType constructor. - * - * @param {String} path - * @param {Object} options - * @inherits SchemaType - * @api public - */ - - function SchemaBoolean(path, options) { - SchemaType.call(this, path, options, "Boolean"); - } - - /** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ - SchemaBoolean.schemaName = "Boolean"; - - SchemaBoolean.defaultOptions = {}; - - /*! - * Inherits from SchemaType. - */ - SchemaBoolean.prototype = Object.create(SchemaType.prototype); - SchemaBoolean.prototype.constructor = SchemaBoolean; - - /*! - * ignore - */ - - SchemaBoolean._cast = castBoolean; - - /** - * Sets a default option for all Boolean instances. - * - * ####Example: - * - * // Make all booleans have `default` of false. - * mongoose.Schema.Boolean.set('default', false); - * - * const Order = mongoose.model('Order', new Schema({ isPaid: Boolean })); - * new Order({ }).isPaid; // false - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - - SchemaBoolean.set = SchemaType.set; - - /** - * Get/set the function used to cast arbitrary values to booleans. - * - * ####Example: - * - * // Make Mongoose cast empty string '' to false. - * const original = mongoose.Schema.Boolean.cast(); - * mongoose.Schema.Boolean.cast(v => { - * if (v === '') { - * return false; - * } - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.Schema.Boolean.cast(false); - * - * @param {Function} caster - * @return {Function} - * @function get - * @static - * @api public - */ - - SchemaBoolean.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = this._defaultCaster; - } - this._cast = caster; - - return this._cast; - }; +Query.prototype.model; - /*! - * ignore - */ +/*! + * Export + */ - SchemaBoolean._defaultCaster = (v) => { - if (v != null && typeof v !== "boolean") { - throw new Error(); - } - return v; - }; +module.exports = Query; - /*! - * ignore - */ - - SchemaBoolean._checkRequired = (v) => v === true || v === false; - - /** - * Override the function the required validator uses to check whether a boolean - * passes the `required` check. - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - - SchemaBoolean.checkRequired = SchemaType.checkRequired; - - /** - * Check if the given value satisfies a required validator. For a boolean - * to satisfy a required validator, it must be strictly equal to true or to - * false. - * - * @param {Any} value - * @return {Boolean} - * @api public - */ - - SchemaBoolean.prototype.checkRequired = function (value) { - return this.constructor._checkRequired(value); - }; - /** - * Configure which values get casted to `true`. - * - * ####Example: - * - * const M = mongoose.model('Test', new Schema({ b: Boolean })); - * new M({ b: 'affirmative' }).b; // undefined - * mongoose.Schema.Boolean.convertToTrue.add('affirmative'); - * new M({ b: 'affirmative' }).b; // true - * - * @property convertToTrue - * @type Set - * @api public - */ - - Object.defineProperty(SchemaBoolean, "convertToTrue", { - get: () => castBoolean.convertToTrue, - set: (v) => { - castBoolean.convertToTrue = v; - }, - }); +/***/ }), - /** - * Configure which values get casted to `false`. - * - * ####Example: - * - * const M = mongoose.model('Test', new Schema({ b: Boolean })); - * new M({ b: 'nay' }).b; // undefined - * mongoose.Schema.Types.Boolean.convertToFalse.add('nay'); - * new M({ b: 'nay' }).b; // false - * - * @property convertToFalse - * @type Set - * @api public - */ - - Object.defineProperty(SchemaBoolean, "convertToFalse", { - get: () => castBoolean.convertToFalse, - set: (v) => { - castBoolean.convertToFalse = v; - }, - }); +/***/ 5299: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Casts to boolean - * - * @param {Object} value - * @param {Object} model - this value is optional - * @api private - */ - - SchemaBoolean.prototype.cast = function (value) { - let castBoolean; - if (typeof this._castFunction === "function") { - castBoolean = this._castFunction; - } else if (typeof this.constructor.cast === "function") { - castBoolean = this.constructor.cast(); - } else { - castBoolean = SchemaBoolean.cast(); - } +"use strict"; - try { - return castBoolean(value); - } catch (error) { - throw new CastError("Boolean", value, this.path, error, this); - } - }; - SchemaBoolean.$conditionalHandlers = utils.options( - SchemaType.prototype.$conditionalHandlers, - {} - ); +/*! + * Module dependencies + */ - /** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} val - * @api private - */ - - SchemaBoolean.prototype.castForQuery = function ($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = SchemaBoolean.$conditionalHandlers[$conditional]; - - if (handler) { - return handler.call(this, val); - } +const checkEmbeddedDiscriminatorKeyProjection = + __nccwpck_require__(1762); +const get = __nccwpck_require__(8730); +const getDiscriminatorByValue = + __nccwpck_require__(8689); +const isDefiningProjection = __nccwpck_require__(1903); +const clone = __nccwpck_require__(5092); - return this._castForQuery(val); - } +/*! + * Prepare a set of path options for query population. + * + * @param {Query} query + * @param {Object} options + * @return {Array} + */ - return this._castForQuery($conditional); - }; +exports.preparePopulationOptions = function preparePopulationOptions(query, options) { + const _populate = query.options.populate; + const pop = Object.keys(_populate).reduce((vals, key) => vals.concat([_populate[key]]), []); - /** - * - * @api private - */ + // lean options should trickle through all queries + if (options.lean != null) { + pop. + filter(p => get(p, 'options.lean') == null). + forEach(makeLean(options.lean)); + } - SchemaBoolean.prototype._castNullish = function _castNullish(v) { - if ( - typeof v === "undefined" && - this.$$context != null && - this.$$context._mongooseOptions != null && - this.$$context._mongooseOptions.omitUndefined - ) { - return v; - } - const castBoolean = - typeof this.constructor.cast === "function" - ? this.constructor.cast() - : SchemaBoolean.cast(); - if (castBoolean == null) { - return v; - } - if ( - castBoolean.convertToFalse instanceof Set && - castBoolean.convertToFalse.has(v) - ) { - return false; - } - if ( - castBoolean.convertToTrue instanceof Set && - castBoolean.convertToTrue.has(v) - ) { - return true; - } - return v; - }; + pop.forEach(opts => { + opts._localModel = query.model; + }); - /*! - * Module exports. - */ + return pop; +}; - module.exports = SchemaBoolean; +/*! + * Prepare a set of path options for query population. This is the MongooseQuery + * version + * + * @param {Query} query + * @param {Object} options + * @return {Array} + */ - /***/ - }, +exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query, options) { + const _populate = query._mongooseOptions.populate; + const pop = Object.keys(_populate).reduce((vals, key) => vals.concat([_populate[key]]), []); - /***/ 4798: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ - - const MongooseBuffer = __nccwpck_require__(5505); - const SchemaBufferOptions = __nccwpck_require__(6680); - const SchemaType = __nccwpck_require__(5660); - const handleBitwiseOperator = __nccwpck_require__(9547); - const utils = __nccwpck_require__(9232); - - const Binary = MongooseBuffer.Binary; - const CastError = SchemaType.CastError; - - /** - * Buffer SchemaType constructor - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - - function SchemaBuffer(key, options) { - SchemaType.call(this, key, options, "Buffer"); - } - - /** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ - SchemaBuffer.schemaName = "Buffer"; - - SchemaBuffer.defaultOptions = {}; - - /*! - * Inherits from SchemaType. - */ - SchemaBuffer.prototype = Object.create(SchemaType.prototype); - SchemaBuffer.prototype.constructor = SchemaBuffer; - SchemaBuffer.prototype.OptionsConstructor = SchemaBufferOptions; - - /*! - * ignore - */ - - SchemaBuffer._checkRequired = (v) => !!(v && v.length); - - /** - * Sets a default option for all Buffer instances. - * - * ####Example: - * - * // Make all buffers have `required` of true by default. - * mongoose.Schema.Buffer.set('required', true); - * - * const User = mongoose.model('User', new Schema({ test: Buffer })); - * new User({ }).validateSync().errors.test.message; // Path `test` is required. - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - - SchemaBuffer.set = SchemaType.set; - - /** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * ####Example: - * - * // Allow empty strings to pass `required` check - * mongoose.Schema.Types.String.checkRequired(v => v != null); - * - * const M = mongoose.model({ buf: { type: Buffer, required: true } }); - * new M({ buf: Buffer.from('') }).validateSync(); // validation passes! - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - - SchemaBuffer.checkRequired = SchemaType.checkRequired; - - /** - * Check if the given value satisfies a required validator. To satisfy a - * required validator, a buffer must not be null or undefined and have - * non-zero length. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - - SchemaBuffer.prototype.checkRequired = function (value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - return this.constructor._checkRequired(value); - }; + // lean options should trickle through all queries + if (options.lean != null) { + pop. + filter(p => get(p, 'options.lean') == null). + forEach(makeLean(options.lean)); + } - /** - * Casts contents - * - * @param {Object} value - * @param {Document} doc document that triggers the casting - * @param {Boolean} init - * @api private - */ - - SchemaBuffer.prototype.cast = function (value, doc, init) { - let ret; - if (SchemaType._isRef(this, value, doc, init)) { - if (value && value.isMongooseBuffer) { - return value; - } + const session = get(query, 'options.session', null); + if (session != null) { + pop.forEach(path => { + if (path.options == null) { + path.options = { session: session }; + return; + } + if (!('session' in path.options)) { + path.options.session = session; + } + }); + } - if (Buffer.isBuffer(value)) { - if (!value || !value.isMongooseBuffer) { - value = new MongooseBuffer(value, [this.path, doc]); - if (this.options.subtype != null) { - value._subtype = this.options.subtype; - } - } - return value; - } + const projection = query._fieldsForExec(); + pop.forEach(p => { + p._queryProjection = projection; + }); + pop.forEach(opts => { + opts._localModel = query.model; + }); - if (value instanceof Binary) { - ret = new MongooseBuffer(value.value(true), [this.path, doc]); - if (typeof value.sub_type !== "number") { - throw new CastError("Buffer", value, this.path, null, this); - } - ret._subtype = value.sub_type; - return ret; - } + return pop; +}; - return this._castRef(value, doc, init); - } +/*! + * If the document is a mapped discriminator type, it returns a model instance for that type, otherwise, + * it returns an instance of the given model. + * + * @param {Model} model + * @param {Object} doc + * @param {Object} fields + * + * @return {Document} + */ +exports.createModel = function createModel(model, doc, fields, userProvidedFields, options) { + model.hooks.execPreSync('createModel', doc); + const discriminatorMapping = model.schema ? + model.schema.discriminatorMapping : + null; + + const key = discriminatorMapping && discriminatorMapping.isRoot ? + discriminatorMapping.key : + null; + + const value = doc[key]; + if (key && value && model.discriminators) { + const discriminator = model.discriminators[value] || getDiscriminatorByValue(model.discriminators, value); + if (discriminator) { + const _fields = clone(userProvidedFields); + exports.applyPaths(_fields, discriminator.schema); + return new discriminator(undefined, _fields, true); + } + } - // documents - if (value && value._id) { - value = value._id; - } + const _opts = { + skipId: true, + isNew: false, + willInit: true + }; + if (options != null && 'defaults' in options) { + _opts.defaults = options.defaults; + } + return new model(undefined, fields, _opts); +}; - if (value && value.isMongooseBuffer) { - return value; - } +/*! + * ignore + */ - if (Buffer.isBuffer(value)) { - if (!value || !value.isMongooseBuffer) { - value = new MongooseBuffer(value, [this.path, doc]); - if (this.options.subtype != null) { - value._subtype = this.options.subtype; - } - } - return value; - } +exports.applyPaths = function applyPaths(fields, schema) { + // determine if query is selecting or excluding fields + let exclude; + let keys; + let keyIndex; - if (value instanceof Binary) { - ret = new MongooseBuffer(value.value(true), [this.path, doc]); - if (typeof value.sub_type !== "number") { - throw new CastError("Buffer", value, this.path, null, this); - } - ret._subtype = value.sub_type; - return ret; - } + if (fields) { + keys = Object.keys(fields); + keyIndex = keys.length; - if (value === null) { - return value; - } + while (keyIndex--) { + if (keys[keyIndex][0] === '+') { + continue; + } + const field = fields[keys[keyIndex]]; + // Skip `$meta` and `$slice` + if (!isDefiningProjection(field)) { + continue; + } + exclude = !field; + break; + } + } - const type = typeof value; - if ( - type === "string" || - type === "number" || - Array.isArray(value) || - (type === "object" && - value.type === "Buffer" && - Array.isArray(value.data)) // gh-6863 - ) { - if (type === "number") { - value = [value]; - } - ret = new MongooseBuffer(value, [this.path, doc]); - if (this.options.subtype != null) { - ret._subtype = this.options.subtype; - } - return ret; - } + // if selecting, apply default schematype select:true fields + // if excluding, apply schematype select:false fields - throw new CastError("Buffer", value, this.path, null, this); - }; + const selected = []; + const excluded = []; + const stack = []; - /** - * Sets the default [subtype](https://studio3t.com/whats-new/best-practices-uuid-mongodb/) - * for this buffer. You can find a [list of allowed subtypes here](http://api.mongodb.com/python/current/api/bson/binary.html). - * - * ####Example: - * - * const s = new Schema({ uuid: { type: Buffer, subtype: 4 }); - * const M = db.model('M', s); - * const m = new M({ uuid: 'test string' }); - * m.uuid._subtype; // 4 - * - * @param {Number} subtype the default subtype - * @return {SchemaType} this - * @api public - */ - - SchemaBuffer.prototype.subtype = function (subtype) { - this.options.subtype = subtype; - return this; - }; + analyzeSchema(schema); - /*! - * ignore - */ - function handleSingle(val) { - return this.castForQuery(val); + switch (exclude) { + case true: + for (const fieldName of excluded) { + fields[fieldName] = 0; + } + break; + case false: + if (schema && + schema.paths['_id'] && + schema.paths['_id'].options && + schema.paths['_id'].options.select === false) { + fields._id = 0; } - SchemaBuffer.prototype.$conditionalHandlers = utils.options( - SchemaType.prototype.$conditionalHandlers, - { - $bitsAllClear: handleBitwiseOperator, - $bitsAnyClear: handleBitwiseOperator, - $bitsAllSet: handleBitwiseOperator, - $bitsAnySet: handleBitwiseOperator, - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle, + for (const fieldName of selected) { + fields[fieldName] = fields[fieldName] || 1; + } + break; + case undefined: + if (fields == null) { + break; + } + // Any leftover plus paths must in the schema, so delete them (gh-7017) + for (const key of Object.keys(fields || {})) { + if (key.startsWith('+')) { + delete fields[key]; } - ); + } - /** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - - SchemaBuffer.prototype.castForQuery = function ($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) { - throw new Error("Can't use " + $conditional + " with Buffer."); - } - return handler.call(this, val); - } - val = $conditional; - const casted = this._castForQuery(val); - return casted - ? casted.toObject({ transform: false, virtuals: false }) - : casted; - }; + // user didn't specify fields, implies returning all fields. + // only need to apply excluded fields and delete any plus paths + for (const fieldName of excluded) { + fields[fieldName] = 0; + } + break; + } - /*! - * Module exports. - */ + function analyzeSchema(schema, prefix) { + prefix || (prefix = ''); - module.exports = SchemaBuffer; + // avoid recursion + if (stack.indexOf(schema) !== -1) { + return []; + } + stack.push(schema); - /***/ - }, + const addedPaths = []; + schema.eachPath(function(path, type) { + if (prefix) path = prefix + '.' + path; - /***/ 9140: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module requirements. - */ - - const MongooseError = __nccwpck_require__(4327); - const SchemaDateOptions = __nccwpck_require__(5354); - const SchemaType = __nccwpck_require__(5660); - const castDate = __nccwpck_require__(1001); - const getConstructorName = __nccwpck_require__(7323); - const utils = __nccwpck_require__(9232); - - const CastError = SchemaType.CastError; - - /** - * Date SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - - function SchemaDate(key, options) { - SchemaType.call(this, key, options, "Date"); - } - - /** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ - SchemaDate.schemaName = "Date"; - - SchemaDate.defaultOptions = {}; - - /*! - * Inherits from SchemaType. - */ - SchemaDate.prototype = Object.create(SchemaType.prototype); - SchemaDate.prototype.constructor = SchemaDate; - SchemaDate.prototype.OptionsConstructor = SchemaDateOptions; - - /*! - * ignore - */ - - SchemaDate._cast = castDate; - - /** - * Sets a default option for all Date instances. - * - * ####Example: - * - * // Make all dates have `required` of true by default. - * mongoose.Schema.Date.set('required', true); - * - * const User = mongoose.model('User', new Schema({ test: Date })); - * new User({ }).validateSync().errors.test.message; // Path `test` is required. - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - - SchemaDate.set = SchemaType.set; - - /** - * Get/set the function used to cast arbitrary values to dates. - * - * ####Example: - * - * // Mongoose converts empty string '' into `null` for date types. You - * // can create a custom caster to disable it. - * const original = mongoose.Schema.Types.Date.cast(); - * mongoose.Schema.Types.Date.cast(v => { - * assert.ok(v !== ''); - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.Schema.Types.Date.cast(false); - * - * @param {Function} caster - * @return {Function} - * @function get - * @static - * @api public - */ - - SchemaDate.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = this._defaultCaster; - } - this._cast = caster; - - return this._cast; - }; + let addedPath = analyzePath(path, type); + // arrays + if (addedPath == null && type.$isMongooseArray && !type.$isMongooseDocumentArray) { + addedPath = analyzePath(path, type.caster); + } + if (addedPath != null) { + addedPaths.push(addedPath); + } - /*! - * ignore - */ + // nested schemas + if (type.schema) { + const _addedPaths = analyzeSchema(type.schema, path); - SchemaDate._defaultCaster = (v) => { - if (v != null && !(v instanceof Date)) { - throw new Error(); + // Special case: if discriminator key is the only field that would + // be projected in, remove it. + if (exclude === false) { + checkEmbeddedDiscriminatorKeyProjection(fields, path, type.schema, + selected, _addedPaths); } - return v; - }; - - /** - * Declares a TTL index (rounded to the nearest second) for _Date_ types only. - * - * This sets the `expireAfterSeconds` index option available in MongoDB >= 2.1.2. - * This index type is only compatible with Date types. - * - * ####Example: - * - * // expire in 24 hours - * new Schema({ createdAt: { type: Date, expires: 60*60*24 }}); - * - * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax: - * - * ####Example: - * - * // expire in 24 hours - * new Schema({ createdAt: { type: Date, expires: '24h' }}); - * - * // expire in 1.5 hours - * new Schema({ createdAt: { type: Date, expires: '1.5h' }}); - * - * // expire in 7 days - * const schema = new Schema({ createdAt: Date }); - * schema.path('createdAt').expires('7d'); - * - * @param {Number|String} when - * @added 3.0.0 - * @return {SchemaType} this - * @api public - */ - - SchemaDate.prototype.expires = function (when) { - if (getConstructorName(this._index) !== "Object") { - this._index = {}; - } - - this._index.expires = when; - utils.expires(this._index); - return this; - }; - - /*! - * ignore - */ - - SchemaDate._checkRequired = (v) => v instanceof Date; - - /** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * ####Example: - * - * // Allow empty strings to pass `required` check - * mongoose.Schema.Types.String.checkRequired(v => v != null); - * - * const M = mongoose.model({ str: { type: String, required: true } }); - * new M({ str: '' }).validateSync(); // `null`, validation passes! - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - - SchemaDate.checkRequired = SchemaType.checkRequired; - - /** - * Check if the given value satisfies a required validator. To satisfy - * a required validator, the given value must be an instance of `Date`. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - - SchemaDate.prototype.checkRequired = function (value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - - // `require('util').inherits()` does **not** copy static properties, and - // plugins like mongoose-float use `inherits()` for pre-ES6. - const _checkRequired = - typeof this.constructor.checkRequired == "function" - ? this.constructor.checkRequired() - : SchemaDate.checkRequired(); - return _checkRequired(value); - }; + } + }); - /** - * Sets a minimum date validator. - * - * ####Example: - * - * const s = new Schema({ d: { type: Date, min: Date('1970-01-01') }) - * const M = db.model('M', s) - * const m = new M({ d: Date('1969-12-31') }) - * m.save(function (err) { - * console.error(err) // validator error - * m.d = Date('2014-12-08'); - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MIN} token which will be replaced with the invalid value - * const min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; - * const schema = new Schema({ d: { type: Date, min: min }) - * const M = mongoose.model('M', schema); - * const s= new M({ d: Date('1969-12-31') }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `d` (1969-12-31) is before the limit (1970-01-01). - * }) - * - * @param {Date} value minimum date - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - - SchemaDate.prototype.min = function (value, message) { - if (this.minValidator) { - this.validators = this.validators.filter(function (v) { - return v.validator !== this.minValidator; - }, this); - } + stack.pop(); + return addedPaths; + } - if (value) { - let msg = message || MongooseError.messages.Date.min; - if (typeof msg === "string") { - msg = msg.replace( - /{MIN}/, - value === Date.now ? "Date.now()" : value.toString() - ); - } - const _this = this; - this.validators.push({ - validator: (this.minValidator = function (val) { - let _value = value; - if (typeof value === "function" && value !== Date.now) { - _value = _value.call(this); - } - const min = _value === Date.now ? _value() : _this.cast(_value); - return val === null || val.valueOf() >= min.valueOf(); - }), - message: msg, - type: "min", - min: value, - }); - } + function analyzePath(path, type) { + const plusPath = '+' + path; + const hasPlusPath = fields && plusPath in fields; + if (hasPlusPath) { + // forced inclusion + delete fields[plusPath]; + } - return this; - }; + if (typeof type.selected !== 'boolean') return; - /** - * Sets a maximum date validator. - * - * ####Example: - * - * const s = new Schema({ d: { type: Date, max: Date('2014-01-01') }) - * const M = db.model('M', s) - * const m = new M({ d: Date('2014-12-08') }) - * m.save(function (err) { - * console.error(err) // validator error - * m.d = Date('2013-12-31'); - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MAX} token which will be replaced with the invalid value - * const max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; - * const schema = new Schema({ d: { type: Date, max: max }) - * const M = mongoose.model('M', schema); - * const s= new M({ d: Date('2014-12-08') }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `d` (2014-12-08) exceeds the limit (2014-01-01). - * }) - * - * @param {Date} maximum date - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - - SchemaDate.prototype.max = function (value, message) { - if (this.maxValidator) { - this.validators = this.validators.filter(function (v) { - return v.validator !== this.maxValidator; - }, this); - } + if (hasPlusPath) { + // forced inclusion + delete fields[plusPath]; - if (value) { - let msg = message || MongooseError.messages.Date.max; - if (typeof msg === "string") { - msg = msg.replace( - /{MAX}/, - value === Date.now ? "Date.now()" : value.toString() - ); - } - const _this = this; - this.validators.push({ - validator: (this.maxValidator = function (val) { - let _value = value; - if (typeof _value === "function" && _value !== Date.now) { - _value = _value.call(this); - } - const max = _value === Date.now ? _value() : _this.cast(_value); - return val === null || val.valueOf() <= max.valueOf(); - }), - message: msg, - type: "max", - max: value, - }); - } + // if there are other fields being included, add this one + // if no other included fields, leave this out (implied inclusion) + if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) { + fields[path] = 1; + } - return this; - }; + return; + } - /** - * Casts to date - * - * @param {Object} value to cast - * @api private - */ - - SchemaDate.prototype.cast = function (value) { - let castDate; - if (typeof this._castFunction === "function") { - castDate = this._castFunction; - } else if (typeof this.constructor.cast === "function") { - castDate = this.constructor.cast(); - } else { - castDate = SchemaDate.cast(); - } + // check for parent exclusions + const pieces = path.split('.'); + let cur = ''; + for (let i = 0; i < pieces.length; ++i) { + cur += cur.length ? '.' + pieces[i] : pieces[i]; + if (excluded.indexOf(cur) !== -1) { + return; + } + } - try { - return castDate(value); - } catch (error) { - throw new CastError("date", value, this.path, error, this); + // Special case: if user has included a parent path of a discriminator key, + // don't explicitly project in the discriminator key because that will + // project out everything else under the parent path + if (!exclude && get(type, 'options.$skipDiscriminatorCheck', false)) { + let cur = ''; + for (let i = 0; i < pieces.length; ++i) { + cur += (cur.length === 0 ? '' : '.') + pieces[i]; + const projection = get(fields, cur, false) || get(fields, cur + '.$', false); + if (projection && typeof projection !== 'object') { + return; } - }; + } + } - /*! - * Date Query casting. - * - * @api private - */ + (type.selected ? selected : excluded).push(path); + return path; + } +}; - function handleSingle(val) { - return this.cast(val); - } +/*! + * Set each path query option to lean + * + * @param {Object} option + */ - SchemaDate.prototype.$conditionalHandlers = utils.options( - SchemaType.prototype.$conditionalHandlers, - { - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle, - } - ); +function makeLean(val) { + return function(option) { + option.options || (option.options = {}); - /** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ + if (val != null && Array.isArray(val.virtuals)) { + val = Object.assign({}, val); + val.virtuals = val.virtuals. + filter(path => typeof path === 'string' && path.startsWith(option.path + '.')). + map(path => path.slice(option.path.length + 1)); + } - SchemaDate.prototype.castForQuery = function ($conditional, val) { - if (arguments.length !== 2) { - return this._castForQuery($conditional); - } + option.options.lean = val; + }; +} - const handler = this.$conditionalHandlers[$conditional]; +/*! + * Handle the `WriteOpResult` from the server + */ - if (!handler) { - throw new Error("Can't use " + $conditional + " with Date."); - } +exports.handleDeleteWriteOpResult = function handleDeleteWriteOpResult(callback) { + return function _handleDeleteWriteOpResult(error, res) { + if (error) { + return callback(error); + } + const mongooseResult = Object.assign({}, res.result); + if (get(res, 'result.n', null) != null) { + mongooseResult.deletedCount = res.result.n; + } + if (res.deletedCount != null) { + mongooseResult.deletedCount = res.deletedCount; + } + return callback(null, mongooseResult); + }; +}; - return handler.call(this, val); - }; - /*! - * Module exports. - */ +/***/ }), - module.exports = SchemaDate; +/***/ 7606: +/***/ ((module, exports, __nccwpck_require__) => { - /***/ - }, +"use strict"; - /***/ 8940: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ - - const SchemaType = __nccwpck_require__(5660); - const CastError = SchemaType.CastError; - const Decimal128Type = __nccwpck_require__(8319); - const castDecimal128 = __nccwpck_require__(8748); - const utils = __nccwpck_require__(9232); - - /** - * Decimal128 SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - - function Decimal128(key, options) { - SchemaType.call(this, key, options, "Decimal128"); - } - - /** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ - Decimal128.schemaName = "Decimal128"; - - Decimal128.defaultOptions = {}; - - /*! - * Inherits from SchemaType. - */ - Decimal128.prototype = Object.create(SchemaType.prototype); - Decimal128.prototype.constructor = Decimal128; - - /*! - * ignore - */ - - Decimal128._cast = castDecimal128; - - /** - * Sets a default option for all Decimal128 instances. - * - * ####Example: - * - * // Make all decimal 128s have `required` of true by default. - * mongoose.Schema.Decimal128.set('required', true); - * - * const User = mongoose.model('User', new Schema({ test: mongoose.Decimal128 })); - * new User({ }).validateSync().errors.test.message; // Path `test` is required. - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - - Decimal128.set = SchemaType.set; - - /** - * Get/set the function used to cast arbitrary values to decimals. - * - * ####Example: - * - * // Make Mongoose only refuse to cast numbers as decimal128 - * const original = mongoose.Schema.Types.Decimal128.cast(); - * mongoose.Decimal128.cast(v => { - * assert.ok(typeof v !== 'number'); - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.Decimal128.cast(false); - * - * @param {Function} [caster] - * @return {Function} - * @function get - * @static - * @api public - */ - - Decimal128.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = this._defaultCaster; - } - this._cast = caster; - - return this._cast; - }; - /*! - * ignore - */ +/*! + * Module dependencies. + */ - Decimal128._defaultCaster = (v) => { - if (v != null && !(v instanceof Decimal128Type)) { - throw new Error(); - } - return v; - }; +const EventEmitter = __nccwpck_require__(8614).EventEmitter; +const Kareem = __nccwpck_require__(716); +const MongooseError = __nccwpck_require__(5953); +const SchemaType = __nccwpck_require__(5660); +const SchemaTypeOptions = __nccwpck_require__(7544); +const VirtualOptions = __nccwpck_require__(5727); +const VirtualType = __nccwpck_require__(1423); +const addAutoId = __nccwpck_require__(9115); +const get = __nccwpck_require__(8730); +const getConstructorName = __nccwpck_require__(7323); +const getIndexes = __nccwpck_require__(8373); +const idGetter = __nccwpck_require__(895); +const merge = __nccwpck_require__(2830); +const mpath = __nccwpck_require__(8586); +const readPref = __nccwpck_require__(2324).get().ReadPreference; +const setupTimestamps = __nccwpck_require__(3151); +const utils = __nccwpck_require__(9232); +const validateRef = __nccwpck_require__(5458); + +let MongooseTypes; + +const queryHooks = __nccwpck_require__(7378).middlewareFunctions; +const documentHooks = __nccwpck_require__(5373).middlewareFunctions; +const hookNames = queryHooks.concat(documentHooks). + reduce((s, hook) => s.add(hook), new Set()); + +let id = 0; + +/** + * Schema constructor. + * + * ####Example: + * + * const child = new Schema({ name: String }); + * const schema = new Schema({ name: String, age: Number, children: [child] }); + * const Tree = mongoose.model('Tree', schema); + * + * // setting schema options + * new Schema({ name: String }, { _id: false, autoIndex: false }) + * + * ####Options: + * + * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option) + * - [autoCreate](/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option) + * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true + * - [bufferTimeoutMS](/docs/guide.html#bufferTimeoutMS): number - defaults to 10000 (10 seconds). If `bufferCommands` is enabled, the amount of time Mongoose will wait for connectivity to be restablished before erroring out. + * - [capped](/docs/guide.html#capped): bool - defaults to false + * - [collection](/docs/guide.html#collection): string - no default + * - [discriminatorKey](/docs/guide.html#discriminatorKey): string - defaults to `__t` + * - [id](/docs/guide.html#id): bool - defaults to true + * - [_id](/docs/guide.html#_id): bool - defaults to true + * - [minimize](/docs/guide.html#minimize): bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true + * - [read](/docs/guide.html#read): string + * - [writeConcern](/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://docs.mongodb.com/manual/reference/write-concern/) + * - [shardKey](/docs/guide.html#shardKey): object - defaults to `null` + * - [strict](/docs/guide.html#strict): bool - defaults to true + * - [strictQuery](/docs/guide.html#strictQuery): bool - defaults to false + * - [toJSON](/docs/guide.html#toJSON) - object - no default + * - [toObject](/docs/guide.html#toObject) - object - no default + * - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type' + * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true` + * - [versionKey](/docs/guide.html#versionKey): string or object - defaults to "__v" + * - [optimisticConcurrency](/docs/guide.html#optimisticConcurrency): bool - defaults to false. Set to true to enable [optimistic concurrency](https://thecodebarbarian.com/whats-new-in-mongoose-5-10-optimistic-concurrency.html). + * - [collation](/docs/guide.html#collation): object - defaults to null (which means use no collation) + * - [timeseries](/docs/guide.html#timeseries): object - defaults to null (which means this schema's collection won't be a timeseries collection) + * - [selectPopulatedPaths](/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true` + * - [skipVersioning](/docs/guide.html#skipVersioning): object - paths to exclude from versioning + * - [timestamps](/docs/guide.html#timestamps): object or boolean - defaults to `false`. If true, Mongoose adds `createdAt` and `updatedAt` properties to your schema and manages those properties for you. + * + * ####Options for Nested Schemas: + * - `excludeIndexes`: bool - defaults to `false`. If `true`, skip building indexes on this schema's paths. + * + * ####Note: + * + * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._ + * + * @param {Object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas + * @param {Object} [options] + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `init`: Emitted after the schema is compiled into a `Model`. + * @api public + */ - /*! - * ignore - */ - - Decimal128._checkRequired = (v) => v instanceof Decimal128Type; - - /** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - - Decimal128.checkRequired = SchemaType.checkRequired; - - /** - * Check if the given value satisfies a required validator. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - - Decimal128.prototype.checkRequired = function checkRequired(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - - // `require('util').inherits()` does **not** copy static properties, and - // plugins like mongoose-float use `inherits()` for pre-ES6. - const _checkRequired = - typeof this.constructor.checkRequired == "function" - ? this.constructor.checkRequired() - : Decimal128.checkRequired(); - - return _checkRequired(value); - }; +function Schema(obj, options) { + if (!(this instanceof Schema)) { + return new Schema(obj, options); + } - /** - * Casts to Decimal128 - * - * @param {Object} value - * @param {Object} doc - * @param {Boolean} init whether this is an initialization cast - * @api private - */ - - Decimal128.prototype.cast = function (value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - if (value instanceof Decimal128Type) { - return value; - } + this.obj = obj; + this.paths = {}; + this.aliases = {}; + this.subpaths = {}; + this.virtuals = {}; + this.singleNestedPaths = {}; + this.nested = {}; + this.inherits = {}; + this.callQueue = []; + this._indexes = []; + this.methods = {}; + this.methodOptions = {}; + this.statics = {}; + this.tree = {}; + this.query = {}; + this.childSchemas = []; + this.plugins = []; + // For internal debugging. Do not use this to try to save a schema in MDB. + this.$id = ++id; + this.mapPaths = []; + + this.s = { + hooks: new Kareem() + }; + this.options = this.defaultOptions(options); - return this._castRef(value, doc, init); - } + // build paths + if (Array.isArray(obj)) { + for (const definition of obj) { + this.add(definition); + } + } else if (obj) { + this.add(obj); + } - let castDecimal128; - if (typeof this._castFunction === "function") { - castDecimal128 = this._castFunction; - } else if (typeof this.constructor.cast === "function") { - castDecimal128 = this.constructor.cast(); - } else { - castDecimal128 = Decimal128.cast(); - } + // check if _id's value is a subdocument (gh-2276) + const _idSubDoc = obj && obj._id && utils.isObject(obj._id); - try { - return castDecimal128(value); - } catch (error) { - throw new CastError("Decimal128", value, this.path, error, this); - } - }; + // ensure the documents get an auto _id unless disabled + const auto_id = !this.paths['_id'] && + (this.options._id) && !_idSubDoc; - /*! - * ignore - */ + if (auto_id) { + addAutoId(this); + } - function handleSingle(val) { - return this.cast(val); - } + this.setupTimestamp(this.options.timestamps); +} - Decimal128.prototype.$conditionalHandlers = utils.options( - SchemaType.prototype.$conditionalHandlers, - { - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle, - } - ); +/*! + * Create virtual properties with alias field + */ +function aliasFields(schema, paths) { + paths = paths || Object.keys(schema.paths); + for (const path of paths) { + const options = get(schema.paths[path], 'options'); + if (options == null) { + continue; + } - /*! - * Module exports. - */ + const prop = schema.paths[path].path; + const alias = options.alias; - module.exports = Decimal128; + if (!alias) { + continue; + } - /***/ - }, + if (typeof alias !== 'string') { + throw new Error('Invalid value for alias option on ' + prop + ', got ' + alias); + } - /***/ 182: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const ArrayType = __nccwpck_require__(6090); - const CastError = __nccwpck_require__(2798); - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const SchemaDocumentArrayOptions = __nccwpck_require__(4508); - const SchemaType = __nccwpck_require__(5660); - const ValidationError = __nccwpck_require__(8460); - const discriminator = __nccwpck_require__(1462); - const get = __nccwpck_require__(8730); - const handleIdOption = __nccwpck_require__(8965); - const util = __nccwpck_require__(1669); - const utils = __nccwpck_require__(9232); - const getConstructor = __nccwpck_require__(1449); - - const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; - const arrayPathSymbol = __nccwpck_require__(3240).arrayPathSymbol; - const documentArrayParent = __nccwpck_require__(3240).documentArrayParent; - - let MongooseDocumentArray; - let Subdocument; - - /** - * SubdocsArray SchemaType constructor - * - * @param {String} key - * @param {Schema} schema - * @param {Object} options - * @inherits SchemaArray - * @api public - */ - - function DocumentArrayPath(key, schema, options, schemaOptions) { - if (schemaOptions != null && schemaOptions._id != null) { - schema = handleIdOption(schema, schemaOptions); - } else if (options != null && options._id != null) { - schema = handleIdOption(schema, options); - } - - const EmbeddedDocument = _createConstructor(schema, options); - EmbeddedDocument.prototype.$basePath = key; - - ArrayType.call(this, key, EmbeddedDocument, options); - - this.schema = schema; - this.schemaOptions = schemaOptions || {}; - this.$isMongooseDocumentArray = true; - this.Constructor = EmbeddedDocument; - - EmbeddedDocument.base = schema.base; - - const fn = this.defaultValue; - - if (!("defaultValue" in this) || fn !== void 0) { - this.default(function () { - let arr = fn.call(this); - if (!Array.isArray(arr)) { - arr = [arr]; - } - // Leave it up to `cast()` to convert this to a documentarray - return arr; - }); - } + schema.aliases[alias] = prop; - const parentSchemaType = this; - this.$embeddedSchemaType = new SchemaType(key + ".$", { - required: get(this, "schemaOptions.required", false), - }); - this.$embeddedSchemaType.cast = function (value, doc, init) { - return parentSchemaType.cast(value, doc, init)[0]; + schema. + virtual(alias). + get((function(p) { + return function() { + if (typeof this.get === 'function') { + return this.get(p); + } + return this[p]; }; - this.$embeddedSchemaType.$isMongooseDocumentArrayElement = true; - this.$embeddedSchemaType.caster = this.Constructor; - this.$embeddedSchemaType.schema = this.schema; - } - - /** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ - DocumentArrayPath.schemaName = "DocumentArray"; - - /** - * Options for all document arrays. - * - * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting. - * - * @api public - */ - - DocumentArrayPath.options = { castNonArrays: true }; - - /*! - * Inherits from ArrayType. - */ - DocumentArrayPath.prototype = Object.create(ArrayType.prototype); - DocumentArrayPath.prototype.constructor = DocumentArrayPath; - DocumentArrayPath.prototype.OptionsConstructor = - SchemaDocumentArrayOptions; - - /*! - * Ignore - */ - - function _createConstructor(schema, options, baseClass) { - Subdocument || (Subdocument = __nccwpck_require__(4433)); - - // compile an embedded document for this schema - function EmbeddedDocument() { - Subdocument.apply(this, arguments); - - this.$session(this.ownerDocument().$session()); - } - - const proto = - baseClass != null ? baseClass.prototype : Subdocument.prototype; - EmbeddedDocument.prototype = Object.create(proto); - EmbeddedDocument.prototype.$__setSchema(schema); - EmbeddedDocument.schema = schema; - EmbeddedDocument.prototype.constructor = EmbeddedDocument; - EmbeddedDocument.$isArraySubdocument = true; - EmbeddedDocument.events = new EventEmitter(); - - // apply methods - for (const i in schema.methods) { - EmbeddedDocument.prototype[i] = schema.methods[i]; - } - - // apply statics - for (const i in schema.statics) { - EmbeddedDocument[i] = schema.statics[i]; - } - - for (const i in EventEmitter.prototype) { - EmbeddedDocument[i] = EventEmitter.prototype[i]; - } - - EmbeddedDocument.options = options; - - return EmbeddedDocument; - } - - /** - * Adds a discriminator to this document array. - * - * ####Example: - * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' }); - * const schema = Schema({ shapes: [shapeSchema] }); - * - * const docArrayPath = parentSchema.path('shapes'); - * docArrayPath.discriminator('Circle', Schema({ radius: Number })); - * - * @param {String} name - * @param {Schema} schema fields to add to the schema for instances of this sub-class - * @param {String} [value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. - * @see discriminators /docs/discriminators.html - * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model - * @api public - */ - - DocumentArrayPath.prototype.discriminator = function ( - name, - schema, - tiedValue - ) { - if (typeof name === "function") { - name = utils.getFunctionName(name); - } - - schema = discriminator(this.casterConstructor, name, schema, tiedValue); - - const EmbeddedDocument = _createConstructor( - schema, - null, - this.casterConstructor - ); - EmbeddedDocument.baseCasterConstructor = this.casterConstructor; + })(prop)). + set((function(p) { + return function(v) { + return this.$set(p, v); + }; + })(prop)); + } +} - try { - Object.defineProperty(EmbeddedDocument, "name", { - value: name, - }); - } catch (error) { - // Ignore error, only happens on old versions of node - } +/*! + * Inherit from EventEmitter. + */ +Schema.prototype = Object.create(EventEmitter.prototype); +Schema.prototype.constructor = Schema; +Schema.prototype.instanceOfSchema = true; - this.casterConstructor.discriminators[name] = EmbeddedDocument; +/*! + * ignore + */ - return this.casterConstructor.discriminators[name]; - }; +Object.defineProperty(Schema.prototype, '$schemaType', { + configurable: false, + enumerable: false, + writable: true +}); - /** - * Performs local validations first, then validations on each embedded doc - * - * @api private - */ - - DocumentArrayPath.prototype.doValidate = function ( - array, - fn, - scope, - options - ) { - // lazy load - MongooseDocumentArray || - (MongooseDocumentArray = __nccwpck_require__(55)); +/** + * Array of child schemas (from document arrays and single nested subdocs) + * and their corresponding compiled models. Each element of the array is + * an object with 2 properties: `schema` and `model`. + * + * This property is typically only useful for plugin authors and advanced users. + * You do not need to interact with this property at all to use mongoose. + * + * @api public + * @property childSchemas + * @memberOf Schema + * @instance + */ - const _this = this; - try { - SchemaType.prototype.doValidate.call(this, array, cb, scope); - } catch (err) { - err.$isArrayValidatorError = true; - return fn(err); - } +Object.defineProperty(Schema.prototype, 'childSchemas', { + configurable: false, + enumerable: true, + writable: true +}); - function cb(err) { - if (err) { - err.$isArrayValidatorError = true; - return fn(err); - } +/** + * Object containing all virtuals defined on this schema. + * The objects' keys are the virtual paths and values are instances of `VirtualType`. + * + * This property is typically only useful for plugin authors and advanced users. + * You do not need to interact with this property at all to use mongoose. + * + * ####Example: + * const schema = new Schema({}); + * schema.virtual('answer').get(() => 42); + * + * console.log(schema.virtuals); // { answer: VirtualType { path: 'answer', ... } } + * console.log(schema.virtuals['answer'].getters[0].call()); // 42 + * + * @api public + * @property virtuals + * @memberOf Schema + * @instance + */ - let count = array && array.length; - let error; +Object.defineProperty(Schema.prototype, 'virtuals', { + configurable: false, + enumerable: true, + writable: true +}); - if (!count) { - return fn(); - } - if (options && options.updateValidator) { - return fn(); - } - if (!array.isMongooseDocumentArray) { - array = new MongooseDocumentArray(array, _this.path, scope); - } +/** + * The original object passed to the schema constructor + * + * ####Example: + * + * const schema = new Schema({ a: String }).add({ b: String }); + * schema.obj; // { a: String } + * + * @api public + * @property obj + * @memberOf Schema + * @instance + */ - // handle sparse arrays, do not use array.forEach which does not - // iterate over sparse elements yet reports array.length including - // them :( +Schema.prototype.obj; - function callback(err) { - if (err != null) { - error = err; - if (!(error instanceof ValidationError)) { - error.$isArrayValidatorError = true; - } - } - --count || fn(error); - } +/** + * The paths defined on this schema. The keys are the top-level paths + * in this schema, and the values are instances of the SchemaType class. + * + * ####Example: + * const schema = new Schema({ name: String }, { _id: false }); + * schema.paths; // { name: SchemaString { ... } } + * + * schema.add({ age: Number }); + * schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } } + * + * @api public + * @property paths + * @memberOf Schema + * @instance + */ - for (let i = 0, len = count; i < len; ++i) { - // sidestep sparse entries - let doc = array[i]; - if (doc == null) { - --count || fn(error); - continue; - } +Schema.prototype.paths; - // If you set the array index directly, the doc might not yet be - // a full fledged mongoose subdoc, so make it into one. - if (!(doc instanceof Subdocument)) { - const Constructor = getConstructor( - _this.casterConstructor, - array[i] - ); - doc = array[i] = new Constructor( - doc, - array, - undefined, - undefined, - i - ); - } +/** + * Schema as a tree + * + * ####Example: + * { + * '_id' : ObjectId + * , 'nested' : { + * 'key' : String + * } + * } + * + * @api private + * @property tree + * @memberOf Schema + * @instance + */ - if ( - options != null && - options.validateModifiedOnly && - !doc.isModified() - ) { - --count || fn(error); - continue; - } +Schema.prototype.tree; - doc.$__validate(callback); - } - } - }; +/** + * Returns a deep copy of the schema + * + * ####Example: + * + * const schema = new Schema({ name: String }); + * const clone = schema.clone(); + * clone === schema; // false + * clone.path('name'); // SchemaString { ... } + * + * @return {Schema} the cloned schema + * @api public + * @memberOf Schema + * @instance + */ - /** - * Performs local validations first, then validations on each embedded doc. - * - * ####Note: - * - * This method ignores the asynchronous validators. - * - * @return {MongooseError|undefined} - * @api private - */ - - DocumentArrayPath.prototype.doValidateSync = function ( - array, - scope, - options - ) { - const schemaTypeError = SchemaType.prototype.doValidateSync.call( - this, - array, - scope - ); - if (schemaTypeError != null) { - schemaTypeError.$isArrayValidatorError = true; - return schemaTypeError; - } +Schema.prototype.clone = function() { + const Constructor = this.base == null ? Schema : this.base.Schema; + + const s = new Constructor({}, this._userProvidedOptions); + s.base = this.base; + s.obj = this.obj; + s.options = utils.clone(this.options); + s.callQueue = this.callQueue.map(function(f) { return f; }); + s.methods = utils.clone(this.methods); + s.methodOptions = utils.clone(this.methodOptions); + s.statics = utils.clone(this.statics); + s.query = utils.clone(this.query); + s.plugins = Array.prototype.slice.call(this.plugins); + s._indexes = utils.clone(this._indexes); + s.s.hooks = this.s.hooks.clone(); + + s.tree = utils.clone(this.tree); + s.paths = utils.clone(this.paths); + s.nested = utils.clone(this.nested); + s.subpaths = utils.clone(this.subpaths); + s.singleNestedPaths = utils.clone(this.singleNestedPaths); + s.childSchemas = gatherChildSchemas(s); + + s.virtuals = utils.clone(this.virtuals); + s.$globalPluginsApplied = this.$globalPluginsApplied; + s.$isRootDiscriminator = this.$isRootDiscriminator; + s.$implicitlyCreated = this.$implicitlyCreated; + s.$id = ++id; + s.$originalSchemaId = this.$id; + s.mapPaths = [].concat(this.mapPaths); + + if (this.discriminatorMapping != null) { + s.discriminatorMapping = Object.assign({}, this.discriminatorMapping); + } + if (this.discriminators != null) { + s.discriminators = Object.assign({}, this.discriminators); + } - const count = array && array.length; - let resultError = null; + s.aliases = Object.assign({}, this.aliases); - if (!count) { - return; - } + // Bubble up `init` for backwards compat + s.on('init', v => this.emit('init', v)); - // handle sparse arrays, do not use array.forEach which does not - // iterate over sparse elements yet reports array.length including - // them :( + return s; +}; - for (let i = 0, len = count; i < len; ++i) { - // sidestep sparse entries - let doc = array[i]; - if (!doc) { - continue; - } +/** + * Returns a new schema that has the picked `paths` from this schema. + * + * This method is analagous to [Lodash's `pick()` function](https://lodash.com/docs/4.17.15#pick) for Mongoose schemas. + * + * ####Example: + * + * const schema = Schema({ name: String, age: Number }); + * // Creates a new schema with the same `name` path as `schema`, + * // but no `age` path. + * const newSchema = schema.pick(['name']); + * + * newSchema.path('name'); // SchemaString { ... } + * newSchema.path('age'); // undefined + * + * @param {Array} paths list of paths to pick + * @param {Object} [options] options to pass to the schema constructor. Defaults to `this.options` if not set. + * @return {Schema} + * @api public + */ - // If you set the array index directly, the doc might not yet be - // a full fledged mongoose subdoc, so make it into one. - if (!(doc instanceof Subdocument)) { - const Constructor = getConstructor( - this.casterConstructor, - array[i] - ); - doc = array[i] = new Constructor( - doc, - array, - undefined, - undefined, - i - ); - } +Schema.prototype.pick = function(paths, options) { + const newSchema = new Schema({}, options || this.options); + if (!Array.isArray(paths)) { + throw new MongooseError('Schema#pick() only accepts an array argument, ' + + 'got "' + typeof paths + '"'); + } - if ( - options != null && - options.validateModifiedOnly && - !doc.isModified() - ) { - continue; - } + for (const path of paths) { + if (this.nested[path]) { + newSchema.add({ [path]: get(this.tree, path) }); + } else { + const schematype = this.path(path); + if (schematype == null) { + throw new MongooseError('Path `' + path + '` is not in the schema'); + } + newSchema.add({ [path]: schematype }); + } + } - const subdocValidateError = doc.validateSync(); + return newSchema; +}; - if (subdocValidateError && resultError == null) { - resultError = subdocValidateError; - } - } +/** + * Returns default options for this schema, merged with `options`. + * + * @param {Object} options + * @return {Object} + * @api private + */ - return resultError; - }; +Schema.prototype.defaultOptions = function(options) { + this._userProvidedOptions = options == null ? {} : utils.clone(options); + const baseOptions = get(this, 'base.options', {}); + + const strict = 'strict' in baseOptions ? baseOptions.strict : true; + options = utils.options({ + strict: strict, + strictQuery: 'strict' in this._userProvidedOptions ? + this._userProvidedOptions.strict : + 'strictQuery' in baseOptions ? + baseOptions.strictQuery : strict, + bufferCommands: true, + capped: false, // { size, max, autoIndexId } + versionKey: '__v', + optimisticConcurrency: false, + minimize: true, + autoIndex: null, + discriminatorKey: '__t', + shardKey: null, + read: null, + validateBeforeSave: true, + // the following are only applied at construction time + _id: true, + id: true, + typeKey: 'type' + }, utils.clone(options)); + + if (options.read) { + options.read = readPref(options.read); + } + + if (options.versionKey && typeof options.versionKey !== 'string') { + throw new MongooseError('`versionKey` must be falsy or string, got `' + (typeof options.versionKey) + '`'); + } - /*! - * ignore - */ + if (options.optimisticConcurrency && !options.versionKey) { + throw new MongooseError('Must set `versionKey` if using `optimisticConcurrency`'); + } - DocumentArrayPath.prototype.getDefault = function (scope) { - let ret = - typeof this.defaultValue === "function" - ? this.defaultValue.call(scope) - : this.defaultValue; + return options; +}; - if (ret == null) { - return ret; - } +/** + * Adds key path / schema type pairs to this schema. + * + * ####Example: + * + * const ToySchema = new Schema(); + * ToySchema.add({ name: 'string', color: 'string', price: 'number' }); + * + * const TurboManSchema = new Schema(); + * // You can also `add()` another schema and copy over all paths, virtuals, + * // getters, setters, indexes, methods, and statics. + * TurboManSchema.add(ToySchema).add({ year: Number }); + * + * @param {Object|Schema} obj plain object with paths to add, or another schema + * @param {String} [prefix] path to prefix the newly added paths with + * @return {Schema} the Schema instance + * @api public + */ - // lazy load - MongooseDocumentArray || - (MongooseDocumentArray = __nccwpck_require__(55)); +Schema.prototype.add = function add(obj, prefix) { + if (obj instanceof Schema || (obj != null && obj.instanceOfSchema)) { + merge(this, obj); - if (!Array.isArray(ret)) { - ret = [ret]; - } + return this; + } - ret = new MongooseDocumentArray(ret, this.path, scope); + // Special case: setting top-level `_id` to false should convert to disabling + // the `_id` option. This behavior never worked before 5.4.11 but numerous + // codebases use it (see gh-7516, gh-7512). + if (obj._id === false && prefix == null) { + this.options._id = false; + } - for (let i = 0; i < ret.length; ++i) { - const Constructor = getConstructor(this.casterConstructor, ret[i]); - const _subdoc = new Constructor({}, ret, undefined, undefined, i); - _subdoc.init(ret[i]); - _subdoc.isNew = true; + prefix = prefix || ''; + // avoid prototype pollution + if (prefix === '__proto__.' || prefix === 'constructor.' || prefix === 'prototype.') { + return this; + } - // Make sure all paths in the subdoc are set to `default` instead - // of `init` since we used `init`. - Object.assign( - _subdoc.$__.activePaths.default, - _subdoc.$__.activePaths.init - ); - _subdoc.$__.activePaths.init = {}; + const keys = Object.keys(obj); - ret[i] = _subdoc; - } + for (const key of keys) { + const fullPath = prefix + key; - return ret; - }; + if (obj[key] == null) { + throw new TypeError('Invalid value for schema path `' + fullPath + + '`, got value "' + obj[key] + '"'); + } + // Retain `_id: false` but don't set it as a path, re: gh-8274. + if (key === '_id' && obj[key] === false) { + continue; + } + if (obj[key] instanceof VirtualType || get(obj[key], 'constructor.name', null) === 'VirtualType') { + this.virtual(obj[key]); + continue; + } - /** - * Casts contents - * - * @param {Object} value - * @param {Document} document that triggers the casting - * @api private - */ - - DocumentArrayPath.prototype.cast = function ( - value, - doc, - init, - prev, - options - ) { - // lazy load - MongooseDocumentArray || - (MongooseDocumentArray = __nccwpck_require__(55)); - - // Skip casting if `value` is the same as the previous value, no need to cast. See gh-9266 - if (value != null && value[arrayPathSymbol] != null && value === prev) { - return value; + if (Array.isArray(obj[key]) && obj[key].length === 1 && obj[key][0] == null) { + throw new TypeError('Invalid value for schema Array path `' + fullPath + + '`, got value "' + obj[key][0] + '"'); + } + + if (!(utils.isPOJO(obj[key]) || obj[key] instanceof SchemaTypeOptions)) { + // Special-case: Non-options definitely a path so leaf at this node + // Examples: Schema instances, SchemaType instances + if (prefix) { + this.nested[prefix.substr(0, prefix.length - 1)] = true; + } + this.path(prefix + key, obj[key]); + } else if (Object.keys(obj[key]).length < 1) { + // Special-case: {} always interpreted as Mixed path so leaf at this node + if (prefix) { + this.nested[prefix.substr(0, prefix.length - 1)] = true; + } + this.path(fullPath, obj[key]); // mixed type + } else if (!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && !(obj[key].type instanceof Function) && obj[key].type.type)) { + // Special-case: POJO with no bona-fide type key - interpret as tree of deep paths so recurse + // nested object `{ last: { name: String } }`. Avoid functions with `.type` re: #10807 because + // NestJS sometimes adds `Date.type`. + this.nested[fullPath] = true; + this.add(obj[key], fullPath + '.'); + } else { + // There IS a bona-fide type key that may also be a POJO + const _typeDef = obj[key][this.options.typeKey]; + if (utils.isPOJO(_typeDef) && Object.keys(_typeDef).length > 0) { + // If a POJO is the value of a type key, make it a subdocument + if (prefix) { + this.nested[prefix.substr(0, prefix.length - 1)] = true; + } + const _schema = new Schema(_typeDef); + const schemaWrappedPath = Object.assign({}, obj[key], { type: _schema }); + this.path(prefix + key, schemaWrappedPath); + } else { + // Either the type is non-POJO or we interpret it as Mixed anyway + if (prefix) { + this.nested[prefix.substr(0, prefix.length - 1)] = true; } + this.path(prefix + key, obj[key]); + } + } + } - let selected; - let subdoc; - const _opts = { transform: false, virtuals: false }; - options = options || {}; + const addedKeys = Object.keys(obj). + map(key => prefix ? prefix + key : key); + aliasFields(this, addedKeys); + return this; +}; - if (!Array.isArray(value)) { - if (!init && !DocumentArrayPath.options.castNonArrays) { - throw new CastError( - "DocumentArray", - util.inspect(value), - this.path, - null, - this - ); - } - // gh-2442 mark whole array as modified if we're initializing a doc from - // the db and the path isn't an array in the document - if (!!doc && init) { - doc.markModified(this.path); - } - return this.cast([value], doc, init, prev, options); - } +/** + * Reserved document keys. + * + * Keys in this object are names that are warned in schema declarations + * because they have the potential to break Mongoose/ Mongoose plugins functionality. If you create a schema + * using `new Schema()` with one of these property names, Mongoose will log a warning. + * + * - _posts + * - _pres + * - collection + * - emit + * - errors + * - get + * - init + * - isModified + * - isNew + * - listeners + * - modelName + * - on + * - once + * - populated + * - prototype + * - remove + * - removeListener + * - save + * - schema + * - toObject + * - validate + * + * _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on. + * + * const schema = new Schema(..); + * schema.methods.init = function () {} // potentially breaking + */ - if ( - !(value && value.isMongooseDocumentArray) && - !options.skipDocumentArrayCast - ) { - value = new MongooseDocumentArray(value, this.path, doc); - } else if (value && value.isMongooseDocumentArray) { - // We need to create a new array, otherwise change tracking will - // update the old doc (gh-4449) - value = new MongooseDocumentArray(value, this.path, doc); - } +Schema.reserved = Object.create(null); +Schema.prototype.reserved = Schema.reserved; + +const reserved = Schema.reserved; +// Core object +reserved['prototype'] = +// EventEmitter +reserved.emit = +reserved.listeners = +reserved.on = +reserved.removeListener = + +// document properties and functions +reserved.collection = +reserved.errors = +reserved.get = +reserved.init = +reserved.isModified = +reserved.isNew = +reserved.populated = +reserved.remove = +reserved.save = +reserved.toObject = +reserved.validate = 1; +reserved.collection = 1; + +/** + * Gets/sets schema paths. + * + * Sets a path (if arity 2) + * Gets a path (if arity 1) + * + * ####Example + * + * schema.path('name') // returns a SchemaType + * schema.path('name', Number) // changes the schemaType of `name` to Number + * + * @param {String} path + * @param {Object} constructor + * @api public + */ - if (prev != null) { - value[arrayAtomicsSymbol] = prev[arrayAtomicsSymbol] || {}; - } +Schema.prototype.path = function(path, obj) { + // Convert to '.$' to check subpaths re: gh-6405 + const cleanPath = _pathToPositionalSyntax(path); + if (obj === undefined) { + let schematype = _getPath(this, path, cleanPath); + if (schematype != null) { + return schematype; + } - if (options.arrayPathIndex != null) { - value[arrayPathSymbol] = this.path + "." + options.arrayPathIndex; - } + // Look for maps + const mapPath = getMapPath(this, path); + if (mapPath != null) { + return mapPath; + } - const len = value.length; - const initDocumentOptions = { skipId: true, willInit: true }; + // Look if a parent of this path is mixed + schematype = this.hasMixedParent(cleanPath); + if (schematype != null) { + return schematype; + } - for (let i = 0; i < len; ++i) { - if (!value[i]) { - continue; - } + // subpaths? + return /\.\d+\.?.*$/.test(path) + ? getPositionalPath(this, path) + : undefined; + } - const Constructor = getConstructor(this.casterConstructor, value[i]); - - // Check if the document has a different schema (re gh-3701) - if ( - value[i].$__ && - (!(value[i] instanceof Constructor) || - value[i][documentArrayParent] !== doc) - ) { - value[i] = value[i].toObject({ - transform: false, - // Special case: if different model, but same schema, apply virtuals - // re: gh-7898 - virtuals: value[i].schema === Constructor.schema, - }); - } + // some path names conflict with document methods + const firstPieceOfPath = path.split('.')[0]; + if (reserved[firstPieceOfPath] && !this.options.supressReservedKeysWarning) { + const errorMessage = `\`${firstPieceOfPath}\` is a reserved schema pathname and may break some functionality. ` + + 'You are allowed to use it, but use at your own risk. ' + + 'To disable this warning pass `supressReservedKeysWarning` as a schema option.'; - if (value[i] instanceof Subdocument) { - // Might not have the correct index yet, so ensure it does. - if (value[i].__index == null) { - value[i].$setIndex(i); - } - } else if (value[i] != null) { - if (init) { - if (doc) { - selected || - (selected = scopePaths(this, doc.$__.selected, init)); - } else { - selected = true; - } + utils.warn(errorMessage); + } - subdoc = new Constructor( - null, - value, - initDocumentOptions, - selected, - i - ); - value[i] = subdoc.init(value[i]); - } else { - if (prev && typeof prev.id === "function") { - subdoc = prev.id(value[i]._id); - } + if (typeof obj === 'object' && utils.hasUserDefinedProperty(obj, 'ref')) { + validateRef(obj.ref, path); + } - if ( - prev && - subdoc && - utils.deepEqual(subdoc.toObject(_opts), value[i]) - ) { - // handle resetting doc with existing id and same data - subdoc.set(value[i]); - // if set() is hooked it will have no return value - // see gh-746 - value[i] = subdoc; - } else { - try { - subdoc = new Constructor( - value[i], - value, - undefined, - undefined, - i - ); - // if set() is hooked it will have no return value - // see gh-746 - value[i] = subdoc; - } catch (error) { - const valueInErrorMessage = util.inspect(value[i]); - throw new CastError( - "embedded", - valueInErrorMessage, - value[arrayPathSymbol], - error, - this - ); - } - } - } - } - } + // update the tree + const subpaths = path.split(/\./); + const last = subpaths.pop(); + let branch = this.tree; + let fullPath = ''; + + for (const sub of subpaths) { + fullPath = fullPath += (fullPath.length > 0 ? '.' : '') + sub; + if (!branch[sub]) { + this.nested[fullPath] = true; + branch[sub] = {}; + } + if (typeof branch[sub] !== 'object') { + const msg = 'Cannot set nested path `' + path + '`. ' + + 'Parent path `' + + fullPath + + '` already set to type ' + branch[sub].name + + '.'; + throw new Error(msg); + } + branch = branch[sub]; + } - return value; - }; + branch[last] = utils.clone(obj); - /*! - * ignore - */ - - DocumentArrayPath.prototype.clone = function () { - const options = Object.assign({}, this.options); - const schematype = new this.constructor( - this.path, - this.schema, - options, - this.schemaOptions - ); - schematype.validators = this.validators.slice(); - if (this.requiredValidator !== undefined) { - schematype.requiredValidator = this.requiredValidator; - } - schematype.Constructor.discriminators = Object.assign( - {}, - this.Constructor.discriminators - ); - return schematype; - }; + this.paths[path] = this.interpretAsType(path, obj, this.options); + const schemaType = this.paths[path]; - /*! - * ignore - */ + if (schemaType.$isSchemaMap) { + // Maps can have arbitrary keys, so `$*` is internal shorthand for "any key" + // The '$' is to imply this path should never be stored in MongoDB so we + // can easily build a regexp out of this path, and '*' to imply "any key." + const mapPath = path + '.$*'; - DocumentArrayPath.prototype.applyGetters = function (value, scope) { - return SchemaType.prototype.applyGetters.call(this, value, scope); - }; + this.paths[mapPath] = schemaType.$__schemaType; + this.mapPaths.push(this.paths[mapPath]); + } - /*! - * Scopes paths selected in a query to this array. - * Necessary for proper default application of subdocument values. - * - * @param {DocumentArrayPath} array - the array to scope `fields` paths - * @param {Object|undefined} fields - the root fields selected in the query - * @param {Boolean|undefined} init - if we are being created part of a query result - */ - - function scopePaths(array, fields, init) { - if (!(init && fields)) { - return undefined; - } - - const path = array.path + "."; - const keys = Object.keys(fields); - let i = keys.length; - const selected = {}; - let hasKeys; - let key; - let sub; - - while (i--) { - key = keys[i]; - if (key.startsWith(path)) { - sub = key.substring(path.length); - if (sub === "$") { - continue; - } - if (sub.startsWith("$.")) { - sub = sub.substr(2); - } - hasKeys || (hasKeys = true); - selected[sub] = fields[key]; - } - } + if (schemaType.$isSingleNested) { + for (const key of Object.keys(schemaType.schema.paths)) { + this.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key]; + } + for (const key of Object.keys(schemaType.schema.singleNestedPaths)) { + this.singleNestedPaths[path + '.' + key] = + schemaType.schema.singleNestedPaths[key]; + } + for (const key of Object.keys(schemaType.schema.subpaths)) { + this.singleNestedPaths[path + '.' + key] = + schemaType.schema.subpaths[key]; + } + for (const key of Object.keys(schemaType.schema.nested)) { + this.singleNestedPaths[path + '.' + key] = 'nested'; + } - return (hasKeys && selected) || undefined; - } + Object.defineProperty(schemaType.schema, 'base', { + configurable: true, + enumerable: false, + writable: false, + value: this.base + }); - /** - * Sets a default option for all DocumentArray instances. - * - * ####Example: - * - * // Make all numbers have option `min` equal to 0. - * mongoose.Schema.DocumentArray.set('_id', false); - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ + schemaType.caster.base = this.base; + this.childSchemas.push({ + schema: schemaType.schema, + model: schemaType.caster + }); + } else if (schemaType.$isMongooseDocumentArray) { + Object.defineProperty(schemaType.schema, 'base', { + configurable: true, + enumerable: false, + writable: false, + value: this.base + }); - DocumentArrayPath.defaultOptions = {}; + schemaType.casterConstructor.base = this.base; + this.childSchemas.push({ + schema: schemaType.schema, + model: schemaType.casterConstructor + }); + } - DocumentArrayPath.set = SchemaType.set; + if (schemaType.$isMongooseArray && schemaType.caster instanceof SchemaType) { + let arrayPath = path; + let _schemaType = schemaType; - /*! - * Module exports. - */ + const toAdd = []; + while (_schemaType.$isMongooseArray) { + arrayPath = arrayPath + '.$'; - module.exports = DocumentArrayPath; + // Skip arrays of document arrays + if (_schemaType.$isMongooseDocumentArray) { + _schemaType.$embeddedSchemaType._arrayPath = arrayPath; + _schemaType.$embeddedSchemaType._arrayParentPath = path; + _schemaType = _schemaType.$embeddedSchemaType.clone(); + } else { + _schemaType.caster._arrayPath = arrayPath; + _schemaType.caster._arrayParentPath = path; + _schemaType = _schemaType.caster.clone(); + } - /***/ - }, + _schemaType.path = arrayPath; + toAdd.push(_schemaType); + } - /***/ 2987: /***/ ( - __unused_webpack_module, - exports, - __nccwpck_require__ - ) => { - "use strict"; + for (const _schemaType of toAdd) { + this.subpaths[_schemaType.path] = _schemaType; + } + } - /*! - * Module exports. - */ + if (schemaType.$isMongooseDocumentArray) { + for (const key of Object.keys(schemaType.schema.paths)) { + const _schemaType = schemaType.schema.paths[key]; + this.subpaths[path + '.' + key] = _schemaType; + if (typeof _schemaType === 'object' && _schemaType != null) { + _schemaType.$isUnderneathDocArray = true; + } + } + for (const key of Object.keys(schemaType.schema.subpaths)) { + const _schemaType = schemaType.schema.subpaths[key]; + this.subpaths[path + '.' + key] = _schemaType; + if (typeof _schemaType === 'object' && _schemaType != null) { + _schemaType.$isUnderneathDocArray = true; + } + } + for (const key of Object.keys(schemaType.schema.singleNestedPaths)) { + const _schemaType = schemaType.schema.singleNestedPaths[key]; + this.subpaths[path + '.' + key] = _schemaType; + if (typeof _schemaType === 'object' && _schemaType != null) { + _schemaType.$isUnderneathDocArray = true; + } + } + } - exports.String = __nccwpck_require__(7451); + return this; +}; - exports.Number = __nccwpck_require__(188); +/*! + * ignore + */ - exports.Boolean = __nccwpck_require__(2900); +function gatherChildSchemas(schema) { + const childSchemas = []; - exports.DocumentArray = __nccwpck_require__(182); + for (const path of Object.keys(schema.paths)) { + const schematype = schema.paths[path]; + if (schematype.$isMongooseDocumentArray || schematype.$isSingleNested) { + childSchemas.push({ schema: schematype.schema, model: schematype.caster }); + } + } - exports.Embedded = __nccwpck_require__(4257); + return childSchemas; +} - exports.Array = __nccwpck_require__(6090); +/*! + * ignore + */ - exports.Buffer = __nccwpck_require__(4798); +function _getPath(schema, path, cleanPath) { + if (schema.paths.hasOwnProperty(path)) { + return schema.paths[path]; + } + if (schema.subpaths.hasOwnProperty(cleanPath)) { + return schema.subpaths[cleanPath]; + } + if (schema.singleNestedPaths.hasOwnProperty(cleanPath) && typeof schema.singleNestedPaths[cleanPath] === 'object') { + return schema.singleNestedPaths[cleanPath]; + } - exports.Date = __nccwpck_require__(9140); + return null; +} - exports.ObjectId = __nccwpck_require__(9259); +/*! + * ignore + */ - exports.Mixed = __nccwpck_require__(7495); +function _pathToPositionalSyntax(path) { + if (!/\.\d+/.test(path)) { + return path; + } + return path.replace(/\.\d+\./g, '.$.').replace(/\.\d+$/, '.$'); +} - exports.Decimal128 = exports.Decimal = __nccwpck_require__(8940); +/*! + * ignore + */ - exports.Map = __nccwpck_require__(2370); +function getMapPath(schema, path) { + if (schema.mapPaths.length === 0) { + return null; + } + for (const val of schema.mapPaths) { + const _path = val.path; + const re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$'); + if (re.test(path)) { + return schema.paths[_path]; + } + } - // alias + return null; +} - exports.Oid = exports.ObjectId; - exports.Object = exports.Mixed; - exports.Bool = exports.Boolean; - exports.ObjectID = exports.ObjectId; +/** + * The Mongoose instance this schema is associated with + * + * @property base + * @api private + */ - /***/ - }, +Object.defineProperty(Schema.prototype, 'base', { + configurable: true, + enumerable: false, + writable: true, + value: null +}); - /***/ 2370: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +/** + * Converts type arguments into Mongoose Types. + * + * @param {String} path + * @param {Object} obj constructor + * @api private + */ - /*! - * ignore - */ +Schema.prototype.interpretAsType = function(path, obj, options) { + if (obj instanceof SchemaType) { + if (obj.path === path) { + return obj; + } + const clone = obj.clone(); + clone.path = path; + return clone; + } - const MongooseMap = __nccwpck_require__(9390); - const SchemaMapOptions = __nccwpck_require__(2809); - const SchemaType = __nccwpck_require__(5660); - /*! - * ignore - */ + // If this schema has an associated Mongoose object, use the Mongoose object's + // copy of SchemaTypes re: gh-7158 gh-6933 + const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types; - class Map extends SchemaType { - constructor(key, options) { - super(key, options, "Map"); - this.$isSchemaMap = true; - } + if (!utils.isPOJO(obj) && !(obj instanceof SchemaTypeOptions)) { + const constructorName = utils.getFunctionName(obj.constructor); + if (constructorName !== 'Object') { + const oldObj = obj; + obj = {}; + obj[options.typeKey] = oldObj; + } + } - set(option, value) { - return SchemaType.set(option, value); - } + // Get the type making sure to allow keys named "type" + // and default to mixed if not specified. + // { type: { type: String, default: 'freshcut' } } + let type = obj[options.typeKey] && (obj[options.typeKey] instanceof Function || options.typeKey !== 'type' || !obj.type.type) + ? obj[options.typeKey] + : {}; + let name; - cast(val, doc, init) { - if (val instanceof MongooseMap) { - return val; - } + if (utils.isPOJO(type) || type === 'mixed') { + return new MongooseTypes.Mixed(path, obj); + } - const path = this.path; + if (Array.isArray(type) || type === Array || type === 'array' || type === MongooseTypes.Array) { + // if it was specified through { type } look for `cast` + let cast = (type === Array || type === 'array') + ? obj.cast || obj.of + : type[0]; - if (init) { - const map = new MongooseMap({}, path, doc, this.$__schemaType); + // new Schema({ path: [new Schema({ ... })] }) + if (cast && cast.instanceOfSchema) { + if (!(cast instanceof Schema)) { + throw new TypeError('Schema for array path `' + path + + '` is from a different copy of the Mongoose module. Please make sure you\'re using the same version ' + + 'of Mongoose everywhere with `npm list mongoose`.'); + } + return new MongooseTypes.DocumentArray(path, cast, obj); + } + if (cast && + cast[options.typeKey] && + cast[options.typeKey].instanceOfSchema) { + if (!(cast[options.typeKey] instanceof Schema)) { + throw new TypeError('Schema for array path `' + path + + '` is from a different copy of the Mongoose module. Please make sure you\'re using the same version ' + + 'of Mongoose everywhere with `npm list mongoose`.'); + } + return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast); + } - if (val instanceof global.Map) { - for (const key of val.keys()) { - let _val = val.get(key); - if (_val == null) { - _val = map.$__schemaType._castNullish(_val); - } else { - _val = map.$__schemaType.cast(_val, doc, true, null, { - path: path + "." + key, - }); - } - map.$init(key, _val); - } - } else { - for (const key of Object.keys(val)) { - let _val = val[key]; - if (_val == null) { - _val = map.$__schemaType._castNullish(_val); - } else { - _val = map.$__schemaType.cast(_val, doc, true, null, { - path: path + "." + key, - }); - } - map.$init(key, _val); - } - } + if (Array.isArray(cast)) { + return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj); + } - return map; - } + // Handle both `new Schema({ arr: [{ subpath: String }] })` and `new Schema({ arr: [{ type: { subpath: string } }] })` + const castFromTypeKey = (cast != null && cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type)) ? + cast[options.typeKey] : + cast; + if (typeof cast === 'string') { + cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)]; + } else if (utils.isPOJO(castFromTypeKey)) { + if (Object.keys(castFromTypeKey).length) { + // The `minimize` and `typeKey` options propagate to child schemas + // declared inline, like `{ arr: [{ val: { $type: String } }] }`. + // See gh-3560 + const childSchemaOptions = { minimize: options.minimize }; + if (options.typeKey) { + childSchemaOptions.typeKey = options.typeKey; + } + // propagate 'strict' option to child schema + if (options.hasOwnProperty('strict')) { + childSchemaOptions.strict = options.strict; + } + if (this._userProvidedOptions.hasOwnProperty('_id')) { + childSchemaOptions._id = this._userProvidedOptions._id; + } else if (Schema.Types.DocumentArray.defaultOptions._id != null) { + childSchemaOptions._id = Schema.Types.DocumentArray.defaultOptions._id; + } + const childSchema = new Schema(castFromTypeKey, childSchemaOptions); + childSchema.$implicitlyCreated = true; + return new MongooseTypes.DocumentArray(path, childSchema, obj); + } else { + // Special case: empty object becomes mixed + return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj); + } + } - return new MongooseMap(val, path, doc, this.$__schemaType); - } + if (cast) { + type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type) + ? cast[options.typeKey] + : cast; - clone() { - const schematype = super.clone(); + name = typeof type === 'string' + ? type + : type.schemaName || utils.getFunctionName(type); - if (this.$__schemaType != null) { - schematype.$__schemaType = this.$__schemaType.clone(); - } - return schematype; - } + // For Jest 26+, see #10296 + if (name === 'ClockDate') { + name = 'Date'; } - Map.prototype.OptionsConstructor = SchemaMapOptions; + if (name === void 0) { + throw new TypeError('Invalid schema configuration: ' + + `Could not determine the embedded type for array \`${path}\`. ` + + 'See https://mongoosejs.com/docs/guide.html#definition for more info on supported schema syntaxes.'); + } + if (!MongooseTypes.hasOwnProperty(name)) { + throw new TypeError('Invalid schema configuration: ' + + `\`${name}\` is not a valid type within the array \`${path}\`.` + + 'See http://bit.ly/mongoose-schematypes for a list of valid schema types.'); + } + } - Map.defaultOptions = {}; + return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options); + } - module.exports = Map; + if (type && type.instanceOfSchema) { + return new MongooseTypes.Subdocument(type, path, obj); + } - /***/ - }, + if (Buffer.isBuffer(type)) { + name = 'Buffer'; + } else if (typeof type === 'function' || typeof type === 'object') { + name = type.schemaName || utils.getFunctionName(type); + } else { + name = type == null ? '' + type : type.toString(); + } - /***/ 7495: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ - - const SchemaType = __nccwpck_require__(5660); - const symbols = __nccwpck_require__(1205); - const isObject = __nccwpck_require__(273); - const utils = __nccwpck_require__(9232); - - /** - * Mixed SchemaType constructor. - * - * @param {String} path - * @param {Object} options - * @inherits SchemaType - * @api public - */ - - function Mixed(path, options) { - if (options && options.default) { - const def = options.default; - if (Array.isArray(def) && def.length === 0) { - // make sure empty array defaults are handled - options.default = Array; - } else if ( - !options.shared && - isObject(def) && - Object.keys(def).length === 0 - ) { - // prevent odd "shared" objects between documents - options.default = function () { - return {}; - }; - } - } + if (name) { + name = name.charAt(0).toUpperCase() + name.substring(1); + } + // Special case re: gh-7049 because the bson `ObjectID` class' capitalization + // doesn't line up with Mongoose's. + if (name === 'ObjectID') { + name = 'ObjectId'; + } + // For Jest 26+, see #10296 + if (name === 'ClockDate') { + name = 'Date'; + } - SchemaType.call(this, path, options, "Mixed"); - - this[symbols.schemaMixedSymbol] = true; - } - - /** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ - Mixed.schemaName = "Mixed"; - - Mixed.defaultOptions = {}; - - /*! - * Inherits from SchemaType. - */ - Mixed.prototype = Object.create(SchemaType.prototype); - Mixed.prototype.constructor = Mixed; - - /** - * Attaches a getter for all Mixed paths. - * - * ####Example: - * - * // Hide the 'hidden' path - * mongoose.Schema.Mixed.get(v => Object.assign({}, v, { hidden: null })); - * - * const Model = mongoose.model('Test', new Schema({ test: {} })); - * new Model({ test: { hidden: 'Secret!' } }).test.hidden; // null - * - * @param {Function} getter - * @return {this} - * @function get - * @static - * @api public - */ - - Mixed.get = SchemaType.get; - - /** - * Sets a default option for all Mixed instances. - * - * ####Example: - * - * // Make all mixed instances have `required` of true by default. - * mongoose.Schema.Mixed.set('required', true); - * - * const User = mongoose.model('User', new Schema({ test: mongoose.Mixed })); - * new User({ }).validateSync().errors.test.message; // Path `test` is required. - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - - Mixed.set = SchemaType.set; - - /** - * Casts `val` for Mixed. - * - * _this is a no-op_ - * - * @param {Object} value to cast - * @api private - */ - - Mixed.prototype.cast = function (val) { - if (val instanceof Error) { - return utils.errorToPOJO(val); - } - return val; - }; + if (name === void 0) { + throw new TypeError(`Invalid schema configuration: \`${path}\` schematype definition is ` + + 'invalid. See ' + + 'https://mongoosejs.com/docs/guide.html#definition for more info on supported schema syntaxes.'); + } + if (MongooseTypes[name] == null) { + throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` + + `a valid type at path \`${path}\`. See ` + + 'http://bit.ly/mongoose-schematypes for a list of valid schema types.'); + } - /** - * Casts contents for queries. - * - * @param {String} $cond - * @param {any} [val] - * @api private - */ + const schemaType = new MongooseTypes[name](path, obj); - Mixed.prototype.castForQuery = function ($cond, val) { - if (arguments.length === 2) { - return val; - } - return $cond; - }; + if (schemaType.$isSchemaMap) { + createMapNestedSchemaType(this, schemaType, path, obj, options); + } - /*! - * Module exports. - */ + return schemaType; +}; - module.exports = Mixed; +/*! + * ignore + */ - /***/ - }, +function createMapNestedSchemaType(schema, schemaType, path, obj, options) { + const mapPath = path + '.$*'; + let _mapType = { type: {} }; + if (utils.hasUserDefinedProperty(obj, 'of')) { + const isInlineSchema = utils.isPOJO(obj.of) && + Object.keys(obj.of).length > 0 && + !utils.hasUserDefinedProperty(obj.of, schema.options.typeKey); + if (isInlineSchema) { + _mapType = { [schema.options.typeKey]: new Schema(obj.of) }; + } else if (utils.isPOJO(obj.of)) { + _mapType = Object.assign({}, obj.of); + } else { + _mapType = { [schema.options.typeKey]: obj.of }; + } - /***/ 188: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module requirements. - */ - - const MongooseError = __nccwpck_require__(4327); - const SchemaNumberOptions = __nccwpck_require__(1079); - const SchemaType = __nccwpck_require__(5660); - const castNumber = __nccwpck_require__(1582); - const handleBitwiseOperator = __nccwpck_require__(9547); - const utils = __nccwpck_require__(9232); - - const CastError = SchemaType.CastError; - - /** - * Number SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - - function SchemaNumber(key, options) { - SchemaType.call(this, key, options, "Number"); - } - - /** - * Attaches a getter for all Number instances. - * - * ####Example: - * - * // Make all numbers round down - * mongoose.Number.get(function(v) { return Math.floor(v); }); - * - * const Model = mongoose.model('Test', new Schema({ test: Number })); - * new Model({ test: 3.14 }).test; // 3 - * - * @param {Function} getter - * @return {this} - * @function get - * @static - * @api public - */ - - SchemaNumber.get = SchemaType.get; - - /** - * Sets a default option for all Number instances. - * - * ####Example: - * - * // Make all numbers have option `min` equal to 0. - * mongoose.Schema.Number.set('min', 0); - * - * const Order = mongoose.model('Order', new Schema({ amount: Number })); - * new Order({ amount: -10 }).validateSync().errors.amount.message; // Path `amount` must be larger than 0. - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - - SchemaNumber.set = SchemaType.set; - - /*! - * ignore - */ - - SchemaNumber._cast = castNumber; - - /** - * Get/set the function used to cast arbitrary values to numbers. - * - * ####Example: - * - * // Make Mongoose cast empty strings '' to 0 for paths declared as numbers - * const original = mongoose.Number.cast(); - * mongoose.Number.cast(v => { - * if (v === '') { return 0; } - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.Number.cast(false); - * - * @param {Function} caster - * @return {Function} - * @function get - * @static - * @api public - */ - - SchemaNumber.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = this._defaultCaster; - } - this._cast = caster; - - return this._cast; - }; + if (utils.hasUserDefinedProperty(obj, 'ref')) { + _mapType.ref = obj.ref; + } + } + schemaType.$__schemaType = schema.interpretAsType(mapPath, _mapType, options); +} - /*! - * ignore - */ +/** + * Iterates the schemas paths similar to Array#forEach. + * + * The callback is passed the pathname and the schemaType instance. + * + * ####Example: + * + * const userSchema = new Schema({ name: String, registeredAt: Date }); + * userSchema.eachPath((pathname, schematype) => { + * // Prints twice: + * // name SchemaString { ... } + * // registeredAt SchemaDate { ... } + * console.log(pathname, schematype); + * }); + * + * @param {Function} fn callback function + * @return {Schema} this + * @api public + */ - SchemaNumber._defaultCaster = (v) => { - if (typeof v !== "number") { - throw new Error(); - } - return v; - }; +Schema.prototype.eachPath = function(fn) { + const keys = Object.keys(this.paths); + const len = keys.length; - /** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ - SchemaNumber.schemaName = "Number"; - - SchemaNumber.defaultOptions = {}; - - /*! - * Inherits from SchemaType. - */ - SchemaNumber.prototype = Object.create(SchemaType.prototype); - SchemaNumber.prototype.constructor = SchemaNumber; - SchemaNumber.prototype.OptionsConstructor = SchemaNumberOptions; - - /*! - * ignore - */ - - SchemaNumber._checkRequired = (v) => - typeof v === "number" || v instanceof Number; - - /** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - - SchemaNumber.checkRequired = SchemaType.checkRequired; - - /** - * Check if the given value satisfies a required validator. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - - SchemaNumber.prototype.checkRequired = function checkRequired( - value, - doc - ) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - - // `require('util').inherits()` does **not** copy static properties, and - // plugins like mongoose-float use `inherits()` for pre-ES6. - const _checkRequired = - typeof this.constructor.checkRequired == "function" - ? this.constructor.checkRequired() - : SchemaNumber.checkRequired(); - - return _checkRequired(value); - }; + for (let i = 0; i < len; ++i) { + fn(keys[i], this.paths[keys[i]]); + } - /** - * Sets a minimum number validator. - * - * ####Example: - * - * const s = new Schema({ n: { type: Number, min: 10 }) - * const M = db.model('M', s) - * const m = new M({ n: 9 }) - * m.save(function (err) { - * console.error(err) // validator error - * m.n = 10; - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MIN} token which will be replaced with the invalid value - * const min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; - * const schema = new Schema({ n: { type: Number, min: min }) - * const M = mongoose.model('Measurement', schema); - * const s= new M({ n: 4 }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10). - * }) - * - * @param {Number} value minimum number - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - - SchemaNumber.prototype.min = function (value, message) { - if (this.minValidator) { - this.validators = this.validators.filter(function (v) { - return v.validator !== this.minValidator; - }, this); - } - - if (value !== null && value !== undefined) { - let msg = message || MongooseError.messages.Number.min; - msg = msg.replace(/{MIN}/, value); - this.validators.push({ - validator: (this.minValidator = function (v) { - return v == null || v >= value; - }), - message: msg, - type: "min", - min: value, - }); - } + return this; +}; - return this; - }; +/** + * Returns an Array of path strings that are required by this schema. + * + * ####Example: + * const s = new Schema({ + * name: { type: String, required: true }, + * age: { type: String, required: true }, + * notes: String + * }); + * s.requiredPaths(); // [ 'age', 'name' ] + * + * @api public + * @param {Boolean} invalidate refresh the cache + * @return {Array} + */ - /** - * Sets a maximum number validator. - * - * ####Example: - * - * const s = new Schema({ n: { type: Number, max: 10 }) - * const M = db.model('M', s) - * const m = new M({ n: 11 }) - * m.save(function (err) { - * console.error(err) // validator error - * m.n = 10; - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MAX} token which will be replaced with the invalid value - * const max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; - * const schema = new Schema({ n: { type: Number, max: max }) - * const M = mongoose.model('Measurement', schema); - * const s= new M({ n: 4 }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10). - * }) - * - * @param {Number} maximum number - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - - SchemaNumber.prototype.max = function (value, message) { - if (this.maxValidator) { - this.validators = this.validators.filter(function (v) { - return v.validator !== this.maxValidator; - }, this); - } - - if (value !== null && value !== undefined) { - let msg = message || MongooseError.messages.Number.max; - msg = msg.replace(/{MAX}/, value); - this.validators.push({ - validator: (this.maxValidator = function (v) { - return v == null || v <= value; - }), - message: msg, - type: "max", - max: value, - }); - } +Schema.prototype.requiredPaths = function requiredPaths(invalidate) { + if (this._requiredpaths && !invalidate) { + return this._requiredpaths; + } - return this; - }; + const paths = Object.keys(this.paths); + let i = paths.length; + const ret = []; - /** - * Sets a enum validator - * - * ####Example: - * - * const s = new Schema({ n: { type: Number, enum: [1, 2, 3] }); - * const M = db.model('M', s); - * - * const m = new M({ n: 4 }); - * await m.save(); // throws validation error - * - * m.n = 3; - * await m.save(); // succeeds - * - * @param {Array} values allowed values - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - - SchemaNumber.prototype.enum = function (values, message) { - if (this.enumValidator) { - this.validators = this.validators.filter(function (v) { - return v.validator !== this.enumValidator; - }, this); - } - - if (!Array.isArray(values)) { - if (utils.isObject(values)) { - values = utils.object.vals(values); - } else { - values = Array.prototype.slice.call(arguments); - } - message = MongooseError.messages.Number.enum; - } + while (i--) { + const path = paths[i]; + if (this.paths[path].isRequired) { + ret.push(path); + } + } + this._requiredpaths = ret; + return this._requiredpaths; +}; - message = - message == null ? MongooseError.messages.Number.enum : message; +/** + * Returns indexes from fields and schema-level indexes (cached). + * + * @api private + * @return {Array} + */ - this.enumValidator = (v) => v == null || values.indexOf(v) !== -1; - this.validators.push({ - validator: this.enumValidator, - message: message, - type: "enum", - enumValues: values, - }); +Schema.prototype.indexedPaths = function indexedPaths() { + if (this._indexedpaths) { + return this._indexedpaths; + } + this._indexedpaths = this.indexes(); + return this._indexedpaths; +}; - return this; - }; +/** + * Returns the pathType of `path` for this schema. + * + * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path. + * + * ####Example: + * const s = new Schema({ name: String, nested: { foo: String } }); + * s.virtual('foo').get(() => 42); + * s.pathType('name'); // "real" + * s.pathType('nested'); // "nested" + * s.pathType('foo'); // "virtual" + * s.pathType('fail'); // "adhocOrUndefined" + * + * @param {String} path + * @return {String} + * @api public + */ - /** - * Casts to number - * - * @param {Object} value value to cast - * @param {Document} doc document that triggers the casting - * @param {Boolean} init - * @api private - */ - - SchemaNumber.prototype.cast = function (value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - if (typeof value === "number") { - return value; - } +Schema.prototype.pathType = function(path) { + // Convert to '.$' to check subpaths re: gh-6405 + const cleanPath = _pathToPositionalSyntax(path); - return this._castRef(value, doc, init); - } + if (this.paths.hasOwnProperty(path)) { + return 'real'; + } + if (this.virtuals.hasOwnProperty(path)) { + return 'virtual'; + } + if (this.nested.hasOwnProperty(path)) { + return 'nested'; + } + if (this.subpaths.hasOwnProperty(cleanPath) || this.subpaths.hasOwnProperty(path)) { + return 'real'; + } - const val = - value && typeof value._id !== "undefined" - ? value._id // documents - : value; + const singleNestedPath = this.singleNestedPaths.hasOwnProperty(cleanPath) || this.singleNestedPaths.hasOwnProperty(path); + if (singleNestedPath) { + return singleNestedPath === 'nested' ? 'nested' : 'real'; + } - let castNumber; - if (typeof this._castFunction === "function") { - castNumber = this._castFunction; - } else if (typeof this.constructor.cast === "function") { - castNumber = this.constructor.cast(); - } else { - castNumber = SchemaNumber.cast(); - } + // Look for maps + const mapPath = getMapPath(this, path); + if (mapPath != null) { + return 'real'; + } - try { - return castNumber(val); - } catch (err) { - throw new CastError("Number", val, this.path, err, this); - } - }; + if (/\.\d+\.|\.\d+$/.test(path)) { + return getPositionalPathType(this, path); + } + return 'adhocOrUndefined'; +}; - /*! - * ignore - */ +/** + * Returns true iff this path is a child of a mixed schema. + * + * @param {String} path + * @return {Boolean} + * @api private + */ - function handleSingle(val) { - return this.cast(val); - } +Schema.prototype.hasMixedParent = function(path) { + const subpaths = path.split(/\./g); + path = ''; + for (let i = 0; i < subpaths.length; ++i) { + path = i > 0 ? path + '.' + subpaths[i] : subpaths[i]; + if (this.paths.hasOwnProperty(path) && + this.paths[path] instanceof MongooseTypes.Mixed) { + return this.paths[path]; + } + } - function handleArray(val) { - const _this = this; - if (!Array.isArray(val)) { - return [this.cast(val)]; - } - return val.map(function (m) { - return _this.cast(m); - }); - } + return null; +}; - SchemaNumber.prototype.$conditionalHandlers = utils.options( - SchemaType.prototype.$conditionalHandlers, - { - $bitsAllClear: handleBitwiseOperator, - $bitsAnyClear: handleBitwiseOperator, - $bitsAllSet: handleBitwiseOperator, - $bitsAnySet: handleBitwiseOperator, - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle, - $mod: handleArray, - } - ); +/** + * Setup updatedAt and createdAt timestamps to documents if enabled + * + * @param {Boolean|Object} timestamps timestamps options + * @api private + */ +Schema.prototype.setupTimestamp = function(timestamps) { + return setupTimestamps(this, timestamps); +}; - /** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - - SchemaNumber.prototype.castForQuery = function ($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) { - throw new CastError("number", val, this.path, null, this); - } - return handler.call(this, val); - } - val = this._castForQuery($conditional); - return val; - }; +/*! + * ignore. Deprecated re: #6405 + */ - /*! - * Module exports. - */ +function getPositionalPathType(self, path) { + const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); + if (subpaths.length < 2) { + return self.paths.hasOwnProperty(subpaths[0]) ? + self.paths[subpaths[0]] : + 'adhocOrUndefined'; + } - module.exports = SchemaNumber; + let val = self.path(subpaths[0]); + let isNested = false; + if (!val) { + return 'adhocOrUndefined'; + } - /***/ - }, + const last = subpaths.length - 1; - /***/ 9259: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ - - const SchemaObjectIdOptions = __nccwpck_require__(1374); - const SchemaType = __nccwpck_require__(5660); - const castObjectId = __nccwpck_require__(5552); - const getConstructorName = __nccwpck_require__(7323); - const oid = __nccwpck_require__(2706); - const utils = __nccwpck_require__(9232); - - const CastError = SchemaType.CastError; - let Document; - - /** - * ObjectId SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - - function ObjectId(key, options) { - const isKeyHexStr = - typeof key === "string" && - key.length === 24 && - /^[a-f0-9]+$/i.test(key); - const suppressWarning = options && options.suppressWarning; - if ((isKeyHexStr || typeof key === "undefined") && !suppressWarning) { - console.warn( - "mongoose: To create a new ObjectId please try " + - "`Mongoose.Types.ObjectId` instead of using " + - "`Mongoose.Schema.ObjectId`. Set the `suppressWarning` option if " + - "you're trying to create a hex char path in your schema." - ); - console.trace(); - } - SchemaType.call(this, key, options, "ObjectID"); - } - - /** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ - ObjectId.schemaName = "ObjectId"; - - ObjectId.defaultOptions = {}; - - /*! - * Inherits from SchemaType. - */ - ObjectId.prototype = Object.create(SchemaType.prototype); - ObjectId.prototype.constructor = ObjectId; - ObjectId.prototype.OptionsConstructor = SchemaObjectIdOptions; - - /** - * Attaches a getter for all ObjectId instances - * - * ####Example: - * - * // Always convert to string when getting an ObjectId - * mongoose.ObjectId.get(v => v.toString()); - * - * const Model = mongoose.model('Test', new Schema({})); - * typeof (new Model({})._id); // 'string' - * - * @param {Function} getter - * @return {this} - * @function get - * @static - * @api public - */ - - ObjectId.get = SchemaType.get; - - /** - * Sets a default option for all ObjectId instances. - * - * ####Example: - * - * // Make all object ids have option `required` equal to true. - * mongoose.Schema.ObjectId.set('required', true); - * - * const Order = mongoose.model('Order', new Schema({ userId: ObjectId })); - * new Order({ }).validateSync().errors.userId.message; // Path `userId` is required. - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - - ObjectId.set = SchemaType.set; - - /** - * Adds an auto-generated ObjectId default if turnOn is true. - * @param {Boolean} turnOn auto generated ObjectId defaults - * @api public - * @return {SchemaType} this - */ - - ObjectId.prototype.auto = function (turnOn) { - if (turnOn) { - this.default(defaultId); - this.set(resetId); - } + for (let i = 1; i < subpaths.length; ++i) { + isNested = false; + const subpath = subpaths[i]; - return this; - }; + if (i === last && val && !/\D/.test(subpath)) { + if (val.$isMongooseDocumentArray) { + val = val.$embeddedSchemaType; + } else if (val instanceof MongooseTypes.Array) { + // StringSchema, NumberSchema, etc + val = val.caster; + } else { + val = undefined; + } + break; + } - /*! - * ignore - */ - - ObjectId._checkRequired = (v) => v instanceof oid; - - /*! - * ignore - */ - - ObjectId._cast = castObjectId; - - /** - * Get/set the function used to cast arbitrary values to objectids. - * - * ####Example: - * - * // Make Mongoose only try to cast length 24 strings. By default, any 12 - * // char string is a valid ObjectId. - * const original = mongoose.ObjectId.cast(); - * mongoose.ObjectId.cast(v => { - * assert.ok(typeof v !== 'string' || v.length === 24); - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.ObjectId.cast(false); - * - * @param {Function} caster - * @return {Function} - * @function get - * @static - * @api public - */ - - ObjectId.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = this._defaultCaster; - } - this._cast = caster; - - return this._cast; - }; + // ignore if its just a position segment: path.0.subpath + if (!/\D/.test(subpath)) { + // Nested array + if (val instanceof MongooseTypes.Array && i !== last) { + val = val.caster; + } + continue; + } - /*! - * ignore - */ + if (!(val && val.schema)) { + val = undefined; + break; + } - ObjectId._defaultCaster = (v) => { - if (!(v instanceof oid)) { - throw new Error(v + " is not an instance of ObjectId"); - } - return v; - }; + const type = val.schema.pathType(subpath); + isNested = (type === 'nested'); + val = val.schema.path(subpath); + } - /** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * ####Example: - * - * // Allow empty strings to pass `required` check - * mongoose.Schema.Types.String.checkRequired(v => v != null); - * - * const M = mongoose.model({ str: { type: String, required: true } }); - * new M({ str: '' }).validateSync(); // `null`, validation passes! - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - - ObjectId.checkRequired = SchemaType.checkRequired; - - /** - * Check if the given value satisfies a required validator. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - - ObjectId.prototype.checkRequired = function checkRequired(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - - // `require('util').inherits()` does **not** copy static properties, and - // plugins like mongoose-float use `inherits()` for pre-ES6. - const _checkRequired = - typeof this.constructor.checkRequired == "function" - ? this.constructor.checkRequired() - : ObjectId.checkRequired(); - - return _checkRequired(value); - }; + self.subpaths[path] = val; + if (val) { + return 'real'; + } + if (isNested) { + return 'nested'; + } + return 'adhocOrUndefined'; +} - /** - * Casts to ObjectId - * - * @param {Object} value - * @param {Object} doc - * @param {Boolean} init whether this is an initialization cast - * @api private - */ - - ObjectId.prototype.cast = function (value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - if (value instanceof oid) { - return value; - } else if ( - (getConstructorName(value) || "").toLowerCase() === "objectid" - ) { - return new oid(value.toHexString()); - } - return this._castRef(value, doc, init); - } +/*! + * ignore + */ - let castObjectId; - if (typeof this._castFunction === "function") { - castObjectId = this._castFunction; - } else if (typeof this.constructor.cast === "function") { - castObjectId = this.constructor.cast(); - } else { - castObjectId = ObjectId.cast(); - } +function getPositionalPath(self, path) { + getPositionalPathType(self, path); + return self.subpaths[path]; +} - try { - return castObjectId(value); - } catch (error) { - throw new CastError("ObjectId", value, this.path, error, this); - } - }; +/** + * Adds a method call to the queue. + * + * ####Example: + * + * schema.methods.print = function() { console.log(this); }; + * schema.queue('print', []); // Print the doc every one is instantiated + * + * const Model = mongoose.model('Test', schema); + * new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }' + * + * @param {String} name name of the document method to call later + * @param {Array} args arguments to pass to the method + * @api public + */ - /*! - * ignore - */ +Schema.prototype.queue = function(name, args) { + this.callQueue.push([name, args]); + return this; +}; - function handleSingle(val) { - return this.cast(val); - } +/** + * Defines a pre hook for the model. + * + * ####Example + * + * const toySchema = new Schema({ name: String, created: Date }); + * + * toySchema.pre('save', function(next) { + * if (!this.created) this.created = new Date; + * next(); + * }); + * + * toySchema.pre('validate', function(next) { + * if (this.name !== 'Woody') this.name = 'Woody'; + * next(); + * }); + * + * // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`. + * toySchema.pre(/^find/, function(next) { + * console.log(this.getFilter()); + * }); + * + * // Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`. + * toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) { + * console.log(this.getFilter()); + * }); + * + * toySchema.pre('deleteOne', function() { + * // Runs when you call `Toy.deleteOne()` + * }); + * + * toySchema.pre('deleteOne', { document: true }, function() { + * // Runs when you call `doc.deleteOne()` + * }); + * + * @param {String|RegExp} The method name or regular expression to match method name + * @param {Object} [options] + * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. For example, set `options.document` to `true` to apply this hook to `Document#deleteOne()` rather than `Query#deleteOne()`. + * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware. + * @param {Function} callback + * @api public + */ - ObjectId.prototype.$conditionalHandlers = utils.options( - SchemaType.prototype.$conditionalHandlers, - { - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle, - } - ); +Schema.prototype.pre = function(name) { + if (name instanceof RegExp) { + const remainingArgs = Array.prototype.slice.call(arguments, 1); + for (const fn of hookNames) { + if (name.test(fn)) { + this.pre.apply(this, [fn].concat(remainingArgs)); + } + } + return this; + } + if (Array.isArray(name)) { + const remainingArgs = Array.prototype.slice.call(arguments, 1); + for (const el of name) { + this.pre.apply(this, [el].concat(remainingArgs)); + } + return this; + } + this.s.hooks.pre.apply(this.s.hooks, arguments); + return this; +}; - /*! - * ignore - */ +/** + * Defines a post hook for the document + * + * const schema = new Schema(..); + * schema.post('save', function (doc) { + * console.log('this fired after a document was saved'); + * }); + * + * schema.post('find', function(docs) { + * console.log('this fired after you ran a find query'); + * }); + * + * schema.post(/Many$/, function(res) { + * console.log('this fired after you ran `updateMany()` or `deleteMany()`); + * }); + * + * const Model = mongoose.model('Model', schema); + * + * const m = new Model(..); + * m.save(function(err) { + * console.log('this fires after the `post` hook'); + * }); + * + * m.find(function(err, docs) { + * console.log('this fires after the post find hook'); + * }); + * + * @param {String|RegExp} The method name or regular expression to match method name + * @param {Object} [options] + * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. + * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware. + * @param {Function} fn callback + * @see middleware http://mongoosejs.com/docs/middleware.html + * @see kareem http://npmjs.org/package/kareem + * @api public + */ - function defaultId() { - return new oid(); +Schema.prototype.post = function(name) { + if (name instanceof RegExp) { + const remainingArgs = Array.prototype.slice.call(arguments, 1); + for (const fn of hookNames) { + if (name.test(fn)) { + this.post.apply(this, [fn].concat(remainingArgs)); } + } + return this; + } + if (Array.isArray(name)) { + const remainingArgs = Array.prototype.slice.call(arguments, 1); + for (const el of name) { + this.post.apply(this, [el].concat(remainingArgs)); + } + return this; + } + this.s.hooks.post.apply(this.s.hooks, arguments); + return this; +}; - defaultId.$runBeforeSetters = true; - - function resetId(v) { - Document || (Document = __nccwpck_require__(6717)); - - if (this instanceof Document) { - if (v === void 0) { - const _v = new oid(); - this.$__._id = _v; - return _v; - } +/** + * Registers a plugin for this schema. + * + * ####Example: + * + * const s = new Schema({ name: String }); + * s.plugin(schema => console.log(schema.path('name').path)); + * mongoose.model('Test', s); // Prints 'name' + * + * @param {Function} plugin callback + * @param {Object} [opts] + * @see plugins + * @api public + */ - this.$__._id = v; - } +Schema.prototype.plugin = function(fn, opts) { + if (typeof fn !== 'function') { + throw new Error('First param to `schema.plugin()` must be a function, ' + + 'got "' + (typeof fn) + '"'); + } - return v; + if (opts && opts.deduplicate) { + for (const plugin of this.plugins) { + if (plugin.fn === fn) { + return this; } + } + } + this.plugins.push({ fn: fn, opts: opts }); - /*! - * Module exports. - */ - - module.exports = ObjectId; - - /***/ - }, + fn(this, opts); + return this; +}; - /***/ 9547: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module requirements. - */ +/** + * Adds an instance method to documents constructed from Models compiled from this schema. + * + * ####Example + * + * const schema = kittySchema = new Schema(..); + * + * schema.method('meow', function () { + * console.log('meeeeeoooooooooooow'); + * }) + * + * const Kitty = mongoose.model('Kitty', schema); + * + * const fizz = new Kitty; + * fizz.meow(); // meeeeeooooooooooooow + * + * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. + * + * schema.method({ + * purr: function () {} + * , scratch: function () {} + * }); + * + * // later + * fizz.purr(); + * fizz.scratch(); + * + * NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](/docs/guide.html#methods) + * + * @param {String|Object} method name + * @param {Function} [fn] + * @api public + */ - const CastError = __nccwpck_require__(2798); +Schema.prototype.method = function(name, fn, options) { + if (typeof name !== 'string') { + for (const i in name) { + this.methods[i] = name[i]; + this.methodOptions[i] = utils.clone(options); + } + } else { + this.methods[name] = fn; + this.methodOptions[name] = utils.clone(options); + } + return this; +}; - /*! - * ignore - */ +/** + * Adds static "class" methods to Models compiled from this schema. + * + * ####Example + * + * const schema = new Schema(..); + * // Equivalent to `schema.statics.findByName = function(name) {}`; + * schema.static('findByName', function(name) { + * return this.find({ name: name }); + * }); + * + * const Drink = mongoose.model('Drink', schema); + * await Drink.findByName('LaCroix'); + * + * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics. + * + * @param {String|Object} name + * @param {Function} [fn] + * @api public + * @see Statics /docs/guide.html#statics + */ - function handleBitwiseOperator(val) { - const _this = this; - if (Array.isArray(val)) { - return val.map(function (v) { - return _castNumber(_this.path, v); - }); - } else if (Buffer.isBuffer(val)) { - return val; - } - // Assume trying to cast to number - return _castNumber(_this.path, val); - } +Schema.prototype.static = function(name, fn) { + if (typeof name !== 'string') { + for (const i in name) { + this.statics[i] = name[i]; + } + } else { + this.statics[name] = fn; + } + return this; +}; - /*! - * ignore - */ +/** + * Defines an index (most likely compound) for this schema. + * + * ####Example + * + * schema.index({ first: 1, last: -1 }) + * + * @param {Object} fields + * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex) + * @param {String | number} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link. + * @api public + */ - function _castNumber(path, num) { - const v = Number(num); - if (isNaN(v)) { - throw new CastError("number", num, path); - } - return v; - } +Schema.prototype.index = function(fields, options) { + fields || (fields = {}); + options || (options = {}); - module.exports = handleBitwiseOperator; + if (options.expires) { + utils.expires(options); + } - /***/ - }, + this._indexes.push([fields, options]); + return this; +}; - /***/ 1426: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +/** + * Sets a schema option. + * + * ####Example + * + * schema.set('strict'); // 'true' by default + * schema.set('strict', false); // Sets 'strict' to false + * schema.set('strict'); // 'false' + * + * @param {String} key option name + * @param {Object} [value] if not passed, the current option value is returned + * @see Schema ./ + * @api public + */ - const castBoolean = __nccwpck_require__(66); +Schema.prototype.set = function(key, value, _tags) { + if (arguments.length === 1) { + return this.options[key]; + } - /*! - * ignore - */ + switch (key) { + case 'read': + this.options[key] = readPref(value, _tags); + this._userProvidedOptions[key] = this.options[key]; + break; + case 'timestamps': + this.setupTimestamp(value); + this.options[key] = value; + this._userProvidedOptions[key] = this.options[key]; + break; + case '_id': + this.options[key] = value; + this._userProvidedOptions[key] = this.options[key]; + + if (value && !this.paths['_id']) { + addAutoId(this); + } else if (!value && this.paths['_id'] != null && this.paths['_id'].auto) { + this.remove('_id'); + } + break; + default: + this.options[key] = value; + this._userProvidedOptions[key] = this.options[key]; + break; + } - module.exports = function (val) { - const path = this != null ? this.path : null; - return castBoolean(val, path); - }; + return this; +}; - /***/ - }, +/** + * Gets a schema option. + * + * ####Example: + * + * schema.get('strict'); // true + * schema.set('strict', false); + * schema.get('strict'); // false + * + * @param {String} key option name + * @api public + * @return {Any} the option's value + */ - /***/ 5061: /***/ ( - __unused_webpack_module, - exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module requirements. - */ - - const castArraysOfNumbers = - __nccwpck_require__(9446) /* .castArraysOfNumbers */.i; - const castToNumber = __nccwpck_require__(9446) /* .castToNumber */.W; - - /*! - * ignore - */ - - exports.cast$geoIntersects = cast$geoIntersects; - exports.cast$near = cast$near; - exports.cast$within = cast$within; - - function cast$near(val) { - const SchemaArray = __nccwpck_require__(6090); - - if (Array.isArray(val)) { - castArraysOfNumbers(val, this); - return val; - } +Schema.prototype.get = function(key) { + return this.options[key]; +}; - _castMinMaxDistance(this, val); +/** + * The allowed index types + * + * @receiver Schema + * @static indexTypes + * @api public + */ - if (val && val.$geometry) { - return cast$geometry(val, this); - } +const indexTypes = '2d 2dsphere hashed text'.split(' '); - if (!Array.isArray(val)) { - throw new TypeError( - "$near must be either an array or an object " + - "with a $geometry property" - ); - } +Object.defineProperty(Schema, 'indexTypes', { + get: function() { + return indexTypes; + }, + set: function() { + throw new Error('Cannot overwrite Schema.indexTypes'); + } +}); - return SchemaArray.prototype.castForQuery.call(this, val); - } +/** + * Returns a list of indexes that this schema declares, via `schema.index()` or by `index: true` in a path's options. + * Indexes are expressed as an array `[spec, options]`. + * + * ####Example: + * + * const userSchema = new Schema({ + * email: { type: String, required: true, unique: true }, + * registeredAt: { type: Date, index: true } + * }); + * + * // [ [ { email: 1 }, { unique: true, background: true } ], + * // [ { registeredAt: 1 }, { background: true } ] ] + * userSchema.indexes(); + * + * [Plugins](/docs/plugins.html) can use the return value of this function to modify a schema's indexes. + * For example, the below plugin makes every index unique by default. + * + * function myPlugin(schema) { + * for (const index of schema.indexes()) { + * if (index[1].unique === undefined) { + * index[1].unique = true; + * } + * } + * } + * + * @api public + * @return {Array} list of indexes defined in the schema + */ - function cast$geometry(val, self) { - switch (val.$geometry.type) { - case "Polygon": - case "LineString": - case "Point": - castArraysOfNumbers(val.$geometry.coordinates, self); - break; - default: - // ignore unknowns - break; - } +Schema.prototype.indexes = function() { + return getIndexes(this); +}; - _castMinMaxDistance(self, val); +/** + * Creates a virtual type with the given name. + * + * @param {String} name + * @param {Object} [options] + * @param {String|Model} [options.ref] model name or model instance. Marks this as a [populate virtual](/docs/populate.html#populate-virtuals). + * @param {String|Function} [options.localField] Required for populate virtuals. See [populate virtual docs](/docs/populate.html#populate-virtuals) for more information. + * @param {String|Function} [options.foreignField] Required for populate virtuals. See [populate virtual docs](/docs/populate.html#populate-virtuals) for more information. + * @param {Boolean|Function} [options.justOne=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), will be a single doc or `null`. Otherwise, the populate virtual will be an array. + * @param {Boolean} [options.count=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), this populate virtual will contain the number of documents rather than the documents themselves when you `populate()`. + * @param {Function|null} [options.get=null] Adds a [getter](/docs/tutorials/getters-setters.html) to this virtual to transform the populated doc. + * @return {VirtualType} + */ - return val; - } +Schema.prototype.virtual = function(name, options) { + if (name instanceof VirtualType || getConstructorName(name) === 'VirtualType') { + return this.virtual(name.path, name.options); + } - function cast$within(val) { - _castMinMaxDistance(this, val); + options = new VirtualOptions(options); - if (val.$box || val.$polygon) { - const type = val.$box ? "$box" : "$polygon"; - val[type].forEach((arr) => { - if (!Array.isArray(arr)) { - const msg = - "Invalid $within $box argument. " + - "Expected an array, received " + - arr; - throw new TypeError(msg); - } - arr.forEach((v, i) => { - arr[i] = castToNumber.call(this, v); - }); - }); - } else if (val.$center || val.$centerSphere) { - const type = val.$center ? "$center" : "$centerSphere"; - val[type].forEach((item, i) => { - if (Array.isArray(item)) { - item.forEach((v, j) => { - item[j] = castToNumber.call(this, v); - }); - } else { - val[type][i] = castToNumber.call(this, item); - } - }); - } else if (val.$geometry) { - cast$geometry(val, this); - } + if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) { + if (options.localField == null) { + throw new Error('Reference virtuals require `localField` option'); + } - return val; - } + if (options.foreignField == null) { + throw new Error('Reference virtuals require `foreignField` option'); + } - function cast$geoIntersects(val) { - const geo = val.$geometry; - if (!geo) { - return; + this.pre('init', function(obj) { + if (mpath.has(name, obj)) { + const _v = mpath.get(name, obj); + if (!this.$$populatedVirtuals) { + this.$$populatedVirtuals = {}; } - cast$geometry(val, this); - return val; - } - - function _castMinMaxDistance(self, val) { - if (val.$maxDistance) { - val.$maxDistance = castToNumber.call(self, val.$maxDistance); - } - if (val.$minDistance) { - val.$minDistance = castToNumber.call(self, val.$minDistance); + if (options.justOne || options.count) { + this.$$populatedVirtuals[name] = Array.isArray(_v) ? + _v[0] : + _v; + } else { + this.$$populatedVirtuals[name] = Array.isArray(_v) ? + _v : + _v == null ? [] : [_v]; } - } - - /***/ - }, - /***/ 9446: /***/ ( - __unused_webpack_module, - exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module requirements. - */ - - const SchemaNumber = __nccwpck_require__(188); - - /*! - * @ignore - */ - - exports.W = castToNumber; - exports.i = castArraysOfNumbers; - - /*! - * @ignore - */ - - function castToNumber(val) { - return SchemaNumber.cast()(val); - } - - function castArraysOfNumbers(arr, self) { - arr.forEach(function (v, i) { - if (Array.isArray(v)) { - castArraysOfNumbers(v, self); - } else { - arr[i] = castToNumber.call(self, v); - } - }); + mpath.unset(name, obj); } + }); - /***/ - }, + const virtual = this.virtual(name); + virtual.options = options; - /***/ 8807: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const CastError = __nccwpck_require__(2798); - const castBoolean = __nccwpck_require__(66); - const castString = __nccwpck_require__(1318); - - /*! - * Casts val to an object suitable for `$text`. Throws an error if the object - * can't be casted. - * - * @param {Any} val value to cast - * @param {String} [path] path to associate with any errors that occured - * @return {Object} casted object - * @see https://docs.mongodb.com/manual/reference/operator/query/text/ - * @api private - */ - - module.exports = function (val, path) { - if (val == null || typeof val !== "object") { - throw new CastError("$text", val, path); - } - - if (val.$search != null) { - val.$search = castString(val.$search, path + ".$search"); - } - if (val.$language != null) { - val.$language = castString(val.$language, path + ".$language"); - } - if (val.$caseSensitive != null) { - val.$caseSensitive = castBoolean( - val.$caseSensitive, - path + ".$castSensitive" - ); - } - if (val.$diacriticSensitive != null) { - val.$diacriticSensitive = castBoolean( - val.$diacriticSensitive, - path + ".$diacriticSensitive" - ); + virtual. + set(function(_v) { + if (!this.$$populatedVirtuals) { + this.$$populatedVirtuals = {}; } - return val; - }; - - /***/ - }, + if (options.justOne || options.count) { + this.$$populatedVirtuals[name] = Array.isArray(_v) ? + _v[0] : + _v; - /***/ 4093: /***/ (module) => { - "use strict"; - - /*! - * ignore - */ - - module.exports = function (val) { - if (Array.isArray(val)) { - if ( - !val.every((v) => typeof v === "number" || typeof v === "string") - ) { - throw new Error("$type array values must be strings or numbers"); + if (typeof this.$$populatedVirtuals[name] !== 'object') { + this.$$populatedVirtuals[name] = options.count ? _v : null; } - return val; - } + } else { + this.$$populatedVirtuals[name] = Array.isArray(_v) ? + _v : + _v == null ? [] : [_v]; - if (typeof val !== "number" && typeof val !== "string") { - throw new Error( - "$type parameter must be number, string, or array of numbers and strings" - ); + this.$$populatedVirtuals[name] = this.$$populatedVirtuals[name].filter(function(doc) { + return doc && typeof doc === 'object'; + }); } - - return val; - }; - - /***/ - }, - - /***/ 7451: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const SchemaType = __nccwpck_require__(5660); - const MongooseError = __nccwpck_require__(4327); - const SchemaStringOptions = __nccwpck_require__(7692); - const castString = __nccwpck_require__(1318); - const utils = __nccwpck_require__(9232); - - const CastError = SchemaType.CastError; - - /** - * String SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - - function SchemaString(key, options) { - this.enumValues = []; - this.regExp = null; - SchemaType.call(this, key, options, "String"); - } - - /** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ - SchemaString.schemaName = "String"; - - SchemaString.defaultOptions = {}; - - /*! - * Inherits from SchemaType. - */ - SchemaString.prototype = Object.create(SchemaType.prototype); - SchemaString.prototype.constructor = SchemaString; - Object.defineProperty(SchemaString.prototype, "OptionsConstructor", { - configurable: false, - enumerable: false, - writable: false, - value: SchemaStringOptions, }); - /*! - * ignore - */ - - SchemaString._cast = castString; - - /** - * Get/set the function used to cast arbitrary values to strings. - * - * ####Example: - * - * // Throw an error if you pass in an object. Normally, Mongoose allows - * // objects with custom `toString()` functions. - * const original = mongoose.Schema.Types.String.cast(); - * mongoose.Schema.Types.String.cast(v => { - * assert.ok(v == null || typeof v !== 'object'); - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.Schema.Types.String.cast(false); - * - * @param {Function} caster - * @return {Function} - * @function get - * @static - * @api public - */ - - SchemaString.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = this._defaultCaster; - } - this._cast = caster; - - return this._cast; - }; + if (typeof options.get === 'function') { + virtual.get(options.get); + } - /*! - * ignore - */ + // Workaround for gh-8198: if virtual is under document array, make a fake + // virtual. See gh-8210 + const parts = name.split('.'); + let cur = parts[0]; + for (let i = 0; i < parts.length - 1; ++i) { + if (this.paths[cur] != null && this.paths[cur].$isMongooseDocumentArray) { + const remnant = parts.slice(i + 1).join('.'); + this.paths[cur].schema.virtual(remnant, options); + break; + } - SchemaString._defaultCaster = (v) => { - if (v != null && typeof v !== "string") { - throw new Error(); - } - return v; - }; + cur += '.' + parts[i + 1]; + } - /** - * Attaches a getter for all String instances. - * - * ####Example: - * - * // Make all numbers round down - * mongoose.Schema.String.get(v => v.toLowerCase()); - * - * const Model = mongoose.model('Test', new Schema({ test: String })); - * new Model({ test: 'FOO' }).test; // 'foo' - * - * @param {Function} getter - * @return {this} - * @function get - * @static - * @api public - */ - - SchemaString.get = SchemaType.get; - - /** - * Sets a default option for all String instances. - * - * ####Example: - * - * // Make all strings have option `trim` equal to true. - * mongoose.Schema.String.set('trim', true); - * - * const User = mongoose.model('User', new Schema({ name: String })); - * new User({ name: ' John Doe ' }).name; // 'John Doe' - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - - SchemaString.set = SchemaType.set; - - /*! - * ignore - */ - - SchemaString._checkRequired = (v) => - (v instanceof String || typeof v === "string") && v.length; - - /** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * ####Example: - * - * // Allow empty strings to pass `required` check - * mongoose.Schema.Types.String.checkRequired(v => v != null); - * - * const M = mongoose.model({ str: { type: String, required: true } }); - * new M({ str: '' }).validateSync(); // `null`, validation passes! - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - - SchemaString.checkRequired = SchemaType.checkRequired; - - /** - * Adds an enum validator - * - * ####Example: - * - * const states = ['opening', 'open', 'closing', 'closed'] - * const s = new Schema({ state: { type: String, enum: states }}) - * const M = db.model('M', s) - * const m = new M({ state: 'invalid' }) - * m.save(function (err) { - * console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`. - * m.state = 'open' - * m.save(callback) // success - * }) - * - * // or with custom error messages - * const enum = { - * values: ['opening', 'open', 'closing', 'closed'], - * message: 'enum validator failed for path `{PATH}` with value `{VALUE}`' - * } - * const s = new Schema({ state: { type: String, enum: enum }) - * const M = db.model('M', s) - * const m = new M({ state: 'invalid' }) - * m.save(function (err) { - * console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid` - * m.state = 'open' - * m.save(callback) // success - * }) - * - * @param {String|Object} [args...] enumeration values - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - - SchemaString.prototype.enum = function () { - if (this.enumValidator) { - this.validators = this.validators.filter(function (v) { - return v.validator !== this.enumValidator; - }, this); - this.enumValidator = false; - } - - if (arguments[0] === void 0 || arguments[0] === false) { - return this; - } + return virtual; + } - let values; - let errorMessage; + const virtuals = this.virtuals; + const parts = name.split('.'); - if (utils.isObject(arguments[0])) { - if (Array.isArray(arguments[0].values)) { - values = arguments[0].values; - errorMessage = arguments[0].message; - } else { - values = utils.object.vals(arguments[0]); - errorMessage = MongooseError.messages.String.enum; - } - } else { - values = arguments; - errorMessage = MongooseError.messages.String.enum; - } + if (this.pathType(name) === 'real') { + throw new Error('Virtual path "' + name + '"' + + ' conflicts with a real path in the schema'); + } - for (const value of values) { - if (value !== undefined) { - this.enumValues.push(this.cast(value)); - } - } + virtuals[name] = parts.reduce(function(mem, part, i) { + mem[part] || (mem[part] = (i === parts.length - 1) + ? new VirtualType(options, name) + : {}); + return mem[part]; + }, this.tree); - const vals = this.enumValues; - this.enumValidator = function (v) { - return undefined === v || ~vals.indexOf(v); - }; - this.validators.push({ - validator: this.enumValidator, - message: errorMessage, - type: "enum", - enumValues: vals, - }); + return virtuals[name]; +}; - return this; - }; +/** + * Returns the virtual type with the given `name`. + * + * @param {String} name + * @return {VirtualType} + */ - /** - * Adds a lowercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). - * - * ####Example: - * - * const s = new Schema({ email: { type: String, lowercase: true }}) - * const M = db.model('M', s); - * const m = new M({ email: 'SomeEmail@example.COM' }); - * console.log(m.email) // someemail@example.com - * M.find({ email: 'SomeEmail@example.com' }); // Queries by 'someemail@example.com' - * - * Note that `lowercase` does **not** affect regular expression queries: - * - * ####Example: - * // Still queries for documents whose `email` matches the regular - * // expression /SomeEmail/. Mongoose does **not** convert the RegExp - * // to lowercase. - * M.find({ email: /SomeEmail/ }); - * - * @api public - * @return {SchemaType} this - */ - - SchemaString.prototype.lowercase = function (shouldApply) { - if (arguments.length > 0 && !shouldApply) { - return this; - } - return this.set(function (v, self) { - if (typeof v !== "string") { - v = self.cast(v); - } - if (v) { - return v.toLowerCase(); - } - return v; - }); - }; +Schema.prototype.virtualpath = function(name) { + return this.virtuals.hasOwnProperty(name) ? this.virtuals[name] : null; +}; - /** - * Adds an uppercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). - * - * ####Example: - * - * const s = new Schema({ caps: { type: String, uppercase: true }}) - * const M = db.model('M', s); - * const m = new M({ caps: 'an example' }); - * console.log(m.caps) // AN EXAMPLE - * M.find({ caps: 'an example' }) // Matches documents where caps = 'AN EXAMPLE' - * - * Note that `uppercase` does **not** affect regular expression queries: - * - * ####Example: - * // Mongoose does **not** convert the RegExp to uppercase. - * M.find({ email: /an example/ }); - * - * @api public - * @return {SchemaType} this - */ - - SchemaString.prototype.uppercase = function (shouldApply) { - if (arguments.length > 0 && !shouldApply) { - return this; - } - return this.set(function (v, self) { - if (typeof v !== "string") { - v = self.cast(v); - } - if (v) { - return v.toUpperCase(); +/** + * Removes the given `path` (or [`paths`]). + * + * ####Example: + * + * const schema = new Schema({ name: String, age: Number }); + * schema.remove('name'); + * schema.path('name'); // Undefined + * schema.path('age'); // SchemaNumber { ... } + * + * @param {String|Array} path + * @return {Schema} the Schema instance + * @api public + */ +Schema.prototype.remove = function(path) { + if (typeof path === 'string') { + path = [path]; + } + if (Array.isArray(path)) { + path.forEach(function(name) { + if (this.path(name) == null && !this.nested[name]) { + return; + } + if (this.nested[name]) { + const allKeys = Object.keys(this.paths). + concat(Object.keys(this.nested)); + for (const path of allKeys) { + if (path.startsWith(name + '.')) { + delete this.paths[path]; + delete this.nested[path]; + _deletePath(this, path); } - return v; - }); - }; - - /** - * Adds a trim [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). - * - * The string value will be trimmed when set. - * - * ####Example: - * - * const s = new Schema({ name: { type: String, trim: true }}); - * const M = db.model('M', s); - * const string = ' some name '; - * console.log(string.length); // 11 - * const m = new M({ name: string }); - * console.log(m.name.length); // 9 - * - * // Equivalent to `findOne({ name: string.trim() })` - * M.findOne({ name: string }); - * - * Note that `trim` does **not** affect regular expression queries: - * - * ####Example: - * // Mongoose does **not** trim whitespace from the RegExp. - * M.find({ name: / some name / }); - * - * @api public - * @return {SchemaType} this - */ - - SchemaString.prototype.trim = function (shouldTrim) { - if (arguments.length > 0 && !shouldTrim) { - return this; } - return this.set(function (v, self) { - if (typeof v !== "string") { - v = self.cast(v); - } - if (v) { - return v.trim(); - } - return v; - }); - }; - /** - * Sets a minimum length validator. - * - * ####Example: - * - * const schema = new Schema({ postalCode: { type: String, minlength: 5 }) - * const Address = db.model('Address', schema) - * const address = new Address({ postalCode: '9512' }) - * address.save(function (err) { - * console.error(err) // validator error - * address.postalCode = '95125'; - * address.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MINLENGTH} token which will be replaced with the minimum allowed length - * const minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).']; - * const schema = new Schema({ postalCode: { type: String, minlength: minlength }) - * const Address = mongoose.model('Address', schema); - * const address = new Address({ postalCode: '9512' }); - * address.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5). - * }) - * - * @param {Number} value minimum string length - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - - SchemaString.prototype.minlength = function (value, message) { - if (this.minlengthValidator) { - this.validators = this.validators.filter(function (v) { - return v.validator !== this.minlengthValidator; - }, this); - } - - if (value !== null && value !== undefined) { - let msg = message || MongooseError.messages.String.minlength; - msg = msg.replace(/{MINLENGTH}/, value); - this.validators.push({ - validator: (this.minlengthValidator = function (v) { - return v === null || v.length >= value; - }), - message: msg, - type: "minlength", - minlength: value, - }); - } + delete this.nested[name]; + _deletePath(this, name); + return; + } - return this; - }; + delete this.paths[name]; + _deletePath(this, name); + }, this); + } + return this; +}; - SchemaString.prototype.minLength = SchemaString.prototype.minlength; - - /** - * Sets a maximum length validator. - * - * ####Example: - * - * const schema = new Schema({ postalCode: { type: String, maxlength: 9 }) - * const Address = db.model('Address', schema) - * const address = new Address({ postalCode: '9512512345' }) - * address.save(function (err) { - * console.error(err) // validator error - * address.postalCode = '95125'; - * address.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MAXLENGTH} token which will be replaced with the maximum allowed length - * const maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).']; - * const schema = new Schema({ postalCode: { type: String, maxlength: maxlength }) - * const Address = mongoose.model('Address', schema); - * const address = new Address({ postalCode: '9512512345' }); - * address.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (9). - * }) - * - * @param {Number} value maximum string length - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - - SchemaString.prototype.maxlength = function (value, message) { - if (this.maxlengthValidator) { - this.validators = this.validators.filter(function (v) { - return v.validator !== this.maxlengthValidator; - }, this); - } - - if (value !== null && value !== undefined) { - let msg = message || MongooseError.messages.String.maxlength; - msg = msg.replace(/{MAXLENGTH}/, value); - this.validators.push({ - validator: (this.maxlengthValidator = function (v) { - return v === null || v.length <= value; - }), - message: msg, - type: "maxlength", - maxlength: value, - }); - } +/*! + * ignore + */ - return this; - }; +function _deletePath(schema, name) { + const pieces = name.split('.'); + const last = pieces.pop(); - SchemaString.prototype.maxLength = SchemaString.prototype.maxlength; - - /** - * Sets a regexp validator. - * - * Any value that does not pass `regExp`.test(val) will fail validation. - * - * ####Example: - * - * const s = new Schema({ name: { type: String, match: /^a/ }}) - * const M = db.model('M', s) - * const m = new M({ name: 'I am invalid' }) - * m.validate(function (err) { - * console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)." - * m.name = 'apples' - * m.validate(function (err) { - * assert.ok(err) // success - * }) - * }) - * - * // using a custom error message - * const match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ]; - * const s = new Schema({ file: { type: String, match: match }}) - * const M = db.model('M', s); - * const m = new M({ file: 'invalid' }); - * m.validate(function (err) { - * console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)" - * }) - * - * Empty strings, `undefined`, and `null` values always pass the match validator. If you require these values, enable the `required` validator also. - * - * const s = new Schema({ name: { type: String, match: /^a/, required: true }}) - * - * @param {RegExp} regExp regular expression to test against - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - - SchemaString.prototype.match = function match(regExp, message) { - // yes, we allow multiple match validators - - const msg = message || MongooseError.messages.String.match; - - const matchValidator = function (v) { - if (!regExp) { - return false; - } + let branch = schema.tree; - // In case RegExp happens to have `/g` flag set, we need to reset the - // `lastIndex`, otherwise `match` will intermittently fail. - regExp.lastIndex = 0; + for (const piece of pieces) { + branch = branch[piece]; + } - const ret = v != null && v !== "" ? regExp.test(v) : true; - return ret; - }; + delete branch[last]; +} - this.validators.push({ - validator: matchValidator, - message: msg, - type: "regexp", - regexp: regExp, - }); - return this; - }; +/** + * Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static), + * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions) + * to schema [virtuals](/docs/guide.html#virtuals), + * [statics](/docs/guide.html#statics), and + * [methods](/docs/guide.html#methods). + * + * ####Example: + * + * ```javascript + * const md5 = require('md5'); + * const userSchema = new Schema({ email: String }); + * class UserClass { + * // `gravatarImage` becomes a virtual + * get gravatarImage() { + * const hash = md5(this.email.toLowerCase()); + * return `https://www.gravatar.com/avatar/${hash}`; + * } + * + * // `getProfileUrl()` becomes a document method + * getProfileUrl() { + * return `https://mysite.com/${this.email}`; + * } + * + * // `findByEmail()` becomes a static + * static findByEmail(email) { + * return this.findOne({ email }); + * } + * } + * + * // `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method, + * // and a `findByEmail()` static + * userSchema.loadClass(UserClass); + * ``` + * + * @param {Function} model + * @param {Boolean} [virtualsOnly] if truthy, only pulls virtuals from the class, not methods or statics + */ +Schema.prototype.loadClass = function(model, virtualsOnly) { + if (model === Object.prototype || + model === Function.prototype || + model.prototype.hasOwnProperty('$isMongooseModelPrototype')) { + return this; + } - /** - * Check if the given value satisfies the `required` validator. The value is - * considered valid if it is a string (that is, not `null` or `undefined`) and - * has positive length. The `required` validator **will** fail for empty - * strings. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - - SchemaString.prototype.checkRequired = function checkRequired( - value, - doc - ) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - - // `require('util').inherits()` does **not** copy static properties, and - // plugins like mongoose-float use `inherits()` for pre-ES6. - const _checkRequired = - typeof this.constructor.checkRequired == "function" - ? this.constructor.checkRequired() - : SchemaString.checkRequired(); - - return _checkRequired(value); - }; + this.loadClass(Object.getPrototypeOf(model), virtualsOnly); - /** - * Casts to String - * - * @api private - */ + // Add static methods + if (!virtualsOnly) { + Object.getOwnPropertyNames(model).forEach(function(name) { + if (name.match(/^(length|name|prototype|constructor|__proto__)$/)) { + return; + } + const prop = Object.getOwnPropertyDescriptor(model, name); + if (prop.hasOwnProperty('value')) { + this.static(name, prop.value); + } + }, this); + } - SchemaString.prototype.cast = function (value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - if (typeof value === "string") { - return value; - } + // Add methods and virtuals + Object.getOwnPropertyNames(model.prototype).forEach(function(name) { + if (name.match(/^(constructor)$/)) { + return; + } + const method = Object.getOwnPropertyDescriptor(model.prototype, name); + if (!virtualsOnly) { + if (typeof method.value === 'function') { + this.method(name, method.value); + } + } + if (typeof method.get === 'function') { + if (this.virtuals[name]) { + this.virtuals[name].getters = []; + } + this.virtual(name).get(method.get); + } + if (typeof method.set === 'function') { + if (this.virtuals[name]) { + this.virtuals[name].setters = []; + } + this.virtual(name).set(method.set); + } + }, this); + + return this; +}; + +/*! + * ignore + */ - return this._castRef(value, doc, init); - } +Schema.prototype._getSchema = function(path) { + const _this = this; + const pathschema = _this.path(path); + const resultPath = []; - let castString; - if (typeof this._castFunction === "function") { - castString = this._castFunction; - } else if (typeof this.constructor.cast === "function") { - castString = this.constructor.cast(); - } else { - castString = SchemaString.cast(); - } + if (pathschema) { + pathschema.$fullPath = path; + return pathschema; + } - try { - return castString(value); - } catch (error) { - throw new CastError("string", value, this.path, null, this); + function search(parts, schema) { + let p = parts.length + 1; + let foundschema; + let trypath; + + while (p--) { + trypath = parts.slice(0, p).join('.'); + foundschema = schema.path(trypath); + if (foundschema) { + resultPath.push(trypath); + + if (foundschema.caster) { + // array of Mixed? + if (foundschema.caster instanceof MongooseTypes.Mixed) { + foundschema.caster.$fullPath = resultPath.join('.'); + return foundschema.caster; + } + + // Now that we found the array, we need to check if there + // are remaining document paths to look up for casting. + // Also we need to handle array.$.path since schema.path + // doesn't work for that. + // If there is no foundschema.schema we are dealing with + // a path like array.$ + if (p !== parts.length) { + if (foundschema.schema) { + let ret; + if (parts[p] === '$' || isArrayFilter(parts[p])) { + if (p + 1 === parts.length) { + // comments.$ + return foundschema; + } + // comments.$.comments.$.title + ret = search(parts.slice(p + 1), foundschema.schema); + if (ret) { + ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || + !foundschema.schema.$isSingleNested; + } + return ret; + } + // this is the last path of the selector + ret = search(parts.slice(p), foundschema.schema); + if (ret) { + ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || + !foundschema.schema.$isSingleNested; + } + return ret; + } + } + } else if (foundschema.$isSchemaMap) { + if (p >= parts.length) { + return foundschema; + } + // Any path in the map will be an instance of the map's embedded schematype + if (p + 1 >= parts.length) { + return foundschema.$__schemaType; + } + const ret = search(parts.slice(p + 1), foundschema.$__schemaType.schema); + return ret; } - }; - /*! - * ignore - */ + foundschema.$fullPath = resultPath.join('.'); - function handleSingle(val) { - return this.castForQuery(val); + return foundschema; } + } + } - function handleArray(val) { - const _this = this; - if (!Array.isArray(val)) { - return [this.castForQuery(val)]; - } - return val.map(function (m) { - return _this.castForQuery(m); - }); - } + // look for arrays + const parts = path.split('.'); + for (let i = 0; i < parts.length; ++i) { + if (parts[i] === '$' || isArrayFilter(parts[i])) { + // Re: gh-5628, because `schema.path()` doesn't take $ into account. + parts[i] = '0'; + } + } + return search(parts, _this); +}; - const $conditionalHandlers = utils.options( - SchemaType.prototype.$conditionalHandlers, - { - $all: handleArray, - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle, - $options: String, - $regex: handleSingle, - $not: handleSingle, - } - ); +/*! + * ignore + */ - Object.defineProperty(SchemaString.prototype, "$conditionalHandlers", { - configurable: false, - enumerable: false, - writable: false, - value: Object.freeze($conditionalHandlers), - }); +Schema.prototype._getPathType = function(path) { + const _this = this; + const pathschema = _this.path(path); - /** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [val] - * @api private - */ - - SchemaString.prototype.castForQuery = function ($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) { - throw new Error("Can't use " + $conditional + " with String."); + if (pathschema) { + return 'real'; + } + + function search(parts, schema) { + let p = parts.length + 1, + foundschema, + trypath; + + while (p--) { + trypath = parts.slice(0, p).join('.'); + foundschema = schema.path(trypath); + if (foundschema) { + if (foundschema.caster) { + // array of Mixed? + if (foundschema.caster instanceof MongooseTypes.Mixed) { + return { schema: foundschema, pathType: 'mixed' }; + } + + // Now that we found the array, we need to check if there + // are remaining document paths to look up for casting. + // Also we need to handle array.$.path since schema.path + // doesn't work for that. + // If there is no foundschema.schema we are dealing with + // a path like array.$ + if (p !== parts.length && foundschema.schema) { + if (parts[p] === '$' || isArrayFilter(parts[p])) { + if (p === parts.length - 1) { + return { schema: foundschema, pathType: 'nested' }; + } + // comments.$.comments.$.title + return search(parts.slice(p + 1), foundschema.schema); + } + // this is the last path of the selector + return search(parts.slice(p), foundschema.schema); } - return handler.call(this, val); - } - val = $conditional; - if (Object.prototype.toString.call(val) === "[object RegExp]") { - return val; + return { + schema: foundschema, + pathType: foundschema.$isSingleNested ? 'nested' : 'array' + }; } + return { schema: foundschema, pathType: 'real' }; + } else if (p === parts.length && schema.nested[trypath]) { + return { schema: schema, pathType: 'nested' }; + } + } + return { schema: foundschema || schema, pathType: 'undefined' }; + } - return this._castForQuery(val); - }; - - /*! - * Module exports. - */ + // look for arrays + return search(path.split('.'), _this); +}; - module.exports = SchemaString; +/*! + * ignore + */ - /***/ - }, +function isArrayFilter(piece) { + return piece.startsWith('$[') && piece.endsWith(']'); +} - /***/ 1205: /***/ (__unused_webpack_module, exports) => { - "use strict"; +/*! + * Called by `compile()` _right before_ compiling. Good for making any changes to + * the schema that should respect options set by plugins, like `id` + */ - exports.schemaMixedSymbol = Symbol.for("mongoose:schema_mixed"); +Schema.prototype._preCompile = function _preCompile() { + idGetter(this); +}; - exports.builtInMiddleware = Symbol.for("mongoose:built-in-middleware"); +/*! + * Module exports. + */ - /***/ - }, +module.exports = exports = Schema; - /***/ 5660: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const MongooseError = __nccwpck_require__(4327); - const SchemaTypeOptions = __nccwpck_require__(7544); - const $exists = __nccwpck_require__(1426); - const $type = __nccwpck_require__(4093); - const get = __nccwpck_require__(8730); - const handleImmutable = __nccwpck_require__(773); - const immediate = __nccwpck_require__(4830); - const schemaTypeSymbol = __nccwpck_require__(3240).schemaTypeSymbol; - const util = __nccwpck_require__(1669); - const utils = __nccwpck_require__(9232); - const validatorErrorSymbol = - __nccwpck_require__(3240).validatorErrorSymbol; - const documentIsModified = __nccwpck_require__(3240).documentIsModified; - - const populateModelSymbol = __nccwpck_require__(3240).populateModelSymbol; - - const CastError = MongooseError.CastError; - const ValidatorError = MongooseError.ValidatorError; - - /** - * SchemaType constructor. Do **not** instantiate `SchemaType` directly. - * Mongoose converts your schema paths into SchemaTypes automatically. - * - * ####Example: - * - * const schema = new Schema({ name: String }); - * schema.path('name') instanceof SchemaType; // true - * - * @param {String} path - * @param {SchemaTypeOptions} [options] See [SchemaTypeOptions docs](/docs/api/schematypeoptions.html) - * @param {String} [instance] - * @api public - */ - - function SchemaType(path, options, instance) { - this[schemaTypeSymbol] = true; - this.path = path; - this.instance = instance; - this.validators = []; - this.getters = this.constructor.hasOwnProperty("getters") - ? this.constructor.getters.slice() - : []; - this.setters = []; - - this.splitPath(); +// require down here because of reference issues - options = options || {}; - const defaultOptions = this.constructor.defaultOptions || {}; - const defaultOptionsKeys = Object.keys(defaultOptions); - - for (const option of defaultOptionsKeys) { - if ( - defaultOptions.hasOwnProperty(option) && - !options.hasOwnProperty(option) - ) { - options[option] = defaultOptions[option]; - } - } +/** + * The various built-in Mongoose Schema Types. + * + * ####Example: + * + * const mongoose = require('mongoose'); + * const ObjectId = mongoose.Schema.Types.ObjectId; + * + * ####Types: + * + * - [String](/docs/schematypes.html#strings) + * - [Number](/docs/schematypes.html#numbers) + * - [Boolean](/docs/schematypes.html#booleans) | Bool + * - [Array](/docs/schematypes.html#arrays) + * - [Buffer](/docs/schematypes.html#buffers) + * - [Date](/docs/schematypes.html#dates) + * - [ObjectId](/docs/schematypes.html#objectids) | Oid + * - [Mixed](/docs/schematypes.html#mixed) + * + * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema. + * + * const Mixed = mongoose.Schema.Types.Mixed; + * new mongoose.Schema({ _user: Mixed }) + * + * @api public + */ - if (options.select == null) { - delete options.select; - } +Schema.Types = MongooseTypes = __nccwpck_require__(2987); - const Options = this.OptionsConstructor || SchemaTypeOptions; - this.options = new Options(options); - this._index = null; +/*! + * ignore + */ - if (utils.hasUserDefinedProperty(this.options, "immutable")) { - this.$immutable = this.options.immutable; +exports.ObjectId = MongooseTypes.ObjectId; - handleImmutable(this); - } - const keys = Object.keys(this.options); - for (const prop of keys) { - if (prop === "cast") { - this.castFunction(this.options[prop]); - continue; - } - if ( - utils.hasUserDefinedProperty(this.options, prop) && - typeof this[prop] === "function" - ) { - // { unique: true, index: true } - if (prop === "index" && this._index) { - if (options.index === false) { - const index = this._index; - if (typeof index === "object" && index != null) { - if (index.unique) { - throw new Error( - 'Path "' + - this.path + - '" may not have `index` ' + - "set to false and `unique` set to true" - ); - } - if (index.sparse) { - throw new Error( - 'Path "' + - this.path + - '" may not have `index` ' + - "set to false and `sparse` set to true" - ); - } - } +/***/ }), - this._index = false; - } - continue; - } +/***/ 2697: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const val = options[prop]; - // Special case so we don't screw up array defaults, see gh-5780 - if (prop === "default") { - this.default(val); - continue; - } +"use strict"; - const opts = Array.isArray(val) ? val : [val]; - this[prop].apply(this, opts); - } - } +/*! + * Module dependencies. + */ - Object.defineProperty(this, "$$context", { - enumerable: false, - configurable: false, - writable: true, - value: null, - }); - } +const CastError = __nccwpck_require__(2798); +const EventEmitter = __nccwpck_require__(8614).EventEmitter; +const ObjectExpectedError = __nccwpck_require__(2293); +const SchemaSubdocumentOptions = __nccwpck_require__(4244); +const SchemaType = __nccwpck_require__(5660); +const $exists = __nccwpck_require__(1426); +const castToNumber = __nccwpck_require__(9446)/* .castToNumber */ .W; +const discriminator = __nccwpck_require__(1462); +const geospatial = __nccwpck_require__(5061); +const get = __nccwpck_require__(8730); +const getConstructor = __nccwpck_require__(1449); +const handleIdOption = __nccwpck_require__(8965); +const internalToObjectOptions = __nccwpck_require__(5684)/* .internalToObjectOptions */ .h; +const utils = __nccwpck_require__(9232); + +let Subdocument; + +module.exports = SubdocumentPath; + +/** + * Single nested subdocument SchemaType constructor. + * + * @param {Schema} schema + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ - /*! - * The class that Mongoose uses internally to instantiate this SchemaType's `options` property. - */ +function SubdocumentPath(schema, path, options) { + schema = handleIdOption(schema, options); - SchemaType.prototype.OptionsConstructor = SchemaTypeOptions; + this.caster = _createConstructor(schema); + this.caster.path = path; + this.caster.prototype.$basePath = path; + this.schema = schema; + this.$isSingleNested = true; + SchemaType.call(this, path, options, 'Embedded'); +} - /*! - * ignore - */ +/*! + * ignore + */ - SchemaType.prototype.splitPath = function () { - if (this._presplitPath != null) { - return this._presplitPath; - } - if (this.path == null) { - return undefined; - } +SubdocumentPath.prototype = Object.create(SchemaType.prototype); +SubdocumentPath.prototype.constructor = SubdocumentPath; +SubdocumentPath.prototype.OptionsConstructor = SchemaSubdocumentOptions; - this._presplitPath = - this.path.indexOf(".") === -1 ? [this.path] : this.path.split("."); - return this._presplitPath; - }; +/*! + * ignore + */ - /** - * Get/set the function used to cast arbitrary values to this type. - * - * ####Example: - * - * // Disallow `null` for numbers, and don't try to cast any values to - * // numbers, so even strings like '123' will cause a CastError. - * mongoose.Number.cast(function(v) { - * assert.ok(v === undefined || typeof v === 'number'); - * return v; - * }); - * - * @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed - * @return {Function} - * @static - * @receiver SchemaType - * @function cast - * @api public - */ - - SchemaType.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = (v) => v; - } - this._cast = caster; - - return this._cast; - }; +function _createConstructor(schema, baseClass) { + // lazy load + Subdocument || (Subdocument = __nccwpck_require__(7302)); - /** - * Get/set the function used to cast arbitrary values to this particular schematype instance. - * Overrides `SchemaType.cast()`. - * - * ####Example: - * - * // Disallow `null` for numbers, and don't try to cast any values to - * // numbers, so even strings like '123' will cause a CastError. - * const number = new mongoose.Number('mypath', {}); - * number.cast(function(v) { - * assert.ok(v === undefined || typeof v === 'number'); - * return v; - * }); - * - * @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed - * @return {Function} - * @static - * @receiver SchemaType - * @function cast - * @api public - */ - - SchemaType.prototype.castFunction = function castFunction(caster) { - if (arguments.length === 0) { - return this._castFunction; - } - if (caster === false) { - caster = this.constructor._defaultCaster || ((v) => v); - } - this._castFunction = caster; - - return this._castFunction; - }; + const _embedded = function SingleNested(value, path, parent) { + const _this = this; - /** - * The function that Mongoose calls to cast arbitrary values to this SchemaType. - * - * @param {Object} value value to cast - * @param {Document} doc document that triggers the casting - * @param {Boolean} init - * @api public - */ - - SchemaType.prototype.cast = function cast() { - throw new Error( - "Base SchemaType class does not implement a `cast()` function" - ); - }; + this.$__parent = parent; + Subdocument.apply(this, arguments); - /** - * Sets a default option for this schema type. - * - * ####Example: - * - * // Make all strings be trimmed by default - * mongoose.SchemaTypes.String.set('trim', true); - * - * @param {String} option The name of the option you'd like to set (e.g. trim, lowercase, etc...) - * @param {*} value The value of the option you'd like to set. - * @return {void} - * @static - * @receiver SchemaType - * @function set - * @api public - */ - - SchemaType.set = function set(option, value) { - if (!this.hasOwnProperty("defaultOptions")) { - this.defaultOptions = Object.assign({}, this.defaultOptions); - } - this.defaultOptions[option] = value; - }; + this.$session(this.ownerDocument().$session()); - /** - * Attaches a getter for all instances of this schema type. - * - * ####Example: - * - * // Make all numbers round down - * mongoose.Number.get(function(v) { return Math.floor(v); }); - * - * @param {Function} getter - * @return {this} - * @static - * @receiver SchemaType - * @function get - * @api public - */ - - SchemaType.get = function (getter) { - this.getters = this.hasOwnProperty("getters") ? this.getters : []; - this.getters.push(getter); - }; + if (parent) { + parent.$on('save', function() { + _this.emit('save', _this); + _this.constructor.emit('save', _this); + }); - /** - * Sets a default value for this SchemaType. - * - * ####Example: - * - * const schema = new Schema({ n: { type: Number, default: 10 }) - * const M = db.model('M', schema) - * const m = new M; - * console.log(m.n) // 10 - * - * Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation. - * - * ####Example: - * - * // values are cast: - * const schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }}) - * const M = db.model('M', schema) - * const m = new M; - * console.log(m.aNumber) // 4.815162342 - * - * // default unique objects for Mixed types: - * const schema = new Schema({ mixed: Schema.Types.Mixed }); - * schema.path('mixed').default(function () { - * return {}; - * }); - * - * // if we don't use a function to return object literals for Mixed defaults, - * // each document will receive a reference to the same object literal creating - * // a "shared" object instance: - * const schema = new Schema({ mixed: Schema.Types.Mixed }); - * schema.path('mixed').default({}); - * const M = db.model('M', schema); - * const m1 = new M; - * m1.mixed.added = 1; - * console.log(m1.mixed); // { added: 1 } - * const m2 = new M; - * console.log(m2.mixed); // { added: 1 } - * - * @param {Function|any} val the default value - * @return {defaultValue} - * @api public - */ - - SchemaType.prototype.default = function (val) { - if (arguments.length === 1) { - if (val === void 0) { - this.defaultValue = void 0; - return void 0; - } + parent.$on('isNew', function(val) { + _this.isNew = val; + _this.emit('isNew', val); + _this.constructor.emit('isNew', val); + }); + } + }; - if (val != null && val.instanceOfSchema) { - throw new MongooseError( - "Cannot set default value of path `" + - this.path + - "` to a mongoose Schema instance." - ); - } + schema._preCompile(); + + const proto = baseClass != null ? baseClass.prototype : Subdocument.prototype; + _embedded.prototype = Object.create(proto); + _embedded.prototype.$__setSchema(schema); + _embedded.prototype.constructor = _embedded; + _embedded.schema = schema; + _embedded.$isSingleNested = true; + _embedded.events = new EventEmitter(); + _embedded.prototype.toBSON = function() { + return this.toObject(internalToObjectOptions); + }; - this.defaultValue = val; - return this.defaultValue; - } else if (arguments.length > 1) { - this.defaultValue = utils.args(arguments); - } - return this.defaultValue; - }; + // apply methods + for (const i in schema.methods) { + _embedded.prototype[i] = schema.methods[i]; + } - /** - * Declares the index options for this schematype. - * - * ####Example: - * - * const s = new Schema({ name: { type: String, index: true }) - * const s = new Schema({ loc: { type: [Number], index: 'hashed' }) - * const s = new Schema({ loc: { type: [Number], index: '2d', sparse: true }) - * const s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }}) - * const s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }}) - * s.path('my.path').index(true); - * s.path('my.date').index({ expires: 60 }); - * s.path('my.path').index({ unique: true, sparse: true }); - * - * ####NOTE: - * - * _Indexes are created [in the background](https://docs.mongodb.com/manual/core/index-creation/#index-creation-background) - * by default. If `background` is set to `false`, MongoDB will not execute any - * read/write operations you send until the index build. - * Specify `background: false` to override Mongoose's default._ - * - * @param {Object|Boolean|String} options - * @return {SchemaType} this - * @api public - */ - - SchemaType.prototype.index = function (options) { - this._index = options; - utils.expires(this._index); - return this; - }; + // apply statics + for (const i in schema.statics) { + _embedded[i] = schema.statics[i]; + } - /** - * Declares an unique index. - * - * ####Example: - * - * const s = new Schema({ name: { type: String, unique: true }}); - * s.path('name').index({ unique: true }); - * - * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._ - * - * @param {Boolean} bool - * @return {SchemaType} this - * @api public - */ - - SchemaType.prototype.unique = function (bool) { - if (this._index === false) { - if (!bool) { - return; - } - throw new Error( - 'Path "' + - this.path + - '" may not have `index` set to ' + - "false and `unique` set to true" - ); - } - if (this._index == null || this._index === true) { - this._index = {}; - } else if (typeof this._index === "string") { - this._index = { type: this._index }; - } + for (const i in EventEmitter.prototype) { + _embedded[i] = EventEmitter.prototype[i]; + } - this._index.unique = bool; - return this; - }; + return _embedded; +} - /** - * Declares a full text index. - * - * ###Example: - * - * const s = new Schema({name : {type: String, text : true }) - * s.path('name').index({text : true}); - * @param {Boolean} bool - * @return {SchemaType} this - * @api public - */ - - SchemaType.prototype.text = function (bool) { - if (this._index === false) { - if (!bool) { - return; - } - throw new Error( - 'Path "' + - this.path + - '" may not have `index` set to ' + - "false and `text` set to true" - ); - } +/*! + * Special case for when users use a common location schema to represent + * locations for use with $geoWithin. + * https://docs.mongodb.org/manual/reference/operator/query/geoWithin/ + * + * @param {Object} val + * @api private + */ - if ( - this._index === null || - this._index === undefined || - typeof this._index === "boolean" - ) { - this._index = {}; - } else if (typeof this._index === "string") { - this._index = { type: this._index }; - } +SubdocumentPath.prototype.$conditionalHandlers.$geoWithin = function handle$geoWithin(val) { + return { $geometry: this.castForQuery(val.$geometry) }; +}; - this._index.text = bool; - return this; - }; +/*! + * ignore + */ - /** - * Declares a sparse index. - * - * ####Example: - * - * const s = new Schema({ name: { type: String, sparse: true } }); - * s.path('name').index({ sparse: true }); - * - * @param {Boolean} bool - * @return {SchemaType} this - * @api public - */ - - SchemaType.prototype.sparse = function (bool) { - if (this._index === false) { - if (!bool) { - return; - } - throw new Error( - 'Path "' + - this.path + - '" may not have `index` set to ' + - "false and `sparse` set to true" - ); - } +SubdocumentPath.prototype.$conditionalHandlers.$near = +SubdocumentPath.prototype.$conditionalHandlers.$nearSphere = geospatial.cast$near; - if (this._index == null || typeof this._index === "boolean") { - this._index = {}; - } else if (typeof this._index === "string") { - this._index = { type: this._index }; - } +SubdocumentPath.prototype.$conditionalHandlers.$within = +SubdocumentPath.prototype.$conditionalHandlers.$geoWithin = geospatial.cast$within; - this._index.sparse = bool; - return this; - }; +SubdocumentPath.prototype.$conditionalHandlers.$geoIntersects = + geospatial.cast$geoIntersects; - /** - * Defines this path as immutable. Mongoose prevents you from changing - * immutable paths unless the parent document has [`isNew: true`](/docs/api.html#document_Document-isNew). - * - * ####Example: - * - * const schema = new Schema({ - * name: { type: String, immutable: true }, - * age: Number - * }); - * const Model = mongoose.model('Test', schema); - * - * await Model.create({ name: 'test' }); - * const doc = await Model.findOne(); - * - * doc.isNew; // false - * doc.name = 'new name'; - * doc.name; // 'test', because `name` is immutable - * - * Mongoose also prevents changing immutable properties using `updateOne()` - * and `updateMany()` based on [strict mode](/docs/guide.html#strict). - * - * ####Example: - * - * // Mongoose will strip out the `name` update, because `name` is immutable - * Model.updateOne({}, { $set: { name: 'test2' }, $inc: { age: 1 } }); - * - * // If `strict` is set to 'throw', Mongoose will throw an error if you - * // update `name` - * const err = await Model.updateOne({}, { name: 'test2' }, { strict: 'throw' }). - * then(() => null, err => err); - * err.name; // StrictModeError - * - * // If `strict` is `false`, Mongoose allows updating `name` even though - * // the property is immutable. - * Model.updateOne({}, { name: 'test2' }, { strict: false }); - * - * @param {Boolean} bool - * @return {SchemaType} this - * @see isNew /docs/api.html#document_Document-isNew - * @api public - */ - - SchemaType.prototype.immutable = function (bool) { - this.$immutable = bool; - handleImmutable(this); +SubdocumentPath.prototype.$conditionalHandlers.$minDistance = castToNumber; +SubdocumentPath.prototype.$conditionalHandlers.$maxDistance = castToNumber; - return this; - }; +SubdocumentPath.prototype.$conditionalHandlers.$exists = $exists; - /** - * Defines a custom function for transforming this path when converting a document to JSON. - * - * Mongoose calls this function with one parameter: the current `value` of the path. Mongoose - * then uses the return value in the JSON output. - * - * ####Example: - * - * const schema = new Schema({ - * date: { type: Date, transform: v => v.getFullYear() } - * }); - * const Model = mongoose.model('Test', schema); - * - * await Model.create({ date: new Date('2016-06-01') }); - * const doc = await Model.findOne(); - * - * doc.date instanceof Date; // true - * - * doc.toJSON().date; // 2016 as a number - * JSON.stringify(doc); // '{"_id":...,"date":2016}' - * - * @param {Function} fn - * @return {SchemaType} this - * @api public - */ - - SchemaType.prototype.transform = function (fn) { - this.options.transform = fn; +/** + * Casts contents + * + * @param {Object} value + * @api private + */ - return this; - }; +SubdocumentPath.prototype.cast = function(val, doc, init, priorVal, options) { + if (val && val.$isSingleNested && val.parent === doc) { + return val; + } - /** - * Adds a setter to this schematype. - * - * ####Example: - * - * function capitalize (val) { - * if (typeof val !== 'string') val = ''; - * return val.charAt(0).toUpperCase() + val.substring(1); - * } - * - * // defining within the schema - * const s = new Schema({ name: { type: String, set: capitalize }}); - * - * // or with the SchemaType - * const s = new Schema({ name: String }) - * s.path('name').set(capitalize); - * - * Setters allow you to transform the data before it gets to the raw mongodb - * document or query. - * - * Suppose you are implementing user registration for a website. Users provide - * an email and password, which gets saved to mongodb. The email is a string - * that you will want to normalize to lower case, in order to avoid one email - * having more than one account -- e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM. - * - * You can set up email lower case normalization easily via a Mongoose setter. - * - * function toLower(v) { - * return v.toLowerCase(); - * } - * - * const UserSchema = new Schema({ - * email: { type: String, set: toLower } - * }); - * - * const User = db.model('User', UserSchema); - * - * const user = new User({email: 'AVENUE@Q.COM'}); - * console.log(user.email); // 'avenue@q.com' - * - * // or - * const user = new User(); - * user.email = 'Avenue@Q.com'; - * console.log(user.email); // 'avenue@q.com' - * User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } }); // update to 'avenue@q.com' - * - * As you can see above, setters allow you to transform the data before it - * stored in MongoDB, or before executing a query. - * - * _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._ - * - * new Schema({ email: { type: String, lowercase: true }}) - * - * Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema. - * - * function inspector (val, schematype) { - * if (schematype.options.required) { - * return schematype.path + ' is required'; - * } else { - * return val; - * } - * } - * - * const VirusSchema = new Schema({ - * name: { type: String, required: true, set: inspector }, - * taxonomy: { type: String, set: inspector } - * }) - * - * const Virus = db.model('Virus', VirusSchema); - * const v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' }); - * - * console.log(v.name); // name is required - * console.log(v.taxonomy); // Parvovirinae - * - * You can also use setters to modify other properties on the document. If - * you're setting a property `name` on a document, the setter will run with - * `this` as the document. Be careful, in mongoose 5 setters will also run - * when querying by `name` with `this` as the query. - * - * ```javascript - * const nameSchema = new Schema({ name: String, keywords: [String] }); - * nameSchema.path('name').set(function(v) { - * // Need to check if `this` is a document, because in mongoose 5 - * // setters will also run on queries, in which case `this` will be a - * // mongoose query object. - * if (this instanceof Document && v != null) { - * this.keywords = v.split(' '); - * } - * return v; - * }); - * ``` - * - * @param {Function} fn - * @return {SchemaType} this - * @api public - */ - - SchemaType.prototype.set = function (fn) { - if (typeof fn !== "function") { - throw new TypeError("A setter must be a function."); - } - this.setters.push(fn); - return this; - }; + if (val != null && (typeof val !== 'object' || Array.isArray(val))) { + throw new ObjectExpectedError(this.path, val); + } - /** - * Adds a getter to this schematype. - * - * ####Example: - * - * function dob (val) { - * if (!val) return val; - * return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear(); - * } - * - * // defining within the schema - * const s = new Schema({ born: { type: Date, get: dob }) - * - * // or by retreiving its SchemaType - * const s = new Schema({ born: Date }) - * s.path('born').get(dob) - * - * Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see. - * - * Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way: - * - * function obfuscate (cc) { - * return '****-****-****-' + cc.slice(cc.length-4, cc.length); - * } - * - * const AccountSchema = new Schema({ - * creditCardNumber: { type: String, get: obfuscate } - * }); - * - * const Account = db.model('Account', AccountSchema); - * - * Account.findById(id, function (err, found) { - * console.log(found.creditCardNumber); // '****-****-****-1234' - * }); - * - * Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema. - * - * function inspector (val, schematype) { - * if (schematype.options.required) { - * return schematype.path + ' is required'; - * } else { - * return schematype.path + ' is not'; - * } - * } - * - * const VirusSchema = new Schema({ - * name: { type: String, required: true, get: inspector }, - * taxonomy: { type: String, get: inspector } - * }) - * - * const Virus = db.model('Virus', VirusSchema); - * - * Virus.findById(id, function (err, virus) { - * console.log(virus.name); // name is required - * console.log(virus.taxonomy); // taxonomy is not - * }) - * - * @param {Function} fn - * @return {SchemaType} this - * @api public - */ - - SchemaType.prototype.get = function (fn) { - if (typeof fn !== "function") { - throw new TypeError("A getter must be a function."); - } - this.getters.push(fn); - return this; - }; + const Constructor = getConstructor(this.caster, val); - /** - * Adds validator(s) for this document path. - * - * Validators always receive the value to validate as their first argument and - * must return `Boolean`. Returning `false` or throwing an error means - * validation failed. - * - * The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used. - * - * ####Examples: - * - * // make sure every value is equal to "something" - * function validator (val) { - * return val == 'something'; - * } - * new Schema({ name: { type: String, validate: validator }}); - * - * // with a custom error message - * - * const custom = [validator, 'Uh oh, {PATH} does not equal "something".'] - * new Schema({ name: { type: String, validate: custom }}); - * - * // adding many validators at a time - * - * const many = [ - * { validator: validator, msg: 'uh oh' } - * , { validator: anotherValidator, msg: 'failed' } - * ] - * new Schema({ name: { type: String, validate: many }}); - * - * // or utilizing SchemaType methods directly: - * - * const schema = new Schema({ name: 'string' }); - * schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`'); - * - * ####Error message templates: - * - * From the examples above, you may have noticed that error messages support - * basic templating. There are a few other template keywords besides `{PATH}` - * and `{VALUE}` too. To find out more, details are available - * [here](#error_messages_MongooseError.messages). - * - * If Mongoose's built-in error message templating isn't enough, Mongoose - * supports setting the `message` property to a function. - * - * schema.path('name').validate({ - * validator: function() { return v.length > 5; }, - * // `errors['name']` will be "name must have length 5, got 'foo'" - * message: function(props) { - * return `${props.path} must have length 5, got '${props.value}'`; - * } - * }); - * - * To bypass Mongoose's error messages and just copy the error message that - * the validator throws, do this: - * - * schema.path('name').validate({ - * validator: function() { throw new Error('Oops!'); }, - * // `errors['name']` will be "Oops!" - * message: function(props) { return props.reason.message; } - * }); - * - * ####Asynchronous validation: - * - * Mongoose supports validators that return a promise. A validator that returns - * a promise is called an _async validator_. Async validators run in - * parallel, and `validate()` will wait until all async validators have settled. - * - * schema.path('name').validate({ - * validator: function (value) { - * return new Promise(function (resolve, reject) { - * resolve(false); // validation failed - * }); - * } - * }); - * - * You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs. - * - * Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate). - * - * If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along. - * - * const conn = mongoose.createConnection(..); - * conn.on('error', handleError); - * - * const Product = conn.model('Product', yourSchema); - * const dvd = new Product(..); - * dvd.save(); // emits error on the `conn` above - * - * If you want to handle these errors at the Model level, add an `error` - * listener to your Model as shown below. - * - * // registering an error listener on the Model lets us handle errors more locally - * Product.on('error', handleError); - * - * @param {RegExp|Function|Object} obj validator function, or hash describing options - * @param {Function} [obj.validator] validator function. If the validator function returns `undefined` or a truthy value, validation succeeds. If it returns [falsy](https://masteringjs.io/tutorials/fundamentals/falsy) (except `undefined`) or throws an error, validation fails. - * @param {String|Function} [obj.message] optional error message. If function, should return the error message as a string - * @param {Boolean} [obj.propsParameter=false] If true, Mongoose will pass the validator properties object (with the `validator` function, `message`, etc.) as the 2nd arg to the validator function. This is disabled by default because many validators [rely on positional args](https://github.com/chriso/validator.js#validators), so turning this on may cause unpredictable behavior in external validators. - * @param {String|Function} [errorMsg] optional error message. If function, should return the error message as a string - * @param {String} [type] optional validator type - * @return {SchemaType} this - * @api public - */ - - SchemaType.prototype.validate = function (obj, message, type) { - if ( - typeof obj === "function" || - (obj && utils.getFunctionName(obj.constructor) === "RegExp") - ) { - let properties; - if (typeof message === "function") { - properties = { validator: obj, message: message }; - properties.type = type || "user defined"; - } else if (message instanceof Object && !type) { - properties = utils.clone(message); - if (!properties.message) { - properties.message = properties.msg; - } - properties.validator = obj; - properties.type = properties.type || "user defined"; - } else { - if (message == null) { - message = MongooseError.messages.general.default; - } - if (!type) { - type = "user defined"; - } - properties = { message: message, type: type, validator: obj }; - } + let subdoc; - if (properties.isAsync) { - handleIsAsync(); - } + // Only pull relevant selected paths and pull out the base path + const parentSelected = get(doc, '$__.selected', {}); + const path = this.path; + const selected = Object.keys(parentSelected).reduce((obj, key) => { + if (key.startsWith(path + '.')) { + obj[key.substr(path.length + 1)] = parentSelected[key]; + } + return obj; + }, {}); + options = Object.assign({}, options, { priorDoc: priorVal }); + if (init) { + subdoc = new Constructor(void 0, selected, doc); + subdoc.$init(val); + } else { + if (Object.keys(val).length === 0) { + return new Constructor({}, selected, doc, undefined, options); + } - this.validators.push(properties); - return this; - } + return new Constructor(val, selected, doc, undefined, options); + } - let i; - let length; - let arg; + return subdoc; +}; - for (i = 0, length = arguments.length; i < length; i++) { - arg = arguments[i]; - if (!utils.isPOJO(arg)) { - const msg = - "Invalid validator. Received (" + - typeof arg + - ") " + - arg + - ". See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate"; +/** + * Casts contents for query + * + * @param {string} [$conditional] optional query operator (like `$eq` or `$in`) + * @param {any} value + * @api private + */ - throw new Error(msg); - } - this.validate(arg.validator, arg); - } +SubdocumentPath.prototype.castForQuery = function($conditional, val, options) { + let handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional); + } + return handler.call(this, val); + } + val = $conditional; + if (val == null) { + return val; + } - return this; - }; + if (this.options.runSetters) { + val = this._applySetters(val); + } - /*! - * ignore - */ - - const handleIsAsync = util.deprecate(function handleIsAsync() {}, - "Mongoose: the `isAsync` option for custom validators is deprecated. Make " + "your async validators return a promise instead: " + "https://mongoosejs.com/docs/validation.html#async-custom-validators"); - - /** - * Adds a required validator to this SchemaType. The validator gets added - * to the front of this SchemaType's validators array using `unshift()`. - * - * ####Example: - * - * const s = new Schema({ born: { type: Date, required: true }) - * - * // or with custom error message - * - * const s = new Schema({ born: { type: Date, required: '{PATH} is required!' }) - * - * // or with a function - * - * const s = new Schema({ - * userId: ObjectId, - * username: { - * type: String, - * required: function() { return this.userId != null; } - * } - * }) - * - * // or with a function and a custom message - * const s = new Schema({ - * userId: ObjectId, - * username: { - * type: String, - * required: [ - * function() { return this.userId != null; }, - * 'username is required if id is specified' - * ] - * } - * }) - * - * // or through the path API - * - * s.path('name').required(true); - * - * // with custom error messaging - * - * s.path('name').required(true, 'grrr :( '); - * - * // or make a path conditionally required based on a function - * const isOver18 = function() { return this.age >= 18; }; - * s.path('voterRegistrationId').required(isOver18); - * - * The required validator uses the SchemaType's `checkRequired` function to - * determine whether a given value satisfies the required validator. By default, - * a value satisfies the required validator if `val != null` (that is, if - * the value is not null nor undefined). However, most built-in mongoose schema - * types override the default `checkRequired` function: - * - * @param {Boolean|Function|Object} required enable/disable the validator, or function that returns required boolean, or options object - * @param {Boolean|Function} [options.isRequired] enable/disable the validator, or function that returns required boolean - * @param {Function} [options.ErrorConstructor] custom error constructor. The constructor receives 1 parameter, an object containing the validator properties. - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @see SchemaArray#checkRequired #schema_array_SchemaArray.checkRequired - * @see SchemaBoolean#checkRequired #schema_boolean_SchemaBoolean-checkRequired - * @see SchemaBuffer#checkRequired #schema_buffer_SchemaBuffer.schemaName - * @see SchemaNumber#checkRequired #schema_number_SchemaNumber-min - * @see SchemaObjectId#checkRequired #schema_objectid_ObjectId-auto - * @see SchemaString#checkRequired #schema_string_SchemaString-checkRequired - * @api public - */ - - SchemaType.prototype.required = function (required, message) { - let customOptions = {}; - - if (arguments.length > 0 && required == null) { - this.validators = this.validators.filter(function (v) { - return v.validator !== this.requiredValidator; - }, this); - - this.isRequired = false; - delete this.originalRequiredValue; - return this; - } + const Constructor = getConstructor(this.caster, val); + const overrideStrict = options != null && options.strict != null ? + options.strict : + void 0; + + try { + val = new Constructor(val, overrideStrict); + } catch (error) { + // Make sure we always wrap in a CastError (gh-6803) + if (!(error instanceof CastError)) { + throw new CastError('Embedded', val, this.path, error, this); + } + throw error; + } + return val; +}; - if (typeof required === "object") { - customOptions = required; - message = customOptions.message || message; - required = required.isRequired; - } +/** + * Async validation on this single nested doc. + * + * @api private + */ - if (required === false) { - this.validators = this.validators.filter(function (v) { - return v.validator !== this.requiredValidator; - }, this); +SubdocumentPath.prototype.doValidate = function(value, fn, scope, options) { + const Constructor = getConstructor(this.caster, value); - this.isRequired = false; - delete this.originalRequiredValue; - return this; - } + if (value && !(value instanceof Constructor)) { + value = new Constructor(value, null, scope); + } - const _this = this; - this.isRequired = true; + if (options && options.skipSchemaValidators) { + return value.validate(fn); + } - this.requiredValidator = function (v) { - const cachedRequired = get(this, "$__.cachedRequired"); + SchemaType.prototype.doValidate.call(this, value, function(error) { + if (error) { + return fn(error); + } + if (!value) { + return fn(null); + } - // no validation when this path wasn't selected in the query. - if ( - cachedRequired != null && - !this.$__isSelected(_this.path) && - !this[documentIsModified](_this.path) - ) { - return true; - } + value.validate(fn); + }, scope, options); +}; - // `$cachedRequired` gets set in `_evaluateRequiredFunctions()` so we - // don't call required functions multiple times in one validate call - // See gh-6801 - if (cachedRequired != null && _this.path in cachedRequired) { - const res = cachedRequired[_this.path] - ? _this.checkRequired(v, this) - : true; - delete cachedRequired[_this.path]; - return res; - } else if (typeof required === "function") { - return required.apply(this) ? _this.checkRequired(v, this) : true; - } +/** + * Synchronously validate this single nested doc + * + * @api private + */ - return _this.checkRequired(v, this); - }; - this.originalRequiredValue = required; +SubdocumentPath.prototype.doValidateSync = function(value, scope, options) { + if (!options || !options.skipSchemaValidators) { + const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope); + if (schemaTypeError) { + return schemaTypeError; + } + } + if (!value) { + return; + } + return value.validateSync(); +}; - if (typeof required === "string") { - message = required; - required = undefined; - } +/** + * Adds a discriminator to this single nested subdocument. + * + * ####Example: + * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' }); + * const schema = Schema({ shape: shapeSchema }); + * + * const singleNestedPath = parentSchema.path('shape'); + * singleNestedPath.discriminator('Circle', Schema({ radius: Number })); + * + * @param {String} name + * @param {Schema} schema fields to add to the schema for instances of this sub-class + * @param {Object|string} [options] If string, same as `options.value`. + * @param {String} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. + * @param {Boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning. + * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model + * @see discriminators /docs/discriminators.html + * @api public + */ - const msg = message || MongooseError.messages.general.required; - this.validators.unshift( - Object.assign({}, customOptions, { - validator: this.requiredValidator, - message: msg, - type: "required", - }) - ); +SubdocumentPath.prototype.discriminator = function(name, schema, options) { + options = options || {}; + const value = utils.isPOJO(options) ? options.value : options; + const clone = get(options, 'clone', true); - return this; - }; + if (schema.instanceOfSchema && clone) { + schema = schema.clone(); + } - /** - * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html) - * looks at to determine the foreign collection it should query. - * - * ####Example: - * const userSchema = new Schema({ name: String }); - * const User = mongoose.model('User', userSchema); - * - * const postSchema = new Schema({ user: mongoose.ObjectId }); - * postSchema.path('user').ref('User'); // Can set ref to a model name - * postSchema.path('user').ref(User); // Or a model class - * postSchema.path('user').ref(() => 'User'); // Or a function that returns the model name - * postSchema.path('user').ref(() => User); // Or a function that returns the model class - * - * // Or you can just declare the `ref` inline in your schema - * const postSchema2 = new Schema({ - * user: { type: mongoose.ObjectId, ref: User } - * }); - * - * @param {String|Model|Function} ref either a model name, a [Model](https://mongoosejs.com/docs/models.html), or a function that returns a model name or model. - * @return {SchemaType} this - * @api public - */ - - SchemaType.prototype.ref = function (ref) { - this.options.ref = ref; - return this; - }; + schema = discriminator(this.caster, name, schema, value); - /** - * Gets the default value - * - * @param {Object} scope the scope which callback are executed - * @param {Boolean} init - * @api private - */ - - SchemaType.prototype.getDefault = function (scope, init) { - let ret = - typeof this.defaultValue === "function" - ? this.defaultValue.call(scope) - : this.defaultValue; - - if (ret !== null && ret !== undefined) { - if ( - typeof ret === "object" && - (!this.options || !this.options.shared) - ) { - ret = utils.clone(ret); - } + this.caster.discriminators[name] = _createConstructor(schema, this.caster); - const casted = this.applySetters(ret, scope, init); - if (casted && casted.$isSingleNested) { - casted.$__parent = scope; - } - return casted; - } - return ret; - }; + return this.caster.discriminators[name]; +}; - /*! - * Applies setters without casting - * - * @api private - */ +/** + * Sets a default option for all SubdocumentPath instances. + * + * ####Example: + * + * // Make all numbers have option `min` equal to 0. + * mongoose.Schema.Embedded.set('required', true); + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ - SchemaType.prototype._applySetters = function (value, scope, init) { - let v = value; - if (init) { - return v; - } - const setters = this.setters; +SubdocumentPath.defaultOptions = {}; - for (let i = setters.length - 1; i >= 0; i--) { - v = setters[i].call(scope, v, this); - } +SubdocumentPath.set = SchemaType.set; - return v; - }; +/*! + * ignore + */ - /*! - * ignore - */ +SubdocumentPath.prototype.clone = function() { + const options = Object.assign({}, this.options); + const schematype = new this.constructor(this.schema, this.path, options); + schematype.validators = this.validators.slice(); + if (this.requiredValidator !== undefined) { + schematype.requiredValidator = this.requiredValidator; + } + schematype.caster.discriminators = Object.assign({}, this.caster.discriminators); + return schematype; +}; - SchemaType.prototype._castNullish = function _castNullish(v) { - return v; - }; - /** - * Applies setters - * - * @param {Object} value - * @param {Object} scope - * @param {Boolean} init - * @api private - */ - - SchemaType.prototype.applySetters = function ( - value, - scope, - init, - priorVal, - options - ) { - let v = this._applySetters(value, scope, init, priorVal, options); - if (v == null) { - return this._castNullish(v); - } - - // do not cast until all setters are applied #665 - v = this.cast(v, scope, init, priorVal, options); +/***/ }), - return v; - }; +/***/ 6090: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Applies getters to a value - * - * @param {Object} value - * @param {Object} scope - * @api private - */ +"use strict"; - SchemaType.prototype.applyGetters = function (value, scope) { - let v = value; - const getters = this.getters; - const len = getters.length; - if (len === 0) { - return v; - } +/*! + * Module dependencies. + */ - for (let i = 0; i < len; ++i) { - v = getters[i].call(scope, v, this); - } +const $exists = __nccwpck_require__(1426); +const $type = __nccwpck_require__(4093); +const MongooseError = __nccwpck_require__(5953); +const SchemaArrayOptions = __nccwpck_require__(7391); +const SchemaType = __nccwpck_require__(5660); +const CastError = SchemaType.CastError; +const Mixed = __nccwpck_require__(7495); +const arrayDepth = __nccwpck_require__(8906); +const cast = __nccwpck_require__(9179); +const get = __nccwpck_require__(8730); +const isOperator = __nccwpck_require__(3342); +const util = __nccwpck_require__(1669); +const utils = __nccwpck_require__(9232); +const castToNumber = __nccwpck_require__(9446)/* .castToNumber */ .W; +const geospatial = __nccwpck_require__(5061); +const getDiscriminatorByValue = __nccwpck_require__(8689); + +let MongooseArray; +let EmbeddedDoc; + +const isNestedArraySymbol = Symbol('mongoose#isNestedArray'); +const emptyOpts = Object.freeze({}); + +/** + * Array SchemaType constructor + * + * @param {String} key + * @param {SchemaType} cast + * @param {Object} options + * @inherits SchemaType + * @api public + */ - return v; - }; +function SchemaArray(key, cast, options, schemaOptions) { + // lazy load + EmbeddedDoc || (EmbeddedDoc = __nccwpck_require__(3000).Embedded); - /** - * Sets default `select()` behavior for this path. - * - * Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level. - * - * ####Example: - * - * T = db.model('T', new Schema({ x: { type: String, select: true }})); - * T.find(..); // field x will always be selected .. - * // .. unless overridden; - * T.find().select('-x').exec(callback); - * - * @param {Boolean} val - * @return {SchemaType} this - * @api public - */ - - SchemaType.prototype.select = function select(val) { - this.selected = !!val; - return this; - }; + let typeKey = 'type'; + if (schemaOptions && schemaOptions.typeKey) { + typeKey = schemaOptions.typeKey; + } + this.schemaOptions = schemaOptions; - /** - * Performs a validation of `value` using the validators declared for this SchemaType. - * - * @param {any} value - * @param {Function} callback - * @param {Object} scope - * @api private - */ - - SchemaType.prototype.doValidate = function (value, fn, scope, options) { - let err = false; - const path = this.path; - - // Avoid non-object `validators` - const validators = this.validators.filter( - (v) => v != null && typeof v === "object" - ); + if (cast) { + let castOptions = {}; - let count = validators.length; + if (utils.isPOJO(cast)) { + if (cast[typeKey]) { + // support { type: Woot } + castOptions = utils.clone(cast); // do not alter user arguments + delete castOptions[typeKey]; + cast = cast[typeKey]; + } else { + cast = Mixed; + } + } - if (!count) { - return fn(null); - } + if (options != null && options.ref != null && castOptions.ref == null) { + castOptions.ref = options.ref; + } - const _this = this; - validators.forEach(function (v) { - if (err) { - return; - } + if (cast === Object) { + cast = Mixed; + } - const validator = v.validator; - let ok; + // support { type: 'String' } + const name = typeof cast === 'string' + ? cast + : utils.getFunctionName(cast); - const validatorProperties = utils.clone(v); - validatorProperties.path = - options && options.path ? options.path : path; - validatorProperties.value = value; + const Types = __nccwpck_require__(2987); + const caster = Types.hasOwnProperty(name) ? Types[name] : cast; - if (validator instanceof RegExp) { - validate(validator.test(value), validatorProperties); - return; - } + this.casterConstructor = caster; - if (typeof validator !== "function") { - return; - } + if (this.casterConstructor instanceof SchemaArray) { + this.casterConstructor[isNestedArraySymbol] = true; + } - if (value === undefined && validator !== _this.requiredValidator) { - validate(true, validatorProperties); - return; - } + if (typeof caster === 'function' && + !caster.$isArraySubdocument && + !caster.$isSchemaMap) { + const path = this.caster instanceof EmbeddedDoc ? null : key; + this.caster = new caster(path, castOptions); + } else { + this.caster = caster; + if (!(this.caster instanceof EmbeddedDoc)) { + this.caster.path = key; + } + } - if (validatorProperties.isAsync) { - asyncValidate( - validator, - scope, - value, - validatorProperties, - validate - ); - return; - } + this.$embeddedSchemaType = this.caster; + } - try { - if (validatorProperties.propsParameter) { - ok = validator.call(scope, value, validatorProperties); - } else { - ok = validator.call(scope, value); - } - } catch (error) { - ok = false; - validatorProperties.reason = error; - if (error.message) { - validatorProperties.message = error.message; - } - } + this.$isMongooseArray = true; - if (ok != null && typeof ok.then === "function") { - ok.then( - function (ok) { - validate(ok, validatorProperties); - }, - function (error) { - validatorProperties.reason = error; - validatorProperties.message = error.message; - ok = false; - validate(ok, validatorProperties); - } - ); - } else { - validate(ok, validatorProperties); - } - }); + SchemaType.call(this, key, options, 'Array'); - function validate(ok, validatorProperties) { - if (err) { - return; - } - if (ok === undefined || ok) { - if (--count <= 0) { - immediate(function () { - fn(null); - }); - } - } else { - const ErrorConstructor = - validatorProperties.ErrorConstructor || ValidatorError; - err = new ErrorConstructor(validatorProperties); - err[validatorErrorSymbol] = true; - immediate(function () { - fn(err); - }); - } - } - }; + let defaultArr; + let fn; - /*! - * Handle async validators - */ - - function asyncValidate(validator, scope, value, props, cb) { - let called = false; - const returnVal = validator.call( - scope, - value, - function (ok, customMsg) { - if (called) { - return; - } - called = true; - if (customMsg) { - props.message = customMsg; - } - cb(ok, props); - } - ); - if (typeof returnVal === "boolean") { - called = true; - cb(returnVal, props); - } else if (returnVal && typeof returnVal.then === "function") { - // Promise - returnVal.then( - function (ok) { - if (called) { - return; - } - called = true; - cb(ok, props); - }, - function (error) { - if (called) { - return; - } - called = true; + if (this.defaultValue != null) { + defaultArr = this.defaultValue; + fn = typeof defaultArr === 'function'; + } - props.reason = error; - props.message = error.message; - cb(false, props); - } - ); - } + if (!('defaultValue' in this) || this.defaultValue !== void 0) { + const defaultFn = function() { + let arr = []; + if (fn) { + arr = defaultArr.call(this); + } else if (defaultArr != null) { + arr = arr.concat(defaultArr); } + // Leave it up to `cast()` to convert the array + return arr; + }; + defaultFn.$runBeforeSetters = !fn; + this.default(defaultFn); + } +} - /** - * Performs a validation of `value` using the validators declared for this SchemaType. - * - * ####Note: - * - * This method ignores the asynchronous validators. - * - * @param {any} value - * @param {Object} scope - * @return {MongooseError|undefined} - * @api private - */ +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaArray.schemaName = 'Array'; - SchemaType.prototype.doValidateSync = function (value, scope, options) { - const path = this.path; - const count = this.validators.length; - if (!count) { - return null; - } +/** + * Options for all arrays. + * + * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting. + * + * @static options + * @api public + */ - let validators = this.validators; - if (value === void 0) { - if ( - this.validators.length > 0 && - this.validators[0].type === "required" - ) { - validators = [this.validators[0]]; - } else { - return null; - } - } +SchemaArray.options = { castNonArrays: true }; - let err = null; - validators.forEach(function (v) { - if (err) { - return; - } +/*! + * ignore + */ - if (v == null || typeof v !== "object") { - return; - } +SchemaArray.defaultOptions = {}; - const validator = v.validator; - const validatorProperties = utils.clone(v); - validatorProperties.path = - options && options.path ? options.path : path; - validatorProperties.value = value; - let ok; +/** + * Sets a default option for all Array instances. + * + * ####Example: + * + * // Make all Array instances have `required` of true by default. + * mongoose.Schema.Array.set('required', true); + * + * const User = mongoose.model('User', new Schema({ test: Array })); + * new User({ }).validateSync().errors.test.message; // Path `test` is required. + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @api public + */ +SchemaArray.set = SchemaType.set; - // Skip any explicit async validators. Validators that return a promise - // will still run, but won't trigger any errors. - if (validator.isAsync) { - return; - } +/*! + * Inherits from SchemaType. + */ +SchemaArray.prototype = Object.create(SchemaType.prototype); +SchemaArray.prototype.constructor = SchemaArray; +SchemaArray.prototype.OptionsConstructor = SchemaArrayOptions; - if (validator instanceof RegExp) { - validate(validator.test(value), validatorProperties); - return; - } +/*! + * ignore + */ - if (typeof validator !== "function") { - return; - } +SchemaArray._checkRequired = SchemaType.prototype.checkRequired; - try { - if (validatorProperties.propsParameter) { - ok = validator.call(scope, value, validatorProperties); - } else { - ok = validator.call(scope, value); - } - } catch (error) { - ok = false; - validatorProperties.reason = error; - } +/** + * Override the function the required validator uses to check whether an array + * passes the `required` check. + * + * ####Example: + * + * // Require non-empty array to pass `required` check + * mongoose.Schema.Types.Array.checkRequired(v => Array.isArray(v) && v.length); + * + * const M = mongoose.model({ arr: { type: Array, required: true } }); + * new M({ arr: [] }).validateSync(); // `null`, validation fails! + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @api public + */ - // Skip any validators that return a promise, we can't handle those - // synchronously - if (ok != null && typeof ok.then === "function") { - return; - } - validate(ok, validatorProperties); - }); +SchemaArray.checkRequired = SchemaType.checkRequired; - return err; +/** + * Check if the given value satisfies the `required` validator. + * + * @param {Any} value + * @param {Document} doc + * @return {Boolean} + * @api public + */ - function validate(ok, validatorProperties) { - if (err) { - return; - } - if (ok !== undefined && !ok) { - const ErrorConstructor = - validatorProperties.ErrorConstructor || ValidatorError; - err = new ErrorConstructor(validatorProperties); - err[validatorErrorSymbol] = true; - } - } - }; +SchemaArray.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } - /** - * Determines if value is a valid Reference. - * - * @param {SchemaType} self - * @param {Object} value - * @param {Document} doc - * @param {Boolean} init - * @return {Boolean} - * @api private - */ - - SchemaType._isRef = function (self, value, doc, init) { - // fast path - let ref = - init && self.options && (self.options.ref || self.options.refPath); - - if (!ref && doc && doc.$__ != null) { - // checks for - // - this populated with adhoc model and no ref was set in schema OR - // - setting / pushing values after population - const path = doc.$__fullPath(self.path); - const owner = doc.ownerDocument ? doc.ownerDocument() : doc; - ref = owner.populated(path) || doc.populated(self.path); - } - - if (ref) { - if (value == null) { - return true; - } - if ( - !Buffer.isBuffer(value) && // buffers are objects too - value._bsontype !== "Binary" && // raw binary value from the db - utils.isObject(value) // might have deselected _id in population query - ) { - return true; - } + // `require('util').inherits()` does **not** copy static properties, and + // plugins like mongoose-float use `inherits()` for pre-ES6. + const _checkRequired = typeof this.constructor.checkRequired == 'function' ? + this.constructor.checkRequired() : + SchemaArray.checkRequired(); - return init; - } + return _checkRequired(value); +}; - return false; - }; +/** + * Adds an enum validator if this is an array of strings or numbers. Equivalent to + * `SchemaString.prototype.enum()` or `SchemaNumber.prototype.enum()` + * + * @param {String|Object} [args...] enumeration values + * @return {SchemaArray} this + */ - /*! - * ignore - */ +SchemaArray.prototype.enum = function() { + let arr = this; + while (true) { + const instance = get(arr, 'caster.instance'); + if (instance === 'Array') { + arr = arr.caster; + continue; + } + if (instance !== 'String' && instance !== 'Number') { + throw new Error('`enum` can only be set on an array of strings or numbers ' + + ', not ' + instance); + } + break; + } - SchemaType.prototype._castRef = function _castRef(value, doc, init) { - if (value == null) { - return value; - } + let enumArray = arguments; + if (!Array.isArray(arguments) && utils.isObject(arguments)) { + enumArray = utils.object.vals(enumArray); + } - if (value.$__ != null) { - value.$__.wasPopulated = true; - return value; - } + arr.caster.enum.apply(arr.caster, enumArray); + return this; +}; - // setting a populated path - if (Buffer.isBuffer(value) || !utils.isObject(value)) { - if (init) { - return value; - } - throw new CastError(this.instance, value, this.path, null, this); - } +/** + * Overrides the getters application for the population special-case + * + * @param {Object} value + * @param {Object} scope + * @api private + */ - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - const path = doc.$__fullPath(this.path); - const owner = doc.ownerDocument ? doc.ownerDocument() : doc; - const pop = owner.populated(path, true); - let ret = value; - if ( - !doc.$__.populated || - !doc.$__.populated[path] || - !doc.$__.populated[path].options || - !doc.$__.populated[path].options.options || - !doc.$__.populated[path].options.options.lean - ) { - ret = new pop.options[populateModelSymbol](value); - ret.$__.wasPopulated = true; +SchemaArray.prototype.applyGetters = function(value, scope) { + if (scope != null && scope.$__ != null && scope.$populated(this.path)) { + // means the object id was populated + return value; + } + + const ret = SchemaType.prototype.applyGetters.call(this, value, scope); + if (Array.isArray(ret)) { + const rawValue = ret.isMongooseArrayProxy ? ret.__array : ret; + const len = rawValue.length; + for (let i = 0; i < len; ++i) { + rawValue[i] = this.caster.applyGetters(rawValue[i], scope); + } + } + return ret; +}; + +SchemaArray.prototype._applySetters = function(value, scope, init, priorVal) { + if (this.casterConstructor.$isMongooseArray && + SchemaArray.options.castNonArrays && + !this[isNestedArraySymbol]) { + // Check nesting levels and wrap in array if necessary + let depth = 0; + let arr = this; + while (arr != null && + arr.$isMongooseArray && + !arr.$isMongooseDocumentArray) { + ++depth; + arr = arr.casterConstructor; + } + + // No need to wrap empty arrays + if (value != null && value.length > 0) { + const valueDepth = arrayDepth(value); + if (valueDepth.min === valueDepth.max && valueDepth.max < depth && valueDepth.containsNonArrayItem) { + for (let i = valueDepth.max; i < depth; ++i) { + value = [value]; } + } + } + } - return ret; - }; + return SchemaType.prototype._applySetters.call(this, value, scope, init, priorVal); +}; + +/** + * Casts values for set(). + * + * @param {Object} value + * @param {Document} doc document that triggers the casting + * @param {Boolean} init whether this is an initialization cast + * @api private + */ - /*! - * ignore - */ +SchemaArray.prototype.cast = function(value, doc, init, prev, options) { + // lazy load + MongooseArray || (MongooseArray = __nccwpck_require__(3000).Array); - function handleSingle(val) { - return this.castForQuery(val); - } + let i; + let l; - /*! - * ignore - */ + if (Array.isArray(value)) { + const len = value.length; + if (!len && doc) { + const indexes = doc.schema.indexedPaths(); - function handleArray(val) { - const _this = this; - if (!Array.isArray(val)) { - return [this.castForQuery(val)]; + const arrayPath = this.path; + for (i = 0, l = indexes.length; i < l; ++i) { + const pathIndex = indexes[i][0][arrayPath]; + if (pathIndex === '2dsphere' || pathIndex === '2d') { + return; } - return val.map(function (m) { - return _this.castForQuery(m); - }); } - /*! - * Just like handleArray, except also allows `[]` because surprisingly - * `$in: [1, []]` works fine - */ - - function handle$in(val) { - const _this = this; - if (!Array.isArray(val)) { - return [this.castForQuery(val)]; - } - return val.map(function (m) { - if (Array.isArray(m) && m.length === 0) { - return m; + // Special case: if this index is on the parent of what looks like + // GeoJSON, skip setting the default to empty array re: #1668, #3233 + const arrayGeojsonPath = this.path.endsWith('.coordinates') ? + this.path.substr(0, this.path.lastIndexOf('.')) : null; + if (arrayGeojsonPath != null) { + for (i = 0, l = indexes.length; i < l; ++i) { + const pathIndex = indexes[i][0][arrayGeojsonPath]; + if (pathIndex === '2dsphere') { + return; } - return _this.castForQuery(m); - }); + } } + } - /*! - * ignore - */ + options = options || emptyOpts; - SchemaType.prototype.$conditionalHandlers = { - $all: handleArray, - $eq: handleSingle, - $in: handle$in, - $ne: handleSingle, - $nin: handle$in, - $exists: $exists, - $type: $type, - }; + let rawValue = value.isMongooseArrayProxy ? value.__array : value; + value = MongooseArray(rawValue, options.path || this._arrayPath || this.path, doc, this); + rawValue = value.__array; - /*! - * Wraps `castForQuery` to handle context - */ + if (init && doc != null && doc.$__ != null && doc.$populated(this.path)) { + return value; + } - SchemaType.prototype.castForQueryWrapper = function (params) { - this.$$context = params.context; - if ("$conditional" in params) { - const ret = this.castForQuery(params.$conditional, params.val); - this.$$context = null; - return ret; - } - if (params.$skipQueryCastForUpdate || params.$applySetters) { - const ret = this._castForQuery(params.val); - this.$$context = null; - return ret; + const caster = this.caster; + const isMongooseArray = caster.$isMongooseArray; + if (caster && this.casterConstructor !== Mixed) { + try { + const len = rawValue.length; + for (i = 0; i < len; i++) { + const opts = {}; + // Perf: creating `arrayPath` is expensive for large arrays. + // We only need `arrayPath` if this is a nested array, so + // skip if possible. + if (isMongooseArray) { + if (options.arrayPath != null) { + opts.arrayPathIndex = i; + } else if (caster._arrayParentPath != null) { + opts.arrayPathIndex = i; + } + } + rawValue[i] = caster.applySetters(rawValue[i], doc, init, void 0, opts); } + } catch (e) { + // rethrow + throw new CastError('[' + e.kind + ']', util.inspect(value), this.path + '.' + i, e, this); + } + } - const ret = this.castForQuery(params.val); - this.$$context = null; - return ret; - }; + return value; + } - /** - * Cast the given value with the given optional query operator. - * - * @param {String} [$conditional] query operator, like `$eq` or `$in` - * @param {any} val - * @api private - */ - - SchemaType.prototype.castForQuery = function ($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) { - throw new Error("Can't use " + $conditional); - } - return handler.call(this, val); - } - val = $conditional; - return this._castForQuery(val); - }; + if (init || SchemaArray.options.castNonArrays) { + // gh-2442: if we're loading this from the db and its not an array, mark + // the whole array as modified. + if (!!doc && !!init) { + doc.markModified(this.path); + } + return this.cast([value], doc, init); + } - /*! - * Internal switch for runSetters - * - * @api private - */ + throw new CastError('Array', util.inspect(value), this.path, null, this); +}; - SchemaType.prototype._castForQuery = function (val) { - return this.applySetters(val, this.$$context); - }; +/*! + * ignore + */ - /** - * Override the function the required validator uses to check whether a value - * passes the `required` check. Override this on the individual SchemaType. - * - * ####Example: - * - * // Use this to allow empty strings to pass the `required` validator - * mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string'); - * - * @param {Function} fn - * @return {Function} - * @static - * @receiver SchemaType - * @function checkRequired - * @api public - */ - - SchemaType.checkRequired = function (fn) { - if (arguments.length > 0) { - this._checkRequired = fn; - } - - return this._checkRequired; - }; +SchemaArray.prototype._castForPopulate = function _castForPopulate(value, doc) { + // lazy load + MongooseArray || (MongooseArray = __nccwpck_require__(3000).Array); - /** - * Default check for if this path satisfies the `required` validator. - * - * @param {any} val - * @api private - */ + if (Array.isArray(value)) { + let i; + const rawValue = value.__array ? value.__array : value; + const len = rawValue.length; - SchemaType.prototype.checkRequired = function (val) { - return val != null; - }; + const caster = this.caster; + if (caster && this.casterConstructor !== Mixed) { + try { + for (i = 0; i < len; i++) { + const opts = {}; + // Perf: creating `arrayPath` is expensive for large arrays. + // We only need `arrayPath` if this is a nested array, so + // skip if possible. + if (caster.$isMongooseArray && caster._arrayParentPath != null) { + opts.arrayPathIndex = i; + } - /*! - * ignore - */ + rawValue[i] = caster.cast(rawValue[i], doc, false, void 0, opts); + } + } catch (e) { + // rethrow + throw new CastError('[' + e.kind + ']', util.inspect(value), this.path + '.' + i, e, this); + } + } - SchemaType.prototype.clone = function () { - const options = Object.assign({}, this.options); - const schematype = new this.constructor( - this.path, - options, - this.instance - ); - schematype.validators = this.validators.slice(); - if (this.requiredValidator !== undefined) - schematype.requiredValidator = this.requiredValidator; - if (this.defaultValue !== undefined) - schematype.defaultValue = this.defaultValue; - if ( - this.$immutable !== undefined && - this.options.immutable === undefined - ) { - schematype.$immutable = this.$immutable; - - handleImmutable(schematype); - } - if (this._index !== undefined) schematype._index = this._index; - if (this.selected !== undefined) schematype.selected = this.selected; - if (this.isRequired !== undefined) - schematype.isRequired = this.isRequired; - if (this.originalRequiredValue !== undefined) - schematype.originalRequiredValue = this.originalRequiredValue; - schematype.getters = this.getters.slice(); - schematype.setters = this.setters.slice(); - return schematype; - }; + return value; + } - /*! - * Module exports. - */ + throw new CastError('Array', util.inspect(value), this.path, null, this); +}; - module.exports = exports = SchemaType; +SchemaArray.prototype.$toObject = SchemaArray.prototype.toObject; - exports.CastError = CastError; +/*! + * Ignore + */ - exports.ValidatorError = ValidatorError; +SchemaArray.prototype.discriminator = function(name, schema) { + let arr = this; + while (arr.$isMongooseArray && !arr.$isMongooseDocumentArray) { + arr = arr.casterConstructor; + if (arr == null || typeof arr === 'function') { + throw new MongooseError('You can only add an embedded discriminator on ' + + 'a document array, ' + this.path + ' is a plain array'); + } + } + return arr.discriminator(name, schema); +}; - /***/ - }, +/*! + * ignore + */ - /***/ 3532: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const utils = __nccwpck_require__(9232); - - /*! - * StateMachine represents a minimal `interface` for the - * constructors it builds via StateMachine.ctor(...). - * - * @api private - */ - - const StateMachine = - (module.exports = - exports = - function StateMachine() {}); - - /*! - * StateMachine.ctor('state1', 'state2', ...) - * A factory method for subclassing StateMachine. - * The arguments are a list of states. For each state, - * the constructor's prototype gets state transition - * methods named after each state. These transition methods - * place their path argument into the given state. - * - * @param {String} state - * @param {String} [state] - * @return {Function} subclass constructor - * @private - */ - - StateMachine.ctor = function () { - const states = utils.args(arguments); - - const ctor = function () { - StateMachine.apply(this, arguments); - this.paths = {}; - this.states = {}; - this.stateNames = states; - - let i = states.length, - state; - - while (i--) { - state = states[i]; - this.states[state] = {}; - } - }; +SchemaArray.prototype.clone = function() { + const options = Object.assign({}, this.options); + const schematype = new this.constructor(this.path, this.caster, options, this.schemaOptions); + schematype.validators = this.validators.slice(); + if (this.requiredValidator !== undefined) { + schematype.requiredValidator = this.requiredValidator; + } + return schematype; +}; - ctor.prototype = new StateMachine(); +/** + * Casts values for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ - states.forEach(function (state) { - // Changes the `path`'s state to `state`. - ctor.prototype[state] = function (path) { - this._changeState(path, state); - }; - }); +SchemaArray.prototype.castForQuery = function($conditional, value) { + let handler; + let val; - return ctor; - }; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; - /*! - * This function is wrapped by the state change functions: - * - * - `require(path)` - * - `modify(path)` - * - `init(path)` - * - * @api private - */ - - StateMachine.prototype._changeState = function _changeState( - path, - nextState - ) { - const prevBucket = this.states[this.paths[path]]; - if (prevBucket) delete prevBucket[path]; - - this.paths[path] = nextState; - this.states[nextState][path] = true; - }; + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with Array.'); + } - /*! - * ignore - */ + val = handler.call(this, value); + } else { + val = $conditional; + let Constructor = this.casterConstructor; + + if (val && + Constructor.discriminators && + Constructor.schema && + Constructor.schema.options && + Constructor.schema.options.discriminatorKey) { + if (typeof val[Constructor.schema.options.discriminatorKey] === 'string' && + Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) { + Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]; + } else { + const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, val[Constructor.schema.options.discriminatorKey]); + if (constructorByValue) { + Constructor = constructorByValue; + } + } + } - StateMachine.prototype.clear = function clear(state) { - const keys = Object.keys(this.states[state]); - let i = keys.length; - let path; + const proto = this.casterConstructor.prototype; + let method = proto && (proto.castForQuery || proto.cast); + if (!method && Constructor.castForQuery) { + method = Constructor.castForQuery; + } + const caster = this.caster; - while (i--) { - path = keys[i]; - delete this.states[state][path]; - delete this.paths[path]; + if (Array.isArray(val)) { + this.setters.reverse().forEach(setter => { + val = setter.call(this, val, this); + }); + val = val.map(function(v) { + if (utils.isObject(v) && v.$elemMatch) { + return v; } - }; + if (method) { + v = method.call(caster, v); + return v; + } + if (v != null) { + v = new Constructor(v); + return v; + } + return v; + }); + } else if (method) { + val = method.call(caster, val); + } else if (val != null) { + val = new Constructor(val); + } + } - /*! - * Checks to see if at least one path is in the states passed in via `arguments` - * e.g., this.some('required', 'inited') - * - * @param {String} state that we want to check for. - * @private - */ + return val; +}; - StateMachine.prototype.some = function some() { - const _this = this; - const what = arguments.length ? arguments : this.stateNames; - return Array.prototype.some.call(what, function (state) { - return Object.keys(_this.states[state]).length; - }); - }; +function cast$all(val) { + if (!Array.isArray(val)) { + val = [val]; + } - /*! - * This function builds the functions that get assigned to `forEach` and `map`, - * since both of those methods share a lot of the same logic. - * - * @param {String} iterMethod is either 'forEach' or 'map' - * @return {Function} - * @api private - */ + val = val.map(function(v) { + if (utils.isObject(v)) { + const o = {}; + o[this.path] = v; + return cast(this.casterConstructor.schema, o)[this.path]; + } + return v; + }, this); + + return this.castForQuery(val); +} + +function cast$elemMatch(val) { + const keys = Object.keys(val); + const numKeys = keys.length; + for (let i = 0; i < numKeys; ++i) { + const key = keys[i]; + const value = val[key]; + if (isOperator(key) && value != null) { + val[key] = this.castForQuery(key, value); + } + } - StateMachine.prototype._iter = function _iter(iterMethod) { - return function () { - const numArgs = arguments.length; - let states = utils.args(arguments, 0, numArgs - 1); - const callback = arguments[numArgs - 1]; + // Is this an embedded discriminator and is the discriminator key set? + // If so, use the discriminator schema. See gh-7449 + const discriminatorKey = get(this, + 'casterConstructor.schema.options.discriminatorKey'); + const discriminators = get(this, 'casterConstructor.schema.discriminators', {}); + if (discriminatorKey != null && + val[discriminatorKey] != null && + discriminators[val[discriminatorKey]] != null) { + return cast(discriminators[val[discriminatorKey]], val); + } - if (!states.length) states = this.stateNames; + return cast(this.casterConstructor.schema, val); +} - const _this = this; +const handle = SchemaArray.prototype.$conditionalHandlers = {}; - const paths = states.reduce(function (paths, state) { - return paths.concat(Object.keys(_this.states[state])); - }, []); +handle.$all = cast$all; +handle.$options = String; +handle.$elemMatch = cast$elemMatch; +handle.$geoIntersects = geospatial.cast$geoIntersects; +handle.$or = createLogicalQueryOperatorHandler('$or'); +handle.$and = createLogicalQueryOperatorHandler('$and'); +handle.$nor = createLogicalQueryOperatorHandler('$nor'); - return paths[iterMethod](function (path, i, paths) { - return callback(path, i, paths); - }); - }; - }; +function createLogicalQueryOperatorHandler(op) { + return function logicalQueryOperatorHandler(val) { + if (!Array.isArray(val)) { + throw new TypeError('conditional ' + op + ' requires an array'); + } - /*! - * Iterates over the paths that belong to one of the parameter states. - * - * The function profile can look like: - * this.forEach(state1, fn); // iterates over all paths in state1 - * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 - * this.forEach(fn); // iterates over all paths in all states - * - * @param {String} [state] - * @param {String} [state] - * @param {Function} callback - * @private - */ - - StateMachine.prototype.forEach = function forEach() { - this.forEach = this._iter("forEach"); - return this.forEach.apply(this, arguments); - }; + const ret = []; + for (const obj of val) { + ret.push(cast(this.casterConstructor.schema, obj)); + } - /*! - * Maps over the paths that belong to one of the parameter states. - * - * The function profile can look like: - * this.forEach(state1, fn); // iterates over all paths in state1 - * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 - * this.forEach(fn); // iterates over all paths in all states - * - * @param {String} [state] - * @param {String} [state] - * @param {Function} callback - * @return {Array} - * @private - */ - - StateMachine.prototype.map = function map() { - this.map = this._iter("map"); - return this.map.apply(this, arguments); - }; + return ret; + }; +} - /***/ - }, +handle.$near = +handle.$nearSphere = geospatial.cast$near; - /***/ 6628: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; - /*! - * Module dependencies. - */ - - const CoreMongooseArray = __nccwpck_require__(7146); - - const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; - const arrayParentSymbol = __nccwpck_require__(3240).arrayParentSymbol; - const arrayPathSymbol = __nccwpck_require__(3240).arrayPathSymbol; - const arraySchemaSymbol = __nccwpck_require__(3240).arraySchemaSymbol; - - const _basePush = Array.prototype.push; - - /** - * Mongoose Array constructor. - * - * ####NOTE: - * - * _Values always have to be passed to the constructor to initialize, otherwise `MongooseArray#push` will mark the array as modified._ - * - * @param {Array} values - * @param {String} path - * @param {Document} doc parent document - * @api private - * @inherits Array - * @see http://bit.ly/f6CnZU - */ - - function MongooseArray(values, path, doc, schematype) { - let arr; - - if (Array.isArray(values)) { - const len = values.length; - - // Perf optimizations for small arrays: much faster to use `...` than `for` + `push`, - // but large arrays may cause stack overflows. And for arrays of length 0/1, just - // modifying the array is faster. Seems small, but adds up when you have a document - // with thousands of nested arrays. - if (len === 0) { - arr = new CoreMongooseArray(); - } else if (len === 1) { - arr = new CoreMongooseArray(1); - arr[0] = values[0]; - } else if (len < 10000) { - arr = new CoreMongooseArray(); - _basePush.apply(arr, values); - } else { - arr = new CoreMongooseArray(); - for (let i = 0; i < len; ++i) { - _basePush.call(arr, values[i]); - } - } +handle.$within = +handle.$geoWithin = geospatial.cast$within; - if (values[arrayAtomicsSymbol] != null) { - arr[arrayAtomicsSymbol] = values[arrayAtomicsSymbol]; - } - } else { - arr = new CoreMongooseArray(); - } +handle.$size = +handle.$minDistance = +handle.$maxDistance = castToNumber; - arr[arrayPathSymbol] = path; +handle.$exists = $exists; +handle.$type = $type; - // Because doc comes from the context of another function, doc === global - // can happen if there was a null somewhere up the chain (see #3020) - // RB Jun 17, 2015 updated to check for presence of expected paths instead - // to make more proof against unusual node environments - if (doc != null && doc.$__ != null) { - arr[arrayParentSymbol] = doc; - arr[arraySchemaSymbol] = schematype || doc.schema.path(path); - } +handle.$eq = +handle.$gt = +handle.$gte = +handle.$lt = +handle.$lte = +handle.$ne = +handle.$regex = SchemaArray.prototype.castForQuery; - return arr; - } +// `$in` is special because you can also include an empty array in the query +// like `$in: [1, []]`, see gh-5913 +handle.$nin = SchemaType.prototype.$conditionalHandlers.$nin; +handle.$in = SchemaType.prototype.$conditionalHandlers.$in; + +/*! + * Module exports. + */ - /*! - * Module exports. - */ +module.exports = SchemaArray; - module.exports = exports = MongooseArray; - /***/ - }, +/***/ }), - /***/ 5505: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module dependencies. - */ - - const Binary = __nccwpck_require__(2324).get().Binary; - const utils = __nccwpck_require__(9232); - const Buffer = __nccwpck_require__(1867).Buffer; - - /** - * Mongoose Buffer constructor. - * - * Values always have to be passed to the constructor to initialize. - * - * @param {Buffer} value - * @param {String} encode - * @param {Number} offset - * @api private - * @inherits Buffer - * @see http://bit.ly/f6CnZU - */ - - function MongooseBuffer(value, encode, offset) { - const length = arguments.length; - let val; +/***/ 2900: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ( - length === 0 || - arguments[0] === null || - arguments[0] === undefined - ) { - val = 0; - } else { - val = value; - } +"use strict"; - let encoding; - let path; - let doc; - if (Array.isArray(encode)) { - // internal casting - path = encode[0]; - doc = encode[1]; - } else { - encoding = encode; - } +/*! + * Module dependencies. + */ - let buf; - if (typeof val === "number" || val instanceof Number) { - buf = Buffer.alloc(val); - } else { - // string, array or object { type: 'Buffer', data: [...] } - buf = Buffer.from(val, encoding, offset); - } - utils.decorate(buf, MongooseBuffer.mixin); - buf.isMongooseBuffer = true; +const CastError = __nccwpck_require__(2798); +const SchemaType = __nccwpck_require__(5660); +const castBoolean = __nccwpck_require__(66); +const utils = __nccwpck_require__(9232); - // make sure these internal props don't show up in Object.keys() - buf[MongooseBuffer.pathSymbol] = path; - buf[parentSymbol] = doc; +/** + * Boolean SchemaType constructor. + * + * @param {String} path + * @param {Object} options + * @inherits SchemaType + * @api public + */ - buf._subtype = 0; - return buf; - } +function SchemaBoolean(path, options) { + SchemaType.call(this, path, options, 'Boolean'); +} - const pathSymbol = Symbol.for("mongoose#Buffer#_path"); - const parentSymbol = Symbol.for("mongoose#Buffer#_parent"); - MongooseBuffer.pathSymbol = pathSymbol; +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaBoolean.schemaName = 'Boolean'; - /*! - * Inherit from Buffer. - */ +SchemaBoolean.defaultOptions = {}; - MongooseBuffer.mixin = { - /** - * Default subtype for the Binary representing this Buffer - * - * @api private - * @property _subtype - * @receiver MongooseBuffer - */ +/*! + * Inherits from SchemaType. + */ +SchemaBoolean.prototype = Object.create(SchemaType.prototype); +SchemaBoolean.prototype.constructor = SchemaBoolean; - _subtype: undefined, +/*! + * ignore + */ - /** - * Marks this buffer as modified. - * - * @api private - * @method _markModified - * @receiver MongooseBuffer - */ +SchemaBoolean._cast = castBoolean; - _markModified: function () { - const parent = this[parentSymbol]; +/** + * Sets a default option for all Boolean instances. + * + * ####Example: + * + * // Make all booleans have `default` of false. + * mongoose.Schema.Boolean.set('default', false); + * + * const Order = mongoose.model('Order', new Schema({ isPaid: Boolean })); + * new Order({ }).isPaid; // false + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ - if (parent) { - parent.markModified(this[MongooseBuffer.pathSymbol]); - } - return this; - }, +SchemaBoolean.set = SchemaType.set; - /** - * Writes the buffer. - * - * @api public - * @method write - * @receiver MongooseBuffer - */ +/** + * Get/set the function used to cast arbitrary values to booleans. + * + * ####Example: + * + * // Make Mongoose cast empty string '' to false. + * const original = mongoose.Schema.Boolean.cast(); + * mongoose.Schema.Boolean.cast(v => { + * if (v === '') { + * return false; + * } + * return original(v); + * }); + * + * // Or disable casting entirely + * mongoose.Schema.Boolean.cast(false); + * + * @param {Function} caster + * @return {Function} + * @function get + * @static + * @api public + */ - write: function () { - const written = Buffer.prototype.write.apply(this, arguments); +SchemaBoolean.cast = function cast(caster) { + if (arguments.length === 0) { + return this._cast; + } + if (caster === false) { + caster = this._defaultCaster; + } + this._cast = caster; - if (written > 0) { - this._markModified(); - } + return this._cast; +}; - return written; - }, +/*! + * ignore + */ - /** - * Copies the buffer. - * - * ####Note: - * - * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this. - * - * @return {Number} The number of bytes copied. - * @param {Buffer} target - * @method copy - * @receiver MongooseBuffer - */ +SchemaBoolean._defaultCaster = v => { + if (v != null && typeof v !== 'boolean') { + throw new Error(); + } + return v; +}; - copy: function (target) { - const ret = Buffer.prototype.copy.apply(this, arguments); +/*! + * ignore + */ - if (target && target.isMongooseBuffer) { - target._markModified(); - } +SchemaBoolean._checkRequired = v => v === true || v === false; - return ret; - }, - }; +/** + * Override the function the required validator uses to check whether a boolean + * passes the `required` check. + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @static + * @api public + */ - /*! - * Compile other Buffer methods marking this buffer as modified. - */ - - // node < 0.5 - ( - "writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 " + - "writeFloat writeDouble fill " + - "utf8Write binaryWrite asciiWrite set " + - // node >= 0.5 - "writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE " + - "writeInt16LE writeInt16BE writeInt32LE writeInt32BE " + - "writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE" - ) - .split(" ") - .forEach(function (method) { - if (!Buffer.prototype[method]) { - return; - } - MongooseBuffer.mixin[method] = function () { - const ret = Buffer.prototype[method].apply(this, arguments); - this._markModified(); - return ret; - }; - }); +SchemaBoolean.checkRequired = SchemaType.checkRequired; - /** - * Converts this buffer to its Binary type representation. - * - * ####SubTypes: - * - * const bson = require('bson') - * bson.BSON_BINARY_SUBTYPE_DEFAULT - * bson.BSON_BINARY_SUBTYPE_FUNCTION - * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY - * bson.BSON_BINARY_SUBTYPE_UUID - * bson.BSON_BINARY_SUBTYPE_MD5 - * bson.BSON_BINARY_SUBTYPE_USER_DEFINED - * - * doc.buffer.toObject(bson.BSON_BINARY_SUBTYPE_USER_DEFINED); - * - * @see http://bsonspec.org/#/specification - * @param {Hex} [subtype] - * @return {Binary} - * @api public - * @method toObject - * @receiver MongooseBuffer - */ - - MongooseBuffer.mixin.toObject = function (options) { - const subtype = - typeof options === "number" ? options : this._subtype || 0; - return new Binary(Buffer.from(this), subtype); - }; +/** + * Check if the given value satisfies a required validator. For a boolean + * to satisfy a required validator, it must be strictly equal to true or to + * false. + * + * @param {Any} value + * @return {Boolean} + * @api public + */ - /** - * Converts this buffer for storage in MongoDB, including subtype - * - * @return {Binary} - * @api public - * @method toBSON - * @receiver MongooseBuffer - */ - - MongooseBuffer.mixin.toBSON = function () { - return new Binary(this, this._subtype || 0); - }; +SchemaBoolean.prototype.checkRequired = function(value) { + return this.constructor._checkRequired(value); +}; - /** - * Determines if this buffer is equals to `other` buffer - * - * @param {Buffer} other - * @return {Boolean} - * @method equals - * @receiver MongooseBuffer - */ - - MongooseBuffer.mixin.equals = function (other) { - if (!Buffer.isBuffer(other)) { - return false; - } +/** + * Configure which values get casted to `true`. + * + * ####Example: + * + * const M = mongoose.model('Test', new Schema({ b: Boolean })); + * new M({ b: 'affirmative' }).b; // undefined + * mongoose.Schema.Boolean.convertToTrue.add('affirmative'); + * new M({ b: 'affirmative' }).b; // true + * + * @property convertToTrue + * @type Set + * @api public + */ - if (this.length !== other.length) { - return false; - } +Object.defineProperty(SchemaBoolean, 'convertToTrue', { + get: () => castBoolean.convertToTrue, + set: v => { castBoolean.convertToTrue = v; } +}); - for (let i = 0; i < this.length; ++i) { - if (this[i] !== other[i]) { - return false; - } - } +/** + * Configure which values get casted to `false`. + * + * ####Example: + * + * const M = mongoose.model('Test', new Schema({ b: Boolean })); + * new M({ b: 'nay' }).b; // undefined + * mongoose.Schema.Types.Boolean.convertToFalse.add('nay'); + * new M({ b: 'nay' }).b; // false + * + * @property convertToFalse + * @type Set + * @api public + */ - return true; - }; +Object.defineProperty(SchemaBoolean, 'convertToFalse', { + get: () => castBoolean.convertToFalse, + set: v => { castBoolean.convertToFalse = v; } +}); - /** - * Sets the subtype option and marks the buffer modified. - * - * ####SubTypes: - * - * const bson = require('bson') - * bson.BSON_BINARY_SUBTYPE_DEFAULT - * bson.BSON_BINARY_SUBTYPE_FUNCTION - * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY - * bson.BSON_BINARY_SUBTYPE_UUID - * bson.BSON_BINARY_SUBTYPE_MD5 - * bson.BSON_BINARY_SUBTYPE_USER_DEFINED - * - * doc.buffer.subtype(bson.BSON_BINARY_SUBTYPE_UUID); - * - * @see http://bsonspec.org/#/specification - * @param {Hex} subtype - * @api public - * @method subtype - * @receiver MongooseBuffer - */ - - MongooseBuffer.mixin.subtype = function (subtype) { - if (typeof subtype !== "number") { - throw new TypeError("Invalid subtype. Expected a number"); - } - - if (this._subtype !== subtype) { - this._markModified(); - } - - this._subtype = subtype; - }; +/** + * Casts to boolean + * + * @param {Object} value + * @param {Object} model - this value is optional + * @api private + */ - /*! - * Module exports. - */ +SchemaBoolean.prototype.cast = function(value) { + let castBoolean; + if (typeof this._castFunction === 'function') { + castBoolean = this._castFunction; + } else if (typeof this.constructor.cast === 'function') { + castBoolean = this.constructor.cast(); + } else { + castBoolean = SchemaBoolean.cast(); + } - MongooseBuffer.Binary = Binary; + try { + return castBoolean(value); + } catch (error) { + throw new CastError('Boolean', value, this.path, error, this); + } +}; - module.exports = MongooseBuffer; +SchemaBoolean.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, {}); - /***/ - }, +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} val + * @api private + */ - /***/ 7146: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +SchemaBoolean.prototype.castForQuery = function($conditional, val) { + let handler; + if (arguments.length === 2) { + handler = SchemaBoolean.$conditionalHandlers[$conditional]; - const Document = __nccwpck_require__(6717); - const EmbeddedDocument = __nccwpck_require__(4433); - const MongooseError = __nccwpck_require__(5953); - const ObjectId = __nccwpck_require__(2706); - const cleanModifiedSubpaths = __nccwpck_require__(7958); - const get = __nccwpck_require__(8730); - const internalToObjectOptions = - __nccwpck_require__(5684) /* .internalToObjectOptions */.h; - const utils = __nccwpck_require__(9232); - const util = __nccwpck_require__(1669); + if (handler) { + return handler.call(this, val); + } - const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; - const arrayParentSymbol = __nccwpck_require__(3240).arrayParentSymbol; - const arrayPathSymbol = __nccwpck_require__(3240).arrayPathSymbol; - const arraySchemaSymbol = __nccwpck_require__(3240).arraySchemaSymbol; - const populateModelSymbol = __nccwpck_require__(3240).populateModelSymbol; - const slicedSymbol = Symbol("mongoose#Array#sliced"); + return this._castForQuery(val); + } - const _basePush = Array.prototype.push; + return this._castForQuery($conditional); +}; - const validatorsSymbol = Symbol("mongoose#MongooseCoreArray#validators"); +/** + * + * @api private + */ - /*! - * ignore - */ +SchemaBoolean.prototype._castNullish = function _castNullish(v) { + if (typeof v === 'undefined') { + return v; + } + const castBoolean = typeof this.constructor.cast === 'function' ? + this.constructor.cast() : + SchemaBoolean.cast(); + if (castBoolean == null) { + return v; + } + if (castBoolean.convertToFalse instanceof Set && castBoolean.convertToFalse.has(v)) { + return false; + } + if (castBoolean.convertToTrue instanceof Set && castBoolean.convertToTrue.has(v)) { + return true; + } + return v; +}; - class CoreMongooseArray extends Array { - get isMongooseArray() { - return true; - } +/*! + * Module exports. + */ - get validators() { - return this[validatorsSymbol]; - } +module.exports = SchemaBoolean; - set validators(v) { - this[validatorsSymbol] = v; - } - /** - * Depopulates stored atomic operation values as necessary for direct insertion to MongoDB. - * - * If no atomics exist, we return all array values after conversion. - * - * @return {Array} - * @method $__getAtomics - * @memberOf MongooseArray - * @instance - * @api private - */ +/***/ }), - $__getAtomics() { - const ret = []; - const keys = Object.keys(this[arrayAtomicsSymbol] || {}); - let i = keys.length; +/***/ 4798: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const opts = Object.assign({}, internalToObjectOptions, { - _isNested: true, - }); +"use strict"; +/*! + * Module dependencies. + */ - if (i === 0) { - ret[0] = ["$set", this.toObject(opts)]; - return ret; - } - while (i--) { - const op = keys[i]; - let val = this[arrayAtomicsSymbol][op]; - // the atomic values which are arrays are not MongooseArrays. we - // need to convert their elements as if they were MongooseArrays - // to handle populated arrays versus DocumentArrays properly. - if (utils.isMongooseObject(val)) { - val = val.toObject(opts); - } else if (Array.isArray(val)) { - val = this.toObject.call(val, opts); - } else if (val != null && Array.isArray(val.$each)) { - val.$each = this.toObject.call(val.$each, opts); - } else if (val != null && typeof val.valueOf === "function") { - val = val.valueOf(); - } +const MongooseBuffer = __nccwpck_require__(5505); +const SchemaBufferOptions = __nccwpck_require__(6680); +const SchemaType = __nccwpck_require__(5660); +const handleBitwiseOperator = __nccwpck_require__(9547); +const utils = __nccwpck_require__(9232); - if (op === "$addToSet") { - val = { $each: val }; - } +const Binary = MongooseBuffer.Binary; +const CastError = SchemaType.CastError; - ret.push([op, val]); - } +/** + * Buffer SchemaType constructor + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ - return ret; - } +function SchemaBuffer(key, options) { + SchemaType.call(this, key, options, 'Buffer'); +} - /*! - * ignore - */ +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaBuffer.schemaName = 'Buffer'; - $atomics() { - return this[arrayAtomicsSymbol] || {}; - } +SchemaBuffer.defaultOptions = {}; - /*! - * ignore - */ +/*! + * Inherits from SchemaType. + */ +SchemaBuffer.prototype = Object.create(SchemaType.prototype); +SchemaBuffer.prototype.constructor = SchemaBuffer; +SchemaBuffer.prototype.OptionsConstructor = SchemaBufferOptions; - $parent() { - return this[arrayParentSymbol]; - } +/*! + * ignore + */ - /*! - * ignore - */ +SchemaBuffer._checkRequired = v => !!(v && v.length); - $path() { - return this[arrayPathSymbol]; - } +/** + * Sets a default option for all Buffer instances. + * + * ####Example: + * + * // Make all buffers have `required` of true by default. + * mongoose.Schema.Buffer.set('required', true); + * + * const User = mongoose.model('User', new Schema({ test: Buffer })); + * new User({ }).validateSync().errors.test.message; // Path `test` is required. + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ - /** - * Atomically shifts the array at most one time per document `save()`. - * - * ####NOTE: - * - * _Calling this multiple times on an array before saving sends the same command as calling it once._ - * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ - * - * doc.array = [1,2,3]; - * - * const shifted = doc.array.$shift(); - * console.log(shifted); // 1 - * console.log(doc.array); // [2,3] - * - * // no affect - * shifted = doc.array.$shift(); - * console.log(doc.array); // [2,3] - * - * doc.save(function (err) { - * if (err) return handleError(err); - * - * // we saved, now $shift works again - * shifted = doc.array.$shift(); - * console.log(shifted ); // 2 - * console.log(doc.array); // [3] - * }) - * - * @api public - * @memberOf MongooseArray - * @instance - * @method $shift - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop - */ +SchemaBuffer.set = SchemaType.set; - $shift() { - this._registerAtomic("$pop", -1); - this._markModified(); +/** + * Override the function the required validator uses to check whether a string + * passes the `required` check. + * + * ####Example: + * + * // Allow empty strings to pass `required` check + * mongoose.Schema.Types.String.checkRequired(v => v != null); + * + * const M = mongoose.model({ buf: { type: Buffer, required: true } }); + * new M({ buf: Buffer.from('') }).validateSync(); // validation passes! + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @static + * @api public + */ - // only allow shifting once - if (this._shifted) { - return; - } - this._shifted = true; +SchemaBuffer.checkRequired = SchemaType.checkRequired; - return [].shift.call(this); - } +/** + * Check if the given value satisfies a required validator. To satisfy a + * required validator, a buffer must not be null or undefined and have + * non-zero length. + * + * @param {Any} value + * @param {Document} doc + * @return {Boolean} + * @api public + */ - /** - * Pops the array atomically at most one time per document `save()`. - * - * #### NOTE: - * - * _Calling this mulitple times on an array before saving sends the same command as calling it once._ - * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ - * - * doc.array = [1,2,3]; - * - * const popped = doc.array.$pop(); - * console.log(popped); // 3 - * console.log(doc.array); // [1,2] - * - * // no affect - * popped = doc.array.$pop(); - * console.log(doc.array); // [1,2] - * - * doc.save(function (err) { - * if (err) return handleError(err); - * - * // we saved, now $pop works again - * popped = doc.array.$pop(); - * console.log(popped); // 2 - * console.log(doc.array); // [1] - * }) - * - * @api public - * @method $pop - * @memberOf MongooseArray - * @instance - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop - * @method $pop - * @memberOf MongooseArray - */ +SchemaBuffer.prototype.checkRequired = function(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + return this.constructor._checkRequired(value); +}; - $pop() { - this._registerAtomic("$pop", 1); - this._markModified(); +/** + * Casts contents + * + * @param {Object} value + * @param {Document} doc document that triggers the casting + * @param {Boolean} init + * @api private + */ - // only allow popping once - if (this._popped) { - return; - } - this._popped = true; +SchemaBuffer.prototype.cast = function(value, doc, init) { + let ret; + if (SchemaType._isRef(this, value, doc, init)) { + if (value && value.isMongooseBuffer) { + return value; + } - return [].pop.call(this); + if (Buffer.isBuffer(value)) { + if (!value || !value.isMongooseBuffer) { + value = new MongooseBuffer(value, [this.path, doc]); + if (this.options.subtype != null) { + value._subtype = this.options.subtype; } + } + return value; + } - /*! - * ignore - */ + if (value instanceof Binary) { + ret = new MongooseBuffer(value.value(true), [this.path, doc]); + if (typeof value.sub_type !== 'number') { + throw new CastError('Buffer', value, this.path, null, this); + } + ret._subtype = value.sub_type; + return ret; + } - $schema() { - return this[arraySchemaSymbol]; - } + if (value == null || utils.isNonBuiltinObject(value)) { + return this._castRef(value, doc, init); + } + } - /** - * Casts a member based on this arrays schema. - * - * @param {any} value - * @return value the casted value - * @method _cast - * @api private - * @memberOf MongooseArray - */ + // documents + if (value && value._id) { + value = value._id; + } - _cast(value) { - let populated = false; - let Model; + if (value && value.isMongooseBuffer) { + return value; + } - if (this[arrayParentSymbol]) { - populated = this[arrayParentSymbol].populated( - this[arrayPathSymbol], - true - ); - } + if (Buffer.isBuffer(value)) { + if (!value || !value.isMongooseBuffer) { + value = new MongooseBuffer(value, [this.path, doc]); + if (this.options.subtype != null) { + value._subtype = this.options.subtype; + } + } + return value; + } - if (populated && value !== null && value !== undefined) { - // cast to the populated Models schema - Model = populated.options[populateModelSymbol]; - - // only objects are permitted so we can safely assume that - // non-objects are to be interpreted as _id - if ( - Buffer.isBuffer(value) || - value instanceof ObjectId || - !utils.isObject(value) - ) { - value = { _id: value }; - } - - // gh-2399 - // we should cast model only when it's not a discriminator - const isDisc = - value.$__schema && - value.$__schema.discriminatorMapping && - value.$__schema.discriminatorMapping.key !== undefined; - if (!isDisc) { - value = new Model(value); - } - return this[arraySchemaSymbol].caster.applySetters( - value, - this[arrayParentSymbol], - true - ); - } + if (value instanceof Binary) { + ret = new MongooseBuffer(value.value(true), [this.path, doc]); + if (typeof value.sub_type !== 'number') { + throw new CastError('Buffer', value, this.path, null, this); + } + ret._subtype = value.sub_type; + return ret; + } - return this[arraySchemaSymbol].caster.applySetters( - value, - this[arrayParentSymbol], - false - ); - } + if (value === null) { + return value; + } - /** - * Internal helper for .map() - * - * @api private - * @return {Number} - * @method _mapCast - * @memberOf MongooseArray - */ - _mapCast(val, index) { - return this._cast(val, this.length + index); - } + const type = typeof value; + if ( + type === 'string' || type === 'number' || Array.isArray(value) || + (type === 'object' && value.type === 'Buffer' && Array.isArray(value.data)) // gh-6863 + ) { + if (type === 'number') { + value = [value]; + } + ret = new MongooseBuffer(value, [this.path, doc]); + if (this.options.subtype != null) { + ret._subtype = this.options.subtype; + } + return ret; + } - /** - * Marks this array as modified. - * - * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments) - * - * @param {EmbeddedDocument} embeddedDoc the embedded doc that invoked this method on the Array - * @param {String} embeddedPath the path which changed in the embeddedDoc - * @method _markModified - * @api private - * @memberOf MongooseArray - */ + throw new CastError('Buffer', value, this.path, null, this); +}; - _markModified(elem) { - const parent = this[arrayParentSymbol]; - let dirtyPath; +/** + * Sets the default [subtype](https://studio3t.com/whats-new/best-practices-uuid-mongodb/) + * for this buffer. You can find a [list of allowed subtypes here](http://api.mongodb.com/python/current/api/bson/binary.html). + * + * ####Example: + * + * const s = new Schema({ uuid: { type: Buffer, subtype: 4 }); + * const M = db.model('M', s); + * const m = new M({ uuid: 'test string' }); + * m.uuid._subtype; // 4 + * + * @param {Number} subtype the default subtype + * @return {SchemaType} this + * @api public + */ - if (parent) { - dirtyPath = this[arrayPathSymbol]; +SchemaBuffer.prototype.subtype = function(subtype) { + this.options.subtype = subtype; + return this; +}; - if (arguments.length) { - dirtyPath = dirtyPath + "." + elem; - } +/*! + * ignore + */ +function handleSingle(val) { + return this.castForQuery(val); +} + +SchemaBuffer.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $bitsAllClear: handleBitwiseOperator, + $bitsAnyClear: handleBitwiseOperator, + $bitsAllSet: handleBitwiseOperator, + $bitsAnySet: handleBitwiseOperator, + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle + }); - if (dirtyPath != null && dirtyPath.endsWith(".$")) { - return this; - } +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ - parent.markModified( - dirtyPath, - arguments.length > 0 ? elem : parent - ); - } +SchemaBuffer.prototype.castForQuery = function($conditional, val) { + let handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with Buffer.'); + } + return handler.call(this, val); + } + val = $conditional; + const casted = this._castForQuery(val); + return casted ? casted.toObject({ transform: false, virtuals: false }) : casted; +}; - return this; - } +/*! + * Module exports. + */ - /** - * Register an atomic operation with the parent. - * - * @param {Array} op operation - * @param {any} val - * @method _registerAtomic - * @api private - * @memberOf MongooseArray - */ +module.exports = SchemaBuffer; - _registerAtomic(op, val) { - if (this[slicedSymbol]) { - return; - } - if (op === "$set") { - // $set takes precedence over all other ops. - // mark entire array modified. - this[arrayAtomicsSymbol] = { $set: val }; - cleanModifiedSubpaths( - this[arrayParentSymbol], - this[arrayPathSymbol] - ); - this._markModified(); - return this; - } - this[arrayAtomicsSymbol] || (this[arrayAtomicsSymbol] = {}); +/***/ }), - const atomics = this[arrayAtomicsSymbol]; +/***/ 9140: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // reset pop/shift after save - if (op === "$pop" && !("$pop" in atomics)) { - const _this = this; - this[arrayParentSymbol].once("save", function () { - _this._popped = _this._shifted = null; - }); - } +"use strict"; +/*! + * Module requirements. + */ - // check for impossible $atomic combos (Mongo denies more than one - // $atomic op on a single path - if ( - this[arrayAtomicsSymbol].$set || - (Object.keys(atomics).length && !(op in atomics)) - ) { - // a different op was previously registered. - // save the entire thing. - this[arrayAtomicsSymbol] = { $set: this }; - return this; - } - let selector; - - if (op === "$pullAll" || op === "$addToSet") { - atomics[op] || (atomics[op] = []); - atomics[op] = atomics[op].concat(val); - } else if (op === "$pullDocs") { - const pullOp = atomics["$pull"] || (atomics["$pull"] = {}); - if (val[0] instanceof EmbeddedDocument) { - selector = pullOp["$or"] || (pullOp["$or"] = []); - Array.prototype.push.apply( - selector, - val.map(function (v) { - return v.toObject({ transform: false, virtuals: false }); - }) - ); - } else { - selector = pullOp["_id"] || (pullOp["_id"] = { $in: [] }); - selector["$in"] = selector["$in"].concat(val); - } - } else if (op === "$push") { - atomics.$push = atomics.$push || { $each: [] }; - if (val != null && utils.hasUserDefinedProperty(val, "$each")) { - atomics.$push = val; - } else { - atomics.$push.$each = atomics.$push.$each.concat(val); - } - } else { - atomics[op] = val; - } - return this; - } +const MongooseError = __nccwpck_require__(4327); +const SchemaDateOptions = __nccwpck_require__(5354); +const SchemaType = __nccwpck_require__(5660); +const castDate = __nccwpck_require__(1001); +const getConstructorName = __nccwpck_require__(7323); +const utils = __nccwpck_require__(9232); - /** - * Adds values to the array if not already present. - * - * ####Example: - * - * console.log(doc.array) // [2,3,4] - * const added = doc.array.addToSet(4,5); - * console.log(doc.array) // [2,3,4,5] - * console.log(added) // [5] - * - * @param {any} [args...] - * @return {Array} the values that were added - * @memberOf MongooseArray - * @api public - * @method addToSet - */ +const CastError = SchemaType.CastError; - addToSet() { - _checkManualPopulation(this, arguments); +/** + * Date SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ - let values = [].map.call(arguments, this._mapCast, this); - values = this[arraySchemaSymbol].applySetters( - values, - this[arrayParentSymbol] - ); - const added = []; - let type = ""; - if (values[0] instanceof EmbeddedDocument) { - type = "doc"; - } else if (values[0] instanceof Date) { - type = "date"; - } +function SchemaDate(key, options) { + SchemaType.call(this, key, options, 'Date'); +} - values.forEach(function (v) { - let found; - const val = +v; - switch (type) { - case "doc": - found = this.some(function (doc) { - return doc.equals(v); - }); - break; - case "date": - found = this.some(function (d) { - return +d === val; - }); - break; - default: - found = ~this.indexOf(v); - } +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaDate.schemaName = 'Date'; - if (!found) { - [].push.call(this, v); - this._registerAtomic("$addToSet", v); - this._markModified(); - [].push.call(added, v); - } - }, this); +SchemaDate.defaultOptions = {}; - return added; - } +/*! + * Inherits from SchemaType. + */ +SchemaDate.prototype = Object.create(SchemaType.prototype); +SchemaDate.prototype.constructor = SchemaDate; +SchemaDate.prototype.OptionsConstructor = SchemaDateOptions; - /** - * Returns the number of pending atomic operations to send to the db for this array. - * - * @api private - * @return {Number} - * @method hasAtomics - * @memberOf MongooseArray - */ +/*! + * ignore + */ - hasAtomics() { - if (!utils.isPOJO(this[arrayAtomicsSymbol])) { - return 0; - } +SchemaDate._cast = castDate; - return Object.keys(this[arrayAtomicsSymbol]).length; - } +/** + * Sets a default option for all Date instances. + * + * ####Example: + * + * // Make all dates have `required` of true by default. + * mongoose.Schema.Date.set('required', true); + * + * const User = mongoose.model('User', new Schema({ test: Date })); + * new User({ }).validateSync().errors.test.message; // Path `test` is required. + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ - /** - * Return whether or not the `obj` is included in the array. - * - * @param {Object} obj the item to check - * @return {Boolean} - * @api public - * @method includes - * @memberOf MongooseArray - */ +SchemaDate.set = SchemaType.set; - includes(obj, fromIndex) { - const ret = this.indexOf(obj, fromIndex); - return ret !== -1; - } +/** + * Get/set the function used to cast arbitrary values to dates. + * + * ####Example: + * + * // Mongoose converts empty string '' into `null` for date types. You + * // can create a custom caster to disable it. + * const original = mongoose.Schema.Types.Date.cast(); + * mongoose.Schema.Types.Date.cast(v => { + * assert.ok(v !== ''); + * return original(v); + * }); + * + * // Or disable casting entirely + * mongoose.Schema.Types.Date.cast(false); + * + * @param {Function} caster + * @return {Function} + * @function get + * @static + * @api public + */ - /** - * Return the index of `obj` or `-1` if not found. - * - * @param {Object} obj the item to look for - * @return {Number} - * @api public - * @method indexOf - * @memberOf MongooseArray - */ +SchemaDate.cast = function cast(caster) { + if (arguments.length === 0) { + return this._cast; + } + if (caster === false) { + caster = this._defaultCaster; + } + this._cast = caster; - indexOf(obj, fromIndex) { - if (obj instanceof ObjectId) { - obj = obj.toString(); - } + return this._cast; +}; - fromIndex = fromIndex == null ? 0 : fromIndex; - const len = this.length; - for (let i = fromIndex; i < len; ++i) { - if (obj == this[i]) { - return i; - } - } - return -1; - } +/*! + * ignore + */ - /** - * Helper for console.log - * - * @api public - * @method inspect - * @memberOf MongooseArray - */ +SchemaDate._defaultCaster = v => { + if (v != null && !(v instanceof Date)) { + throw new Error(); + } + return v; +}; - inspect() { - return JSON.stringify(this); - } +/** + * Declares a TTL index (rounded to the nearest second) for _Date_ types only. + * + * This sets the `expireAfterSeconds` index option available in MongoDB >= 2.1.2. + * This index type is only compatible with Date types. + * + * ####Example: + * + * // expire in 24 hours + * new Schema({ createdAt: { type: Date, expires: 60*60*24 }}); + * + * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax: + * + * ####Example: + * + * // expire in 24 hours + * new Schema({ createdAt: { type: Date, expires: '24h' }}); + * + * // expire in 1.5 hours + * new Schema({ createdAt: { type: Date, expires: '1.5h' }}); + * + * // expire in 7 days + * const schema = new Schema({ createdAt: Date }); + * schema.path('createdAt').expires('7d'); + * + * @param {Number|String} when + * @added 3.0.0 + * @return {SchemaType} this + * @api public + */ - /** - * Pushes items to the array non-atomically. - * - * ####NOTE: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @param {any} [args...] - * @api public - * @method nonAtomicPush - * @memberOf MongooseArray - */ +SchemaDate.prototype.expires = function(when) { + if (getConstructorName(this._index) !== 'Object') { + this._index = {}; + } - nonAtomicPush() { - const values = [].map.call(arguments, this._mapCast, this); - const ret = [].push.apply(this, values); - this._registerAtomic("$set", this); - this._markModified(); - return ret; - } + this._index.expires = when; + utils.expires(this._index); + return this; +}; - /** - * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking. - * - * ####Note: - * - * _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @see MongooseArray#$pop #types_array_MongooseArray-%24pop - * @api public - * @method pop - * @memberOf MongooseArray - */ +/*! + * ignore + */ - pop() { - const ret = [].pop.call(this); - this._registerAtomic("$set", this); - this._markModified(); - return ret; - } +SchemaDate._checkRequired = v => v instanceof Date; - /** - * Pulls items from the array atomically. Equality is determined by casting - * the provided value to an embedded document and comparing using - * [the `Document.equals()` function.](./api.html#document_Document-equals) - * - * ####Examples: - * - * doc.array.pull(ObjectId) - * doc.array.pull({ _id: 'someId' }) - * doc.array.pull(36) - * doc.array.pull('tag 1', 'tag 2') - * - * To remove a document from a subdocument array we may pass an object with a matching `_id`. - * - * doc.subdocs.push({ _id: 4815162342 }) - * doc.subdocs.pull({ _id: 4815162342 }) // removed - * - * Or we may passing the _id directly and let mongoose take care of it. - * - * doc.subdocs.push({ _id: 4815162342 }) - * doc.subdocs.pull(4815162342); // works - * - * The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime. - * - * @param {any} [args...] - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull - * @api public - * @method pull - * @memberOf MongooseArray - */ +/** + * Override the function the required validator uses to check whether a string + * passes the `required` check. + * + * ####Example: + * + * // Allow empty strings to pass `required` check + * mongoose.Schema.Types.String.checkRequired(v => v != null); + * + * const M = mongoose.model({ str: { type: String, required: true } }); + * new M({ str: '' }).validateSync(); // `null`, validation passes! + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @static + * @api public + */ - pull() { - const values = [].map.call(arguments, this._cast, this); - const cur = this[arrayParentSymbol].get(this[arrayPathSymbol]); - let i = cur.length; - let mem; - - while (i--) { - mem = cur[i]; - if (mem instanceof Document) { - const some = values.some(function (v) { - return mem.equals(v); - }); - if (some) { - [].splice.call(cur, i, 1); - } - } else if (~cur.indexOf.call(values, mem)) { - [].splice.call(cur, i, 1); - } - } +SchemaDate.checkRequired = SchemaType.checkRequired; - if (values[0] instanceof EmbeddedDocument) { - this._registerAtomic( - "$pullDocs", - values.map(function (v) { - return v.$__getValue("_id") || v; - }) - ); - } else { - this._registerAtomic("$pullAll", values); - } +/** + * Check if the given value satisfies a required validator. To satisfy + * a required validator, the given value must be an instance of `Date`. + * + * @param {Any} value + * @param {Document} doc + * @return {Boolean} + * @api public + */ - this._markModified(); - - // Might have modified child paths and then pulled, like - // `doc.children[1].name = 'test';` followed by - // `doc.children.remove(doc.children[0]);`. In this case we fall back - // to a `$set` on the whole array. See #3511 - if ( - cleanModifiedSubpaths( - this[arrayParentSymbol], - this[arrayPathSymbol] - ) > 0 - ) { - this._registerAtomic("$set", this); - } +SchemaDate.prototype.checkRequired = function(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } - return this; - } + // `require('util').inherits()` does **not** copy static properties, and + // plugins like mongoose-float use `inherits()` for pre-ES6. + const _checkRequired = typeof this.constructor.checkRequired == 'function' ? + this.constructor.checkRequired() : + SchemaDate.checkRequired(); + return _checkRequired(value); +}; - /** - * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. - * - * ####Example: - * - * const schema = Schema({ nums: [Number] }); - * const Model = mongoose.model('Test', schema); - * - * const doc = await Model.create({ nums: [3, 4] }); - * doc.nums.push(5); // Add 5 to the end of the array - * await doc.save(); - * - * // You can also pass an object with `$each` as the - * // first parameter to use MongoDB's `$position` - * doc.nums.push({ - * $each: [1, 2], - * $position: 0 - * }); - * doc.nums; // [1, 2, 3, 4, 5] - * - * @param {Object} [args...] - * @api public - * @method push - * @memberOf MongooseArray - */ +/** + * Sets a minimum date validator. + * + * ####Example: + * + * const s = new Schema({ d: { type: Date, min: Date('1970-01-01') }) + * const M = db.model('M', s) + * const m = new M({ d: Date('1969-12-31') }) + * m.save(function (err) { + * console.error(err) // validator error + * m.d = Date('2014-12-08'); + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MIN} token which will be replaced with the invalid value + * const min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; + * const schema = new Schema({ d: { type: Date, min: min }) + * const M = mongoose.model('M', schema); + * const s= new M({ d: Date('1969-12-31') }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `d` (1969-12-31) is before the limit (1970-01-01). + * }) + * + * @param {Date} value minimum date + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ - push() { - let values = arguments; - let atomic = values; - const isOverwrite = - values[0] != null && - utils.hasUserDefinedProperty(values[0], "$each"); - if (isOverwrite) { - atomic = values[0]; - values = values[0].$each; - } +SchemaDate.prototype.min = function(value, message) { + if (this.minValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.minValidator; + }, this); + } - if (this[arraySchemaSymbol] == null) { - return _basePush.apply(this, values); - } + if (value) { + let msg = message || MongooseError.messages.Date.min; + if (typeof msg === 'string') { + msg = msg.replace(/{MIN}/, (value === Date.now ? 'Date.now()' : value.toString())); + } + const _this = this; + this.validators.push({ + validator: this.minValidator = function(val) { + let _value = value; + if (typeof value === 'function' && value !== Date.now) { + _value = _value.call(this); + } + const min = (_value === Date.now ? _value() : _this.cast(_value)); + return val === null || val.valueOf() >= min.valueOf(); + }, + message: msg, + type: 'min', + min: value + }); + } - _checkManualPopulation(this, values); + return this; +}; - const parent = this[arrayParentSymbol]; - values = [].map.call(values, this._mapCast, this); - values = this[arraySchemaSymbol].applySetters( - values, - parent, - undefined, - undefined, - { skipDocumentArrayCast: true } - ); - let ret; - const atomics = this[arrayAtomicsSymbol]; - - if (isOverwrite) { - atomic.$each = values; - - if ( - get(atomics, "$push.$each.length", 0) > 0 && - atomics.$push.$position != atomics.$position - ) { - throw new MongooseError( - "Cannot call `Array#push()` multiple times " + - "with different `$position`" - ); - } +/** + * Sets a maximum date validator. + * + * ####Example: + * + * const s = new Schema({ d: { type: Date, max: Date('2014-01-01') }) + * const M = db.model('M', s) + * const m = new M({ d: Date('2014-12-08') }) + * m.save(function (err) { + * console.error(err) // validator error + * m.d = Date('2013-12-31'); + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MAX} token which will be replaced with the invalid value + * const max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; + * const schema = new Schema({ d: { type: Date, max: max }) + * const M = mongoose.model('M', schema); + * const s= new M({ d: Date('2014-12-08') }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `d` (2014-12-08) exceeds the limit (2014-01-01). + * }) + * + * @param {Date} maximum date + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ - if (atomic.$position != null) { - [].splice.apply(this, [atomic.$position, 0].concat(values)); - ret = this.length; - } else { - ret = [].push.apply(this, values); - } - } else { - if ( - get(atomics, "$push.$each.length", 0) > 0 && - atomics.$push.$position != null - ) { - throw new MongooseError( - "Cannot call `Array#push()` multiple times " + - "with different `$position`" - ); - } - atomic = values; - ret = [].push.apply(this, values); - } - this._registerAtomic("$push", atomic); - this._markModified(); - return ret; - } +SchemaDate.prototype.max = function(value, message) { + if (this.maxValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.maxValidator; + }, this); + } - /** - * Alias of [pull](#mongoosearray_MongooseArray-pull) - * - * @see MongooseArray#pull #types_array_MongooseArray-pull - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull - * @api public - * @memberOf MongooseArray - * @instance - * @method remove - */ + if (value) { + let msg = message || MongooseError.messages.Date.max; + if (typeof msg === 'string') { + msg = msg.replace(/{MAX}/, (value === Date.now ? 'Date.now()' : value.toString())); + } + const _this = this; + this.validators.push({ + validator: this.maxValidator = function(val) { + let _value = value; + if (typeof _value === 'function' && _value !== Date.now) { + _value = _value.call(this); + } + const max = (_value === Date.now ? _value() : _this.cast(_value)); + return val === null || val.valueOf() <= max.valueOf(); + }, + message: msg, + type: 'max', + max: value + }); + } - remove() { - return this.pull.apply(this, arguments); - } + return this; +}; - /** - * Sets the casted `val` at index `i` and marks the array modified. - * - * ####Example: - * - * // given documents based on the following - * const Doc = mongoose.model('Doc', new Schema({ array: [Number] })); - * - * const doc = new Doc({ array: [2,3,4] }) - * - * console.log(doc.array) // [2,3,4] - * - * doc.array.set(1,"5"); - * console.log(doc.array); // [2,5,4] // properly cast to number - * doc.save() // the change is saved - * - * // VS not using array#set - * doc.array[1] = "5"; - * console.log(doc.array); // [2,"5",4] // no casting - * doc.save() // change is not saved - * - * @return {Array} this - * @api public - * @method set - * @memberOf MongooseArray - */ +/** + * Casts to date + * + * @param {Object} value to cast + * @api private + */ - set(i, val) { - const value = this._cast(val, i); - this[i] = value; - this._markModified(i); - return this; - } +SchemaDate.prototype.cast = function(value) { + let castDate; + if (typeof this._castFunction === 'function') { + castDate = this._castFunction; + } else if (typeof this.constructor.cast === 'function') { + castDate = this.constructor.cast(); + } else { + castDate = SchemaDate.cast(); + } - /** - * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. - * - * ####Example: - * - * doc.array = [2,3]; - * const res = doc.array.shift(); - * console.log(res) // 2 - * console.log(doc.array) // [3] - * - * ####Note: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - * @method shift - * @memberOf MongooseArray - */ + try { + return castDate(value); + } catch (error) { + throw new CastError('date', value, this.path, error, this); + } +}; - shift() { - const ret = [].shift.call(this); - this._registerAtomic("$set", this); - this._markModified(); - return ret; - } +/*! + * Date Query casting. + * + * @api private + */ - /** - * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking. - * - * ####NOTE: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - * @method sort - * @memberOf MongooseArray - * @see https://masteringjs.io/tutorials/fundamentals/array-sort - */ +function handleSingle(val) { + return this.cast(val); +} - sort() { - const ret = [].sort.apply(this, arguments); - this._registerAtomic("$set", this); - return ret; - } +SchemaDate.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle + }); - /** - * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. - * - * ####Note: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - * @method splice - * @memberOf MongooseArray - * @see https://masteringjs.io/tutorials/fundamentals/array-splice - */ - splice() { - let ret; +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ - _checkManualPopulation( - this, - Array.prototype.slice.call(arguments, 2) - ); +SchemaDate.prototype.castForQuery = function($conditional, val) { + if (arguments.length !== 2) { + return this._castForQuery($conditional); + } - if (arguments.length) { - let vals; - if (this[arraySchemaSymbol] == null) { - vals = arguments; - } else { - vals = []; - for (let i = 0; i < arguments.length; ++i) { - vals[i] = - i < 2 - ? arguments[i] - : this._cast(arguments[i], arguments[0] + (i - 2)); - } - } + const handler = this.$conditionalHandlers[$conditional]; - ret = [].splice.apply(this, vals); - this._registerAtomic("$set", this); - } + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with Date.'); + } - return ret; - } + return handler.call(this, val); +}; - /*! - * ignore - */ +/*! + * Module exports. + */ - slice() { - const ret = super.slice.apply(this, arguments); - ret[arrayParentSymbol] = this[arrayParentSymbol]; - ret[arraySchemaSymbol] = this[arraySchemaSymbol]; - ret[arrayAtomicsSymbol] = this[arrayAtomicsSymbol]; - ret[arrayPathSymbol] = this[arrayPathSymbol]; - ret[slicedSymbol] = true; - return ret; - } +module.exports = SchemaDate; - /*! - * ignore - */ - filter() { - const ret = super.filter.apply(this, arguments); - ret[arrayParentSymbol] = this[arrayParentSymbol]; - ret[arraySchemaSymbol] = this[arraySchemaSymbol]; - ret[arrayAtomicsSymbol] = this[arrayAtomicsSymbol]; - ret[arrayPathSymbol] = this[arrayPathSymbol]; - return ret; - } +/***/ }), - /*! - * ignore - */ +/***/ 8940: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - toBSON() { - return this.toObject(internalToObjectOptions); - } +"use strict"; +/*! + * Module dependencies. + */ - /** - * Returns a native js Array. - * - * @param {Object} options - * @return {Array} - * @api public - * @method toObject - * @memberOf MongooseArray - */ - toObject(options) { - if (options && options.depopulate) { - options = utils.clone(options); - options._isNested = true; - // Ensure return value is a vanilla array, because in Node.js 6+ `map()` - // is smart enough to use the inherited array's constructor. - return [].concat(this).map(function (doc) { - return doc instanceof Document ? doc.toObject(options) : doc; - }); - } - return [].concat(this); - } +const SchemaType = __nccwpck_require__(5660); +const CastError = SchemaType.CastError; +const Decimal128Type = __nccwpck_require__(8319); +const castDecimal128 = __nccwpck_require__(8748); +const utils = __nccwpck_require__(9232); - /** - * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. - * - * ####Note: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwriting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - * @method unshift - * @memberOf MongooseArray - */ +/** + * Decimal128 SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ - unshift() { - _checkManualPopulation(this, arguments); +function Decimal128(key, options) { + SchemaType.call(this, key, options, 'Decimal128'); +} - let values; - if (this[arraySchemaSymbol] == null) { - values = arguments; - } else { - values = [].map.call(arguments, this._cast, this); - values = this[arraySchemaSymbol].applySetters( - values, - this[arrayParentSymbol] - ); - } +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +Decimal128.schemaName = 'Decimal128'; - [].unshift.apply(this, values); - this._registerAtomic("$set", this); - this._markModified(); - return this.length; - } - } +Decimal128.defaultOptions = {}; - if (util.inspect.custom) { - CoreMongooseArray.prototype[util.inspect.custom] = - CoreMongooseArray.prototype.inspect; - } +/*! + * Inherits from SchemaType. + */ +Decimal128.prototype = Object.create(SchemaType.prototype); +Decimal128.prototype.constructor = Decimal128; - /*! - * ignore - */ +/*! + * ignore + */ - function _isAllSubdocs(docs, ref) { - if (!ref) { - return false; - } +Decimal128._cast = castDecimal128; - for (const arg of docs) { - if (arg == null) { - return false; - } - const model = arg.constructor; - if ( - !(arg instanceof Document) || - (model.modelName !== ref && model.baseModelName !== ref) - ) { - return false; - } - } +/** + * Sets a default option for all Decimal128 instances. + * + * ####Example: + * + * // Make all decimal 128s have `required` of true by default. + * mongoose.Schema.Decimal128.set('required', true); + * + * const User = mongoose.model('User', new Schema({ test: mongoose.Decimal128 })); + * new User({ }).validateSync().errors.test.message; // Path `test` is required. + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ - return true; - } +Decimal128.set = SchemaType.set; - /*! - * ignore - */ +/** + * Get/set the function used to cast arbitrary values to decimals. + * + * ####Example: + * + * // Make Mongoose only refuse to cast numbers as decimal128 + * const original = mongoose.Schema.Types.Decimal128.cast(); + * mongoose.Decimal128.cast(v => { + * assert.ok(typeof v !== 'number'); + * return original(v); + * }); + * + * // Or disable casting entirely + * mongoose.Decimal128.cast(false); + * + * @param {Function} [caster] + * @return {Function} + * @function get + * @static + * @api public + */ - function _checkManualPopulation(arr, docs) { - const ref = - arr == null - ? null - : get(arr[arraySchemaSymbol], "caster.options.ref", null); - if (arr.length === 0 && docs.length > 0) { - if (_isAllSubdocs(docs, ref)) { - arr[arrayParentSymbol].populated(arr[arrayPathSymbol], [], { - [populateModelSymbol]: docs[0].constructor, - }); - } - } - } +Decimal128.cast = function cast(caster) { + if (arguments.length === 0) { + return this._cast; + } + if (caster === false) { + caster = this._defaultCaster; + } + this._cast = caster; - module.exports = CoreMongooseArray; + return this._cast; +}; - /***/ - }, +/*! + * ignore + */ - /***/ 8319: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /** - * ObjectId type constructor - * - * ####Example - * - * const id = new mongoose.Types.ObjectId; - * - * @constructor ObjectId - */ - - module.exports = __nccwpck_require__(2324).get().Decimal128; - - /***/ - }, +Decimal128._defaultCaster = v => { + if (v != null && !(v instanceof Decimal128Type)) { + throw new Error(); + } + return v; +}; - /***/ 55: /***/ (module, __unused_webpack_exports, __nccwpck_require__) => { - "use strict"; +/*! + * ignore + */ - /*! - * Module dependencies. - */ +Decimal128._checkRequired = v => v instanceof Decimal128Type; - const CoreMongooseArray = __nccwpck_require__(7146); - const Document = __nccwpck_require__(6717); - const ObjectId = __nccwpck_require__(2706); - const castObjectId = __nccwpck_require__(5552); - const getDiscriminatorByValue = __nccwpck_require__(8689); - const internalToObjectOptions = - __nccwpck_require__(5684) /* .internalToObjectOptions */.h; - const util = __nccwpck_require__(1669); - const utils = __nccwpck_require__(9232); +/** + * Override the function the required validator uses to check whether a string + * passes the `required` check. + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @static + * @api public + */ - const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; - const arrayParentSymbol = __nccwpck_require__(3240).arrayParentSymbol; - const arrayPathSymbol = __nccwpck_require__(3240).arrayPathSymbol; - const arraySchemaSymbol = __nccwpck_require__(3240).arraySchemaSymbol; - const documentArrayParent = __nccwpck_require__(3240).documentArrayParent; +Decimal128.checkRequired = SchemaType.checkRequired; - const _basePush = Array.prototype.push; +/** + * Check if the given value satisfies a required validator. + * + * @param {Any} value + * @param {Document} doc + * @return {Boolean} + * @api public + */ - class CoreDocumentArray extends CoreMongooseArray { - get isMongooseDocumentArray() { - return true; - } +Decimal128.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } - /*! - * ignore - */ + // `require('util').inherits()` does **not** copy static properties, and + // plugins like mongoose-float use `inherits()` for pre-ES6. + const _checkRequired = typeof this.constructor.checkRequired == 'function' ? + this.constructor.checkRequired() : + Decimal128.checkRequired(); - toBSON() { - return this.toObject(internalToObjectOptions); - } + return _checkRequired(value); +}; - /*! - * ignore - */ +/** + * Casts to Decimal128 + * + * @param {Object} value + * @param {Object} doc + * @param {Boolean} init whether this is an initialization cast + * @api private + */ - map() { - const ret = super.map.apply(this, arguments); - ret[arraySchemaSymbol] = null; - ret[arrayPathSymbol] = null; - ret[arrayParentSymbol] = null; +Decimal128.prototype.cast = function(value, doc, init) { + if (SchemaType._isRef(this, value, doc, init)) { + if (value instanceof Decimal128Type) { + return value; + } - return ret; - } + return this._castRef(value, doc, init); + } - /** - * Overrides MongooseArray#cast - * - * @method _cast - * @api private - * @receiver MongooseDocumentArray - */ + let castDecimal128; + if (typeof this._castFunction === 'function') { + castDecimal128 = this._castFunction; + } else if (typeof this.constructor.cast === 'function') { + castDecimal128 = this.constructor.cast(); + } else { + castDecimal128 = Decimal128.cast(); + } - _cast(value, index) { - if (this[arraySchemaSymbol] == null) { - return value; - } - let Constructor = this[arraySchemaSymbol].casterConstructor; - const isInstance = Constructor.$isMongooseDocumentArray - ? value && value.isMongooseDocumentArray - : value instanceof Constructor; - if ( - isInstance || - // Hack re: #5001, see #5005 - (value && - value.constructor && - value.constructor.baseCasterConstructor === Constructor) - ) { - if (!(value[documentArrayParent] && value.__parentArray)) { - // value may have been created using array.create() - value[documentArrayParent] = this[arrayParentSymbol]; - value.__parentArray = this; - } - value.$setIndex(index); - return value; - } + try { + return castDecimal128(value); + } catch (error) { + throw new CastError('Decimal128', value, this.path, error, this); + } +}; - if (value === undefined || value === null) { - return null; - } +/*! + * ignore + */ - // handle cast('string') or cast(ObjectId) etc. - // only objects are permitted so we can safely assume that - // non-objects are to be interpreted as _id - if ( - Buffer.isBuffer(value) || - value instanceof ObjectId || - !utils.isObject(value) - ) { - value = { _id: value }; - } +function handleSingle(val) { + return this.cast(val); +} - if ( - value && - Constructor.discriminators && - Constructor.schema && - Constructor.schema.options && - Constructor.schema.options.discriminatorKey - ) { - if ( - typeof value[Constructor.schema.options.discriminatorKey] === - "string" && - Constructor.discriminators[ - value[Constructor.schema.options.discriminatorKey] - ] - ) { - Constructor = - Constructor.discriminators[ - value[Constructor.schema.options.discriminatorKey] - ]; - } else { - const constructorByValue = getDiscriminatorByValue( - Constructor.discriminators, - value[Constructor.schema.options.discriminatorKey] - ); - if (constructorByValue) { - Constructor = constructorByValue; - } - } - } +Decimal128.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle + }); - if (Constructor.$isMongooseDocumentArray) { - return Constructor.cast(value, this, undefined, undefined, index); - } - return new Constructor(value, this, undefined, undefined, index); - } +/*! + * Module exports. + */ - /** - * Searches array items for the first document with a matching _id. - * - * ####Example: - * - * const embeddedDoc = m.array.id(some_id); - * - * @return {EmbeddedDocument|null} the subdocument or null if not found. - * @param {ObjectId|String|Number|Buffer} id - * @TODO cast to the _id based on schema for proper comparison - * @method id - * @api public - * @receiver MongooseDocumentArray - */ +module.exports = Decimal128; - id(id) { - let casted; - let sid; - let _id; - try { - casted = castObjectId(id).toString(); - } catch (e) { - casted = null; - } +/***/ }), - for (const val of this) { - if (!val) { - continue; - } +/***/ 182: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _id = val.get("_id"); +"use strict"; - if (_id === null || typeof _id === "undefined") { - continue; - } else if (_id instanceof Document) { - sid || (sid = String(id)); - if (sid == _id._id) { - return val; - } - } else if ( - !(id instanceof ObjectId) && - !(_id instanceof ObjectId) - ) { - if (id == _id || utils.deepEqual(id, _id)) { - return val; - } - } else if (casted == _id) { - return val; - } - } - return null; - } +/*! + * Module dependencies. + */ - /** - * Returns a native js Array of plain js objects - * - * ####NOTE: - * - * _Each sub-document is converted to a plain object by calling its `#toObject` method._ - * - * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion - * @return {Array} - * @method toObject - * @api public - * @receiver MongooseDocumentArray - */ +const ArrayType = __nccwpck_require__(6090); +const CastError = __nccwpck_require__(2798); +const EventEmitter = __nccwpck_require__(8614).EventEmitter; +const SchemaDocumentArrayOptions = + __nccwpck_require__(4508); +const SchemaType = __nccwpck_require__(5660); +const discriminator = __nccwpck_require__(1462); +const get = __nccwpck_require__(8730); +const handleIdOption = __nccwpck_require__(8965); +const util = __nccwpck_require__(1669); +const utils = __nccwpck_require__(9232); +const getConstructor = __nccwpck_require__(1449); + +const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; +const arrayPathSymbol = __nccwpck_require__(3240).arrayPathSymbol; +const documentArrayParent = __nccwpck_require__(3240).documentArrayParent; + +let MongooseDocumentArray; +let Subdocument; + +/** + * SubdocsArray SchemaType constructor + * + * @param {String} key + * @param {Schema} schema + * @param {Object} options + * @inherits SchemaArray + * @api public + */ - toObject(options) { - // `[].concat` coerces the return value into a vanilla JS array, rather - // than a Mongoose array. - return [].concat( - this.map(function (doc) { - if (doc == null) { - return null; - } - if (typeof doc.toObject !== "function") { - return doc; - } - return doc.toObject(options); - }) - ); - } +function DocumentArrayPath(key, schema, options, schemaOptions) { + if (schemaOptions != null && schemaOptions._id != null) { + schema = handleIdOption(schema, schemaOptions); + } else if (options != null && options._id != null) { + schema = handleIdOption(schema, options); + } - slice() { - const arr = super.slice.apply(this, arguments); - arr[arrayParentSymbol] = this[arrayParentSymbol]; - arr[arrayPathSymbol] = this[arrayPathSymbol]; + const EmbeddedDocument = _createConstructor(schema, options); + EmbeddedDocument.prototype.$basePath = key; - return arr; - } + ArrayType.call(this, key, EmbeddedDocument, options); - /** - * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. - * - * @param {Object} [args...] - * @api public - * @method push - * @memberOf MongooseDocumentArray - */ + this.schema = schema; + this.schemaOptions = schemaOptions || {}; + this.$isMongooseDocumentArray = true; + this.Constructor = EmbeddedDocument; - push() { - const ret = super.push.apply(this, arguments); + EmbeddedDocument.base = schema.base; - _updateParentPopulated(this); + const fn = this.defaultValue; - return ret; - } + if (!('defaultValue' in this) || fn !== void 0) { + this.default(function() { + let arr = fn.call(this); + if (arr != null && !Array.isArray(arr)) { + arr = [arr]; + } + // Leave it up to `cast()` to convert this to a documentarray + return arr; + }); + } - /** - * Pulls items from the array atomically. - * - * @param {Object} [args...] - * @api public - * @method pull - * @memberOf MongooseDocumentArray - */ + const parentSchemaType = this; + this.$embeddedSchemaType = new SchemaType(key + '.$', { + required: get(this, 'schemaOptions.required', false) + }); + this.$embeddedSchemaType.cast = function(value, doc, init) { + return parentSchemaType.cast(value, doc, init)[0]; + }; + this.$embeddedSchemaType.$isMongooseDocumentArrayElement = true; + this.$embeddedSchemaType.caster = this.Constructor; + this.$embeddedSchemaType.schema = this.schema; +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +DocumentArrayPath.schemaName = 'DocumentArray'; - pull() { - const ret = super.pull.apply(this, arguments); +/** + * Options for all document arrays. + * + * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting. + * + * @api public + */ - _updateParentPopulated(this); +DocumentArrayPath.options = { castNonArrays: true }; - return ret; - } +/*! + * Inherits from ArrayType. + */ +DocumentArrayPath.prototype = Object.create(ArrayType.prototype); +DocumentArrayPath.prototype.constructor = DocumentArrayPath; +DocumentArrayPath.prototype.OptionsConstructor = SchemaDocumentArrayOptions; - /** - * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. - */ +/*! + * Ignore + */ - shift() { - const ret = super.shift.apply(this, arguments); +function _createConstructor(schema, options, baseClass) { + Subdocument || (Subdocument = __nccwpck_require__(9999)); - _updateParentPopulated(this); + // compile an embedded document for this schema + function EmbeddedDocument() { + Subdocument.apply(this, arguments); - return ret; - } + this.$session(this.ownerDocument().$session()); + } - /** - * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. - */ + schema._preCompile(); - splice() { - const ret = super.splice.apply(this, arguments); + const proto = baseClass != null ? baseClass.prototype : Subdocument.prototype; + EmbeddedDocument.prototype = Object.create(proto); + EmbeddedDocument.prototype.$__setSchema(schema); + EmbeddedDocument.schema = schema; + EmbeddedDocument.prototype.constructor = EmbeddedDocument; + EmbeddedDocument.$isArraySubdocument = true; + EmbeddedDocument.events = new EventEmitter(); - _updateParentPopulated(this); + // apply methods + for (const i in schema.methods) { + EmbeddedDocument.prototype[i] = schema.methods[i]; + } - return ret; - } + // apply statics + for (const i in schema.statics) { + EmbeddedDocument[i] = schema.statics[i]; + } - /** - * Helper for console.log - * - * @method inspect - * @api public - * @receiver MongooseDocumentArray - */ + for (const i in EventEmitter.prototype) { + EmbeddedDocument[i] = EventEmitter.prototype[i]; + } - inspect() { - return this.toObject(); - } + EmbeddedDocument.options = options; - /** - * Creates a subdocument casted to this schema. - * - * This is the same subdocument constructor used for casting. - * - * @param {Object} obj the value to cast to this arrays SubDocument schema - * @method create - * @api public - * @receiver MongooseDocumentArray - */ + return EmbeddedDocument; +} - create(obj) { - let Constructor = this[arraySchemaSymbol].casterConstructor; - if ( - obj && - Constructor.discriminators && - Constructor.schema && - Constructor.schema.options && - Constructor.schema.options.discriminatorKey - ) { - if ( - typeof obj[Constructor.schema.options.discriminatorKey] === - "string" && - Constructor.discriminators[ - obj[Constructor.schema.options.discriminatorKey] - ] - ) { - Constructor = - Constructor.discriminators[ - obj[Constructor.schema.options.discriminatorKey] - ]; - } else { - const constructorByValue = getDiscriminatorByValue( - Constructor.discriminators, - obj[Constructor.schema.options.discriminatorKey] - ); - if (constructorByValue) { - Constructor = constructorByValue; - } - } - } +/** + * Adds a discriminator to this document array. + * + * ####Example: + * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' }); + * const schema = Schema({ shapes: [shapeSchema] }); + * + * const docArrayPath = parentSchema.path('shapes'); + * docArrayPath.discriminator('Circle', Schema({ radius: Number })); + * + * @param {String} name + * @param {Schema} schema fields to add to the schema for instances of this sub-class + * @param {Object|string} [options] If string, same as `options.value`. + * @param {String} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. + * @param {Boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning. + * @see discriminators /docs/discriminators.html + * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model + * @api public + */ - return new Constructor(obj, this); - } +DocumentArrayPath.prototype.discriminator = function(name, schema, options) { + if (typeof name === 'function') { + name = utils.getFunctionName(name); + } - /*! - * ignore - */ + options = options || {}; + const tiedValue = utils.isPOJO(options) ? options.value : options; + const clone = get(options, 'clone', true); - notify(event) { - const _this = this; - return function notify(val, _arr) { - _arr = _arr || _this; - let i = _arr.length; - while (i--) { - if (_arr[i] == null) { - continue; - } - switch (event) { - // only swap for save event for now, we may change this to all event types later - case "save": - val = _this[i]; - break; - default: - // NO-OP - break; - } + if (schema.instanceOfSchema && clone) { + schema = schema.clone(); + } - if (_arr[i].isMongooseArray) { - notify(val, _arr[i]); - } else if (_arr[i]) { - _arr[i].emit(event, val); - } - } - }; - } + schema = discriminator(this.casterConstructor, name, schema, tiedValue); - _markModified(elem, embeddedPath) { - const parent = this[arrayParentSymbol]; - let dirtyPath; + const EmbeddedDocument = _createConstructor(schema, null, this.casterConstructor); + EmbeddedDocument.baseCasterConstructor = this.casterConstructor; - if (parent) { - dirtyPath = this[arrayPathSymbol]; + try { + Object.defineProperty(EmbeddedDocument, 'name', { + value: name + }); + } catch (error) { + // Ignore error, only happens on old versions of node + } - if (arguments.length) { - if (embeddedPath != null) { - // an embedded doc bubbled up the change - const index = elem.__index; - dirtyPath = dirtyPath + "." + index + "." + embeddedPath; - } else { - // directly set an index - dirtyPath = dirtyPath + "." + elem; - } - } + this.casterConstructor.discriminators[name] = EmbeddedDocument; - if (dirtyPath != null && dirtyPath.endsWith(".$")) { - return this; - } + return this.casterConstructor.discriminators[name]; +}; - parent.markModified( - dirtyPath, - arguments.length > 0 ? elem : parent - ); - } +/** + * Performs local validations first, then validations on each embedded doc + * + * @api private + */ - return this; - } - } +DocumentArrayPath.prototype.doValidate = function(array, fn, scope, options) { + // lazy load + MongooseDocumentArray || (MongooseDocumentArray = __nccwpck_require__(3369)); - if (util.inspect.custom) { - CoreDocumentArray.prototype[util.inspect.custom] = - CoreDocumentArray.prototype.inspect; - } + const _this = this; + try { + SchemaType.prototype.doValidate.call(this, array, cb, scope); + } catch (err) { + return fn(err); + } - /*! - * If this is a document array, each element may contain single - * populated paths, so we need to modify the top-level document's - * populated cache. See gh-8247, gh-8265. - */ + function cb(err) { + if (err) { + return fn(err); + } - function _updateParentPopulated(arr) { - const parent = arr[arrayParentSymbol]; - if (!parent || parent.$__.populated == null) return; + let count = array && array.length; + let error; - const populatedPaths = Object.keys(parent.$__.populated).filter((p) => - p.startsWith(arr[arrayPathSymbol] + ".") - ); + if (!count) { + return fn(); + } + if (options && options.updateValidator) { + return fn(); + } + if (!array.isMongooseDocumentArray) { + array = new MongooseDocumentArray(array, _this.path, scope); + } - for (const path of populatedPaths) { - const remnant = path.slice((arr[arrayPathSymbol] + ".").length); - if (!Array.isArray(parent.$__.populated[path].value)) { - continue; - } + // handle sparse arrays, do not use array.forEach which does not + // iterate over sparse elements yet reports array.length including + // them :( - parent.$__.populated[path].value = arr.map((val) => - val.populated(remnant) - ); - } + function callback(err) { + if (err != null) { + error = err; } + --count || fn(error); + } - /** - * DocumentArray constructor - * - * @param {Array} values - * @param {String} path the path to this array - * @param {Document} doc parent document - * @api private - * @return {MongooseDocumentArray} - * @inherits MongooseArray - * @see http://bit.ly/f6CnZU - */ - - function MongooseDocumentArray(values, path, doc) { - // TODO: replace this with `new CoreDocumentArray().concat()` when we remove - // support for node 4.x and 5.x, see https://i.imgur.com/UAAHk4S.png - const arr = new CoreDocumentArray(); - - arr[arrayAtomicsSymbol] = {}; - arr[arraySchemaSymbol] = void 0; - if (Array.isArray(values)) { - if ( - values[arrayPathSymbol] === path && - values[arrayParentSymbol] === doc - ) { - arr[arrayAtomicsSymbol] = Object.assign( - {}, - values[arrayAtomicsSymbol] - ); - } - values.forEach((v) => { - _basePush.call(arr, v); - }); - } - arr[arrayPathSymbol] = path; - - // Because doc comes from the context of another function, doc === global - // can happen if there was a null somewhere up the chain (see #3020 && #3034) - // RB Jun 17, 2015 updated to check for presence of expected paths instead - // to make more proof against unusual node environments - if (doc && doc instanceof Document) { - arr[arrayParentSymbol] = doc; - arr[arraySchemaSymbol] = doc.schema.path(path); - - // `schema.path()` doesn't drill into nested arrays properly yet, see - // gh-6398, gh-6602. This is a workaround because nested arrays are - // always plain non-document arrays, so once you get to a document array - // nesting is done. Matryoshka code. - while ( - arr != null && - arr[arraySchemaSymbol] != null && - arr[arraySchemaSymbol].$isMongooseArray && - !arr[arraySchemaSymbol].$isMongooseDocumentArray - ) { - arr[arraySchemaSymbol] = arr[arraySchemaSymbol].casterConstructor; - } - } + for (let i = 0, len = count; i < len; ++i) { + // sidestep sparse entries + let doc = array[i]; + if (doc == null) { + --count || fn(error); + continue; + } - return arr; + // If you set the array index directly, the doc might not yet be + // a full fledged mongoose subdoc, so make it into one. + if (!(doc instanceof Subdocument)) { + const Constructor = getConstructor(_this.casterConstructor, array[i]); + doc = array[i] = new Constructor(doc, array, undefined, undefined, i); } - /*! - * Module exports. - */ + if (options != null && options.validateModifiedOnly && !doc.$isModified()) { + --count || fn(error); + continue; + } - module.exports = MongooseDocumentArray; + doc.$__validate(callback); + } + } +}; - /***/ - }, +/** + * Performs local validations first, then validations on each embedded doc. + * + * ####Note: + * + * This method ignores the asynchronous validators. + * + * @return {MongooseError|undefined} + * @api private + */ - /***/ 4433: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /* eslint no-func-assign: 1 */ - - /*! - * Module dependencies. - */ - - const Document = __nccwpck_require__(1860)(); - const EventEmitter = __nccwpck_require__(8614).EventEmitter; - const ValidationError = __nccwpck_require__(8460); - const immediate = __nccwpck_require__(4830); - const internalToObjectOptions = - __nccwpck_require__(5684) /* .internalToObjectOptions */.h; - const get = __nccwpck_require__(8730); - const promiseOrCallback = __nccwpck_require__(4046); - const util = __nccwpck_require__(1669); - - const documentArrayParent = __nccwpck_require__(3240).documentArrayParent; - const validatorErrorSymbol = - __nccwpck_require__(3240).validatorErrorSymbol; - - /** - * EmbeddedDocument constructor. - * - * @param {Object} obj js object returned from the db - * @param {MongooseDocumentArray} parentArr the parent array of this document - * @param {Boolean} skipId - * @inherits Document - * @api private - */ - - function EmbeddedDocument(obj, parentArr, skipId, fields, index) { - const options = {}; - if (parentArr != null && parentArr.isMongooseDocumentArray) { - this.__parentArray = parentArr; - this[documentArrayParent] = parentArr.$parent(); - } else { - this.__parentArray = undefined; - this[documentArrayParent] = undefined; - } - this.$setIndex(index); - this.$isDocumentArrayElement = true; +DocumentArrayPath.prototype.doValidateSync = function(array, scope, options) { + const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope); + if (schemaTypeError != null) { + return schemaTypeError; + } - if (this[documentArrayParent] != null) { - options.defaults = this[documentArrayParent].$__.$options.defaults; - } + const count = array && array.length; + let resultError = null; - Document.call(this, obj, fields, skipId, options); + if (!count) { + return; + } - const _this = this; - this.on("isNew", function (val) { - _this.isNew = val; - }); + // handle sparse arrays, do not use array.forEach which does not + // iterate over sparse elements yet reports array.length including + // them :( - _this.on("save", function () { - _this.constructor.emit("save", _this); - }); - } + for (let i = 0, len = count; i < len; ++i) { + // sidestep sparse entries + let doc = array[i]; + if (!doc) { + continue; + } - /*! - * Inherit from Document - */ - EmbeddedDocument.prototype = Object.create(Document.prototype); - EmbeddedDocument.prototype.constructor = EmbeddedDocument; + // If you set the array index directly, the doc might not yet be + // a full fledged mongoose subdoc, so make it into one. + if (!(doc instanceof Subdocument)) { + const Constructor = getConstructor(this.casterConstructor, array[i]); + doc = array[i] = new Constructor(doc, array, undefined, undefined, i); + } - for (const i in EventEmitter.prototype) { - EmbeddedDocument[i] = EventEmitter.prototype[i]; - } + if (options != null && options.validateModifiedOnly && !doc.$isModified()) { + continue; + } - EmbeddedDocument.prototype.toBSON = function () { - return this.toObject(internalToObjectOptions); - }; + const subdocValidateError = doc.validateSync(); - /*! - * ignore - */ + if (subdocValidateError && resultError == null) { + resultError = subdocValidateError; + } + } - EmbeddedDocument.prototype.$setIndex = function (index) { - this.__index = index; + return resultError; +}; - if (get(this, "$__.validationError", null) != null) { - const keys = Object.keys(this.$__.validationError.errors); - for (const key of keys) { - this.invalidate(key, this.$__.validationError.errors[key]); - } - } - }; +/*! + * ignore + */ - /** - * Marks the embedded doc modified. - * - * ####Example: - * - * const doc = blogpost.comments.id(hexstring); - * doc.mixed.type = 'changed'; - * doc.markModified('mixed.type'); - * - * @param {String} path the path which changed - * @api public - * @receiver EmbeddedDocument - */ - - EmbeddedDocument.prototype.markModified = function (path) { - this.$__.activePaths.modify(path); - if (!this.__parentArray) { - return; - } +DocumentArrayPath.prototype.getDefault = function(scope) { + let ret = typeof this.defaultValue === 'function' + ? this.defaultValue.call(scope) + : this.defaultValue; - const pathToCheck = this.__parentArray.$path() + ".0." + path; - if (this.isNew && this.ownerDocument().$__isSelected(pathToCheck)) { - // Mark the WHOLE parent array as modified - // if this is a new document (i.e., we are initializing - // a document), - this.__parentArray._markModified(); - } else { - this.__parentArray._markModified(this, path); - } - }; + if (ret == null) { + return ret; + } - /*! - * ignore - */ + // lazy load + MongooseDocumentArray || (MongooseDocumentArray = __nccwpck_require__(3369)); - EmbeddedDocument.prototype.populate = function () { - throw new Error( - "Mongoose does not support calling populate() on nested " + - 'docs. Instead of `doc.arr[0].populate("path")`, use ' + - '`doc.populate("arr.0.path")`' - ); - }; + if (!Array.isArray(ret)) { + ret = [ret]; + } - /** - * Used as a stub for [hooks.js](https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3) - * - * ####NOTE: - * - * _This is a no-op. Does not actually save the doc to the db._ - * - * @param {Function} [fn] - * @return {Promise} resolved Promise - * @api private - */ - - EmbeddedDocument.prototype.save = function (options, fn) { - if (typeof options === "function") { - fn = options; - options = {}; - } - options = options || {}; + ret = new MongooseDocumentArray(ret, this.path, scope); - if (!options.suppressWarning) { - console.warn( - "mongoose: calling `save()` on a subdoc does **not** save " + - "the document to MongoDB, it only runs save middleware. " + - "Use `subdoc.save({ suppressWarning: true })` to hide this warning " + - "if you're sure this behavior is right for your app." - ); - } + for (let i = 0; i < ret.length; ++i) { + const Constructor = getConstructor(this.casterConstructor, ret[i]); + const _subdoc = new Constructor({}, ret, undefined, + undefined, i); + _subdoc.$init(ret[i]); + _subdoc.isNew = true; - return promiseOrCallback(fn, (cb) => { - this.$__save(cb); - }); - }; + // Make sure all paths in the subdoc are set to `default` instead + // of `init` since we used `init`. + Object.assign(_subdoc.$__.activePaths.default, _subdoc.$__.activePaths.init); + _subdoc.$__.activePaths.init = {}; - /** - * Used as a stub for middleware - * - * ####NOTE: - * - * _This is a no-op. Does not actually save the doc to the db._ - * - * @param {Function} [fn] - * @method $__save - * @api private - */ - - EmbeddedDocument.prototype.$__save = function (fn) { - return immediate(() => fn(null, this)); - }; + ret[i] = _subdoc; + } - /*! - * Registers remove event listeners for triggering - * on subdocuments. - * - * @param {EmbeddedDocument} sub - * @api private - */ + return ret; +}; - function registerRemoveListener(sub) { - let owner = sub.ownerDocument(); +/** + * Casts contents + * + * @param {Object} value + * @param {Document} document that triggers the casting + * @api private + */ - function emitRemove() { - owner.removeListener("save", emitRemove); - owner.removeListener("remove", emitRemove); - sub.emit("remove", sub); - sub.constructor.emit("remove", sub); - owner = sub = null; - } +DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) { + // lazy load + MongooseDocumentArray || (MongooseDocumentArray = __nccwpck_require__(3369)); - owner.on("save", emitRemove); - owner.on("remove", emitRemove); - } + // Skip casting if `value` is the same as the previous value, no need to cast. See gh-9266 + if (value != null && value[arrayPathSymbol] != null && value === prev) { + return value; + } - /*! - * no-op for hooks - */ + let selected; + let subdoc; + const _opts = { transform: false, virtuals: false }; + options = options || {}; - EmbeddedDocument.prototype.$__remove = function (cb) { - if (cb == null) { - return; - } - return cb(null, this); - }; + if (!Array.isArray(value)) { + if (!init && !DocumentArrayPath.options.castNonArrays) { + throw new CastError('DocumentArray', util.inspect(value), this.path, null, this); + } + // gh-2442 mark whole array as modified if we're initializing a doc from + // the db and the path isn't an array in the document + if (!!doc && init) { + doc.markModified(this.path); + } + return this.cast([value], doc, init, prev, options); + } - /** - * Removes the subdocument from its parent array. - * - * @param {Object} [options] - * @param {Function} [fn] - * @api public - */ - - EmbeddedDocument.prototype.remove = function (options, fn) { - if (typeof options === "function" && !fn) { - fn = options; - options = undefined; - } - if (!this.__parentArray || (options && options.noop)) { - this.$__remove(fn); - return this; - } + if (!(value && value.isMongooseDocumentArray) && + !options.skipDocumentArrayCast) { + value = new MongooseDocumentArray(value, this.path, doc); + } else if (value && value.isMongooseDocumentArray) { + // We need to create a new array, otherwise change tracking will + // update the old doc (gh-4449) + value = new MongooseDocumentArray(value, this.path, doc); + } - let _id; - if (!this.willRemove) { - _id = this._doc._id; - if (!_id) { - throw new Error( - "For your own good, Mongoose does not know " + - "how to remove an EmbeddedDocument that has no _id" - ); - } - this.__parentArray.pull({ _id: _id }); - this.willRemove = true; - registerRemoveListener(this); - } + if (prev != null) { + value[arrayAtomicsSymbol] = prev[arrayAtomicsSymbol] || {}; + } - this.$__remove(fn); + if (options.arrayPathIndex != null) { + value[arrayPathSymbol] = this.path + '.' + options.arrayPathIndex; + } - return this; - }; + const rawArray = value.isMongooseDocumentArrayProxy ? value.__array : value; - /** - * Override #update method of parent documents. - * @api private - */ + const len = rawArray.length; + const initDocumentOptions = { skipId: true, willInit: true }; - EmbeddedDocument.prototype.update = function () { - throw new Error( - "The #update method is not available on EmbeddedDocuments" - ); - }; + for (let i = 0; i < len; ++i) { + if (!rawArray[i]) { + continue; + } - /** - * Helper for console.log - * - * @api public - */ - - EmbeddedDocument.prototype.inspect = function () { - return this.toObject({ - transform: false, - virtuals: false, - flattenDecimals: false, - }); - }; + const Constructor = getConstructor(this.casterConstructor, value[i]); - if (util.inspect.custom) { - /*! - * Avoid Node deprecation warning DEP0079 - */ + // Check if the document has a different schema (re gh-3701) + if (rawArray[i].$__ && !(rawArray[i] instanceof Constructor)) { + rawArray[i] = rawArray[i].toObject({ + transform: false, + // Special case: if different model, but same schema, apply virtuals + // re: gh-7898 + virtuals: rawArray[i].schema === Constructor.schema + }); + } - EmbeddedDocument.prototype[util.inspect.custom] = - EmbeddedDocument.prototype.inspect; + if (rawArray[i] instanceof Subdocument) { + if (rawArray[i][documentArrayParent] !== doc) { + if (init) { + const subdoc = new Constructor(null, value, initDocumentOptions, selected, i); + rawArray[i] = subdoc.$init(rawArray[i]); + } else { + const subdoc = new Constructor(rawArray[i], value, undefined, undefined, i); + rawArray[i] = subdoc; + } } + // Might not have the correct index yet, so ensure it does. + if (rawArray[i].__index == null) { + rawArray[i].$setIndex(i); + } + } else if (rawArray[i] != null) { + if (init) { + if (doc) { + selected || (selected = scopePaths(this, doc.$__.selected, init)); + } else { + selected = true; + } - /** - * Marks a path as invalid, causing validation to fail. - * - * @param {String} path the field to invalidate - * @param {String|Error} err error which states the reason `path` was invalid - * @return {Boolean} - * @api public - */ - - EmbeddedDocument.prototype.invalidate = function (path, err, val) { - Document.prototype.invalidate.call(this, path, err, val); + subdoc = new Constructor(null, value, initDocumentOptions, selected, i); + rawArray[i] = subdoc.$init(rawArray[i]); + } else { + if (prev && typeof prev.id === 'function') { + subdoc = prev.id(rawArray[i]._id); + } - if (!this[documentArrayParent] || this.__index == null) { - if (err[validatorErrorSymbol] || err instanceof ValidationError) { - return this.ownerDocument().$__.validationError; + if (prev && subdoc && utils.deepEqual(subdoc.toObject(_opts), rawArray[i])) { + // handle resetting doc with existing id and same data + subdoc.set(rawArray[i]); + // if set() is hooked it will have no return value + // see gh-746 + rawArray[i] = subdoc; + } else { + try { + subdoc = new Constructor(rawArray[i], value, undefined, + undefined, i); + // if set() is hooked it will have no return value + // see gh-746 + rawArray[i] = subdoc; + } catch (error) { + const valueInErrorMessage = util.inspect(rawArray[i]); + throw new CastError('embedded', valueInErrorMessage, + value[arrayPathSymbol], error, this); } - throw err; } + } + } + } - const index = this.__index; - const parentPath = this.__parentArray.$path(); - const fullPath = [parentPath, index, path].join("."); - this[documentArrayParent].invalidate(fullPath, err, val); + return value; +}; - return this.ownerDocument().$__.validationError; - }; +/*! + * ignore + */ - /** - * Marks a path as valid, removing existing validation errors. - * - * @param {String} path the field to mark as valid - * @api private - * @method $markValid - * @receiver EmbeddedDocument - */ - - EmbeddedDocument.prototype.$markValid = function (path) { - if (!this[documentArrayParent]) { - return; - } +DocumentArrayPath.prototype.clone = function() { + const options = Object.assign({}, this.options); + const schematype = new this.constructor(this.path, this.schema, options, this.schemaOptions); + schematype.validators = this.validators.slice(); + if (this.requiredValidator !== undefined) { + schematype.requiredValidator = this.requiredValidator; + } + schematype.Constructor.discriminators = Object.assign({}, + this.Constructor.discriminators); + return schematype; +}; - const index = this.__index; - if (typeof index !== "undefined") { - const parentPath = this.__parentArray.$path(); - const fullPath = [parentPath, index, path].join("."); - this[documentArrayParent].$markValid(fullPath); - } - }; +/*! + * ignore + */ - /*! - * ignore - */ +DocumentArrayPath.prototype.applyGetters = function(value, scope) { + return SchemaType.prototype.applyGetters.call(this, value, scope); +}; - EmbeddedDocument.prototype.$ignore = function (path) { - Document.prototype.$ignore.call(this, path); +/*! + * Scopes paths selected in a query to this array. + * Necessary for proper default application of subdocument values. + * + * @param {DocumentArrayPath} array - the array to scope `fields` paths + * @param {Object|undefined} fields - the root fields selected in the query + * @param {Boolean|undefined} init - if we are being created part of a query result + */ - if (!this[documentArrayParent]) { - return; - } +function scopePaths(array, fields, init) { + if (!(init && fields)) { + return undefined; + } - const index = this.__index; - if (typeof index !== "undefined") { - const parentPath = this.__parentArray.$path(); - const fullPath = [parentPath, index, path].join("."); - this[documentArrayParent].$ignore(fullPath); - } - }; + const path = array.path + '.'; + const keys = Object.keys(fields); + let i = keys.length; + const selected = {}; + let hasKeys; + let key; + let sub; + + while (i--) { + key = keys[i]; + if (key.startsWith(path)) { + sub = key.substring(path.length); + if (sub === '$') { + continue; + } + if (sub.startsWith('$.')) { + sub = sub.substr(2); + } + hasKeys || (hasKeys = true); + selected[sub] = fields[key]; + } + } - /** - * Checks if a path is invalid - * - * @param {String} path the field to check - * @api private - * @method $isValid - * @receiver EmbeddedDocument - */ - - EmbeddedDocument.prototype.$isValid = function (path) { - const index = this.__index; - if (typeof index !== "undefined" && this[documentArrayParent]) { - return ( - !this[documentArrayParent].$__.validationError || - !this[documentArrayParent].$__.validationError.errors[ - this.$__fullPath(path) - ] - ); - } + return hasKeys && selected || undefined; +} - return true; - }; +/** + * Sets a default option for all DocumentArray instances. + * + * ####Example: + * + * // Make all numbers have option `min` equal to 0. + * mongoose.Schema.DocumentArray.set('_id', false); + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ - /** - * Returns the top level document of this sub-document. - * - * @return {Document} - */ +DocumentArrayPath.defaultOptions = {}; - EmbeddedDocument.prototype.ownerDocument = function () { - if (this.$__.ownerDocument) { - return this.$__.ownerDocument; - } +DocumentArrayPath.set = SchemaType.set; + +/*! + * Module exports. + */ + +module.exports = DocumentArrayPath; + + +/***/ }), + +/***/ 2987: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; - let parent = this[documentArrayParent]; - if (!parent) { - return this; - } +/*! + * Module exports. + */ - while (parent[documentArrayParent] || parent.$__parent) { - parent = parent[documentArrayParent] || parent.$__parent; - } - this.$__.ownerDocument = parent; - return this.$__.ownerDocument; - }; - /** - * Returns the full path to this document. If optional `path` is passed, it is appended to the full path. - * - * @param {String} [path] - * @return {String} - * @api private - * @method $__fullPath - * @memberOf EmbeddedDocument - * @instance - */ - - EmbeddedDocument.prototype.$__fullPath = function (path) { - if (!this.$__.fullPath) { - let parent = this; - if (!parent[documentArrayParent]) { - return path; - } +exports.String = __nccwpck_require__(7451); - const paths = []; - while (parent[documentArrayParent] || parent.$__parent) { - if (parent[documentArrayParent]) { - paths.unshift(parent.__parentArray.$path()); - } else { - paths.unshift(parent.$basePath); - } - parent = parent[documentArrayParent] || parent.$__parent; - } +exports.Number = __nccwpck_require__(188); - this.$__.fullPath = paths.join("."); +exports.Boolean = __nccwpck_require__(2900); - if (!this.$__.ownerDocument) { - // optimization - this.$__.ownerDocument = parent; - } - } +exports.DocumentArray = __nccwpck_require__(182); - return path ? this.$__.fullPath + "." + path : this.$__.fullPath; - }; +exports.Subdocument = __nccwpck_require__(2697); - /** - * Returns this sub-documents parent document. - * - * @api public - */ +exports.Array = __nccwpck_require__(6090); - EmbeddedDocument.prototype.parent = function () { - return this[documentArrayParent]; - }; +exports.Buffer = __nccwpck_require__(4798); - /** - * Returns this sub-documents parent document. - * - * @api public - */ +exports.Date = __nccwpck_require__(9140); - EmbeddedDocument.prototype.$parent = EmbeddedDocument.prototype.parent; +exports.ObjectId = __nccwpck_require__(9259); - /** - * Returns this sub-documents parent array. - * - * @api public - */ +exports.Mixed = __nccwpck_require__(7495); - EmbeddedDocument.prototype.parentArray = function () { - return this.__parentArray; - }; +exports.Decimal128 = exports.Decimal = __nccwpck_require__(8940); - /*! - * Module exports. - */ +exports.Map = __nccwpck_require__(2370); - module.exports = EmbeddedDocument; +// alias - /***/ - }, +exports.Oid = exports.ObjectId; +exports.Object = exports.Mixed; +exports.Bool = exports.Boolean; +exports.ObjectID = exports.ObjectId; - /***/ 3000: /***/ ( - __unused_webpack_module, - exports, - __nccwpck_require__ - ) => { - "use strict"; - /*! - * Module exports. - */ +/***/ }), - exports.Array = __nccwpck_require__(6628); - exports.Buffer = __nccwpck_require__(5505); +/***/ 2370: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - exports.Document = exports.Embedded = __nccwpck_require__(4433); // @deprecate +"use strict"; - exports.DocumentArray = __nccwpck_require__(55); - exports.Decimal128 = __nccwpck_require__(8319); - exports.ObjectId = __nccwpck_require__(2706); - exports.Map = __nccwpck_require__(9390); +/*! + * ignore + */ - exports.Subdocument = __nccwpck_require__(7302); +const MongooseMap = __nccwpck_require__(9390); +const SchemaMapOptions = __nccwpck_require__(2809); +const SchemaType = __nccwpck_require__(5660); +/*! + * ignore + */ - /***/ - }, +class Map extends SchemaType { + constructor(key, options) { + super(key, options, 'Map'); + this.$isSchemaMap = true; + } - /***/ 9390: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Mixed = __nccwpck_require__(7495); - const ObjectId = __nccwpck_require__(2706); - const clone = __nccwpck_require__(5092); - const deepEqual = __nccwpck_require__(9232).deepEqual; - const get = __nccwpck_require__(8730); - const getConstructorName = __nccwpck_require__(7323); - const handleSpreadDoc = __nccwpck_require__(5232); - const util = __nccwpck_require__(1669); - const specialProperties = __nccwpck_require__(6786); - - const populateModelSymbol = __nccwpck_require__(3240).populateModelSymbol; - - /*! - * ignore - */ - - class MongooseMap extends Map { - constructor(v, path, doc, schemaType) { - if (getConstructorName(v) === "Object") { - v = Object.keys(v).reduce( - (arr, key) => arr.concat([[key, v[key]]]), - [] - ); - } - super(v); - this.$__parent = doc != null && doc.$__ != null ? doc : null; - this.$__path = path; - this.$__schemaType = - schemaType == null ? new Mixed(path) : schemaType; + set(option, value) { + return SchemaType.set(option, value); + } - this.$__runDeferred(); - } + cast(val, doc, init) { + if (val instanceof MongooseMap) { + return val; + } - $init(key, value) { - checkValidKey(key); + const path = this.path; - super.set(key, value); + if (init) { + const map = new MongooseMap({}, path, doc, this.$__schemaType); - if (value != null && value.$isSingleNested) { - value.$basePath = this.$__path + "." + key; + if (val instanceof global.Map) { + for (const key of val.keys()) { + let _val = val.get(key); + if (_val == null) { + _val = map.$__schemaType._castNullish(_val); + } else { + _val = map.$__schemaType.cast(_val, doc, true, null, { path: path + '.' + key }); } + map.$init(key, _val); } - - $__set(key, value) { - super.set(key, value); + } else { + for (const key of Object.keys(val)) { + let _val = val[key]; + if (_val == null) { + _val = map.$__schemaType._castNullish(_val); + } else { + _val = map.$__schemaType.cast(_val, doc, true, null, { path: path + '.' + key }); + } + map.$init(key, _val); } + } - get(key, options) { - if (key instanceof ObjectId) { - key = key.toString(); - } + return map; + } - options = options || {}; - if (options.getters === false) { - return super.get(key); - } - return this.$__schemaType.applyGetters( - super.get(key), - this.$__parent - ); - } + return new MongooseMap(val, path, doc, this.$__schemaType); + } - set(key, value) { - if (key instanceof ObjectId) { - key = key.toString(); - } + clone() { + const schematype = super.clone(); - checkValidKey(key); - value = handleSpreadDoc(value); + if (this.$__schemaType != null) { + schematype.$__schemaType = this.$__schemaType.clone(); + } + return schematype; + } +} - // Weird, but because you can't assign to `this` before calling `super()` - // you can't get access to `$__schemaType` to cast in the initial call to - // `set()` from the `super()` constructor. +Map.prototype.OptionsConstructor = SchemaMapOptions; - if (this.$__schemaType == null) { - this.$__deferred = this.$__deferred || []; - this.$__deferred.push({ key: key, value: value }); - return; - } +Map.defaultOptions = {}; - const fullPath = this.$__path + "." + key; - const populated = - this.$__parent != null && this.$__parent.$__ - ? this.$__parent.populated(fullPath) || - this.$__parent.populated(this.$__path) - : null; - const priorVal = this.get(key); +module.exports = Map; - if (populated != null) { - if (value.$__ == null) { - value = new populated.options[populateModelSymbol](value); - } - value.$__.wasPopulated = true; - } else { - try { - value = this.$__schemaType.applySetters( - value, - this.$__parent, - false, - this.get(key), - { path: fullPath } - ); - } catch (error) { - if (this.$__parent != null && this.$__parent.$__ != null) { - this.$__parent.invalidate(fullPath, error); - return; - } - throw error; - } - } - super.set(key, value); +/***/ }), - if (value != null && value.$isSingleNested) { - value.$basePath = this.$__path + "." + key; - } +/***/ 7495: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const parent = this.$__parent; - if ( - parent != null && - parent.$__ != null && - !deepEqual(value, priorVal) - ) { - parent.markModified(this.$__path + "." + key); - } - } +"use strict"; +/*! + * Module dependencies. + */ - clear() { - super.clear(); - const parent = this.$__parent; - if (parent != null) { - parent.markModified(this.$__path); - } - } - delete(key) { - if (key instanceof ObjectId) { - key = key.toString(); - } - this.set(key, undefined); - super.delete(key); - } +const SchemaType = __nccwpck_require__(5660); +const symbols = __nccwpck_require__(1205); +const isObject = __nccwpck_require__(273); +const utils = __nccwpck_require__(9232); - toBSON() { - return new Map(this); - } +/** + * Mixed SchemaType constructor. + * + * @param {String} path + * @param {Object} options + * @inherits SchemaType + * @api public + */ - toObject(options) { - if (get(options, "flattenMaps")) { - const ret = {}; - const keys = this.keys(); - for (const key of keys) { - ret[key] = clone(this.get(key)); - } - return ret; - } +function Mixed(path, options) { + if (options && options.default) { + const def = options.default; + if (Array.isArray(def) && def.length === 0) { + // make sure empty array defaults are handled + options.default = Array; + } else if (!options.shared && isObject(def) && Object.keys(def).length === 0) { + // prevent odd "shared" objects between documents + options.default = function() { + return {}; + }; + } + } - return new Map(this); - } + SchemaType.call(this, path, options, 'Mixed'); - toJSON() { - const ret = {}; - const keys = this.keys(); - for (const key of keys) { - ret[key] = this.get(key); - } - return ret; - } + this[symbols.schemaMixedSymbol] = true; +} - inspect() { - return new Map(this); - } +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +Mixed.schemaName = 'Mixed'; - $__runDeferred() { - if (!this.$__deferred) { - return; - } +Mixed.defaultOptions = {}; - for (const keyValueObject of this.$__deferred) { - this.set(keyValueObject.key, keyValueObject.value); - } +/*! + * Inherits from SchemaType. + */ +Mixed.prototype = Object.create(SchemaType.prototype); +Mixed.prototype.constructor = Mixed; - this.$__deferred = null; - } - } +/** + * Attaches a getter for all Mixed paths. + * + * ####Example: + * + * // Hide the 'hidden' path + * mongoose.Schema.Mixed.get(v => Object.assign({}, v, { hidden: null })); + * + * const Model = mongoose.model('Test', new Schema({ test: {} })); + * new Model({ test: { hidden: 'Secret!' } }).test.hidden; // null + * + * @param {Function} getter + * @return {this} + * @function get + * @static + * @api public + */ - if (util.inspect.custom) { - Object.defineProperty(MongooseMap.prototype, util.inspect.custom, { - enumerable: false, - writable: false, - configurable: false, - value: MongooseMap.prototype.inspect, - }); - } +Mixed.get = SchemaType.get; - Object.defineProperty(MongooseMap.prototype, "$__set", { - enumerable: false, - writable: true, - configurable: false, - }); +/** + * Sets a default option for all Mixed instances. + * + * ####Example: + * + * // Make all mixed instances have `required` of true by default. + * mongoose.Schema.Mixed.set('required', true); + * + * const User = mongoose.model('User', new Schema({ test: mongoose.Mixed })); + * new User({ }).validateSync().errors.test.message; // Path `test` is required. + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ - Object.defineProperty(MongooseMap.prototype, "$__parent", { - enumerable: false, - writable: true, - configurable: false, - }); +Mixed.set = SchemaType.set; - Object.defineProperty(MongooseMap.prototype, "$__path", { - enumerable: false, - writable: true, - configurable: false, - }); +/** + * Casts `val` for Mixed. + * + * _this is a no-op_ + * + * @param {Object} value to cast + * @api private + */ - Object.defineProperty(MongooseMap.prototype, "$__schemaType", { - enumerable: false, - writable: true, - configurable: false, - }); +Mixed.prototype.cast = function(val) { + if (val instanceof Error) { + return utils.errorToPOJO(val); + } + return val; +}; - Object.defineProperty(MongooseMap.prototype, "$isMongooseMap", { - enumerable: false, - writable: false, - configurable: false, - value: true, - }); +/** + * Casts contents for queries. + * + * @param {String} $cond + * @param {any} [val] + * @api private + */ - Object.defineProperty(MongooseMap.prototype, "$__deferredCalls", { - enumerable: false, - writable: false, - configurable: false, - value: true, - }); +Mixed.prototype.castForQuery = function($cond, val) { + if (arguments.length === 2) { + return val; + } + return $cond; +}; - /*! - * Since maps are stored as objects under the hood, keys must be strings - * and can't contain any invalid characters - */ +/*! + * Module exports. + */ - function checkValidKey(key) { - const keyType = typeof key; - if (keyType !== "string") { - throw new TypeError( - `Mongoose maps only support string keys, got ${keyType}` - ); - } - if (key.startsWith("$")) { - throw new Error( - `Mongoose maps do not support keys that start with "$", got "${key}"` - ); - } - if (key.includes(".")) { - throw new Error( - `Mongoose maps do not support keys that contain ".", got "${key}"` - ); - } - if (specialProperties.has(key)) { - throw new Error( - `Mongoose maps do not support reserved key name "${key}"` - ); - } - } +module.exports = Mixed; - module.exports = MongooseMap; - /***/ - }, +/***/ }), - /***/ 2706: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - /** - * ObjectId type constructor - * - * ####Example - * - * const id = new mongoose.Types.ObjectId; - * - * @constructor ObjectId - */ - - const ObjectId = __nccwpck_require__(2324).get().ObjectId; - const objectIdSymbol = __nccwpck_require__(3240).objectIdSymbol; - - /*! - * Getter for convenience with populate, see gh-6115 - */ - - Object.defineProperty(ObjectId.prototype, "_id", { - enumerable: false, - configurable: true, - get: function () { - return this; - }, - }); +/***/ 188: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - ObjectId.prototype[objectIdSymbol] = true; +"use strict"; - module.exports = ObjectId; - /***/ - }, +/*! + * Module requirements. + */ - /***/ 7302: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Document = __nccwpck_require__(6717); - const immediate = __nccwpck_require__(4830); - const internalToObjectOptions = - __nccwpck_require__(5684) /* .internalToObjectOptions */.h; - const promiseOrCallback = __nccwpck_require__(4046); - - const documentArrayParent = __nccwpck_require__(3240).documentArrayParent; - - module.exports = Subdocument; - - /** - * Subdocument constructor. - * - * @inherits Document - * @api private - */ - - function Subdocument(value, fields, parent, skipId, options) { - this.$isSingleNested = true; - if (options != null && options.path != null) { - this.$basePath = options.path; - } - const hasPriorDoc = options != null && options.priorDoc; - let initedPaths = null; - if (hasPriorDoc) { - this._doc = Object.assign({}, options.priorDoc._doc); - delete this._doc[this.$__schema.options.discriminatorKey]; - initedPaths = Object.keys(options.priorDoc._doc || {}).filter( - (key) => key !== this.$__schema.options.discriminatorKey - ); - } - if (parent != null) { - // If setting a nested path, should copy isNew from parent re: gh-7048 - options = Object.assign({}, options, { - isNew: parent.isNew, - defaults: parent.$__.$options.defaults, - }); - } - Document.call(this, value, fields, skipId, options); - - if (hasPriorDoc) { - for (const key of initedPaths) { - if ( - !this.$__.activePaths.states.modify[key] && - !this.$__.activePaths.states.default[key] && - !this.$__.$setCalled.has(key) - ) { - const schematype = this.$__schema.path(key); - const def = - schematype == null ? void 0 : schematype.getDefault(this); - if (def === void 0) { - delete this._doc[key]; - } else { - this._doc[key] = def; - this.$__.activePaths.default(key); - } - } - } +const MongooseError = __nccwpck_require__(4327); +const SchemaNumberOptions = __nccwpck_require__(1079); +const SchemaType = __nccwpck_require__(5660); +const castNumber = __nccwpck_require__(1582); +const handleBitwiseOperator = __nccwpck_require__(9547); +const utils = __nccwpck_require__(9232); - delete options.priorDoc; - delete this.$__.$options.priorDoc; - } - } +const CastError = SchemaType.CastError; - Subdocument.prototype = Object.create(Document.prototype); +/** + * Number SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ - Subdocument.prototype.toBSON = function () { - return this.toObject(internalToObjectOptions); - }; +function SchemaNumber(key, options) { + SchemaType.call(this, key, options, 'Number'); +} - /** - * Used as a stub for middleware - * - * ####NOTE: - * - * _This is a no-op. Does not actually save the doc to the db._ - * - * @param {Function} [fn] - * @return {Promise} resolved Promise - * @api private - */ - - Subdocument.prototype.save = function (options, fn) { - if (typeof options === "function") { - fn = options; - options = {}; - } - options = options || {}; +/** + * Attaches a getter for all Number instances. + * + * ####Example: + * + * // Make all numbers round down + * mongoose.Number.get(function(v) { return Math.floor(v); }); + * + * const Model = mongoose.model('Test', new Schema({ test: Number })); + * new Model({ test: 3.14 }).test; // 3 + * + * @param {Function} getter + * @return {this} + * @function get + * @static + * @api public + */ - if (!options.suppressWarning) { - console.warn( - "mongoose: calling `save()` on a subdoc does **not** save " + - "the document to MongoDB, it only runs save middleware. " + - "Use `subdoc.save({ suppressWarning: true })` to hide this warning " + - "if you're sure this behavior is right for your app." - ); - } +SchemaNumber.get = SchemaType.get; - return promiseOrCallback(fn, (cb) => { - this.$__save(cb); - }); - }; +/** + * Sets a default option for all Number instances. + * + * ####Example: + * + * // Make all numbers have option `min` equal to 0. + * mongoose.Schema.Number.set('min', 0); + * + * const Order = mongoose.model('Order', new Schema({ amount: Number })); + * new Order({ amount: -10 }).validateSync().errors.amount.message; // Path `amount` must be larger than 0. + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ - /** - * Used as a stub for middleware - * - * ####NOTE: - * - * _This is a no-op. Does not actually save the doc to the db._ - * - * @param {Function} [fn] - * @method $__save - * @api private - */ - - Subdocument.prototype.$__save = function (fn) { - return immediate(() => fn(null, this)); - }; +SchemaNumber.set = SchemaType.set; - Subdocument.prototype.$isValid = function (path) { - if (this.$__parent && this.$basePath) { - return this.$__parent.$isValid([this.$basePath, path].join(".")); - } - return Document.prototype.$isValid.call(this, path); - }; +/*! + * ignore + */ - Subdocument.prototype.markModified = function (path) { - Document.prototype.markModified.call(this, path); +SchemaNumber._cast = castNumber; - if (this.$__parent && this.$basePath) { - if (this.$__parent.isDirectModified(this.$basePath)) { - return; - } - this.$__parent.markModified([this.$basePath, path].join("."), this); - } - }; +/** + * Get/set the function used to cast arbitrary values to numbers. + * + * ####Example: + * + * // Make Mongoose cast empty strings '' to 0 for paths declared as numbers + * const original = mongoose.Number.cast(); + * mongoose.Number.cast(v => { + * if (v === '') { return 0; } + * return original(v); + * }); + * + * // Or disable casting entirely + * mongoose.Number.cast(false); + * + * @param {Function} caster + * @return {Function} + * @function get + * @static + * @api public + */ - Subdocument.prototype.isModified = function (paths, modifiedPaths) { - if (this.$__parent && this.$basePath) { - if (Array.isArray(paths) || typeof paths === "string") { - paths = Array.isArray(paths) ? paths : paths.split(" "); - paths = paths.map((p) => [this.$basePath, p].join(".")); +SchemaNumber.cast = function cast(caster) { + if (arguments.length === 0) { + return this._cast; + } + if (caster === false) { + caster = this._defaultCaster; + } + this._cast = caster; - return this.$__parent.isModified(paths, modifiedPaths); - } + return this._cast; +}; - return this.$__parent.isModified(this.$basePath); - } +/*! + * ignore + */ - return Document.prototype.isModified.call(this, paths, modifiedPaths); - }; +SchemaNumber._defaultCaster = v => { + if (typeof v !== 'number') { + throw new Error(); + } + return v; +}; - /** - * Marks a path as valid, removing existing validation errors. - * - * @param {String} path the field to mark as valid - * @api private - * @method $markValid - * @receiver Subdocument - */ +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaNumber.schemaName = 'Number'; - Subdocument.prototype.$markValid = function (path) { - Document.prototype.$markValid.call(this, path); - if (this.$__parent && this.$basePath) { - this.$__parent.$markValid([this.$basePath, path].join(".")); - } - }; +SchemaNumber.defaultOptions = {}; - /*! - * ignore - */ +/*! + * Inherits from SchemaType. + */ +SchemaNumber.prototype = Object.create(SchemaType.prototype); +SchemaNumber.prototype.constructor = SchemaNumber; +SchemaNumber.prototype.OptionsConstructor = SchemaNumberOptions; - Subdocument.prototype.invalidate = function (path, err, val) { - // Hack: array subdocuments' validationError is equal to the owner doc's, - // so validating an array subdoc gives the top-level doc back. Temporary - // workaround for #5208 so we don't have circular errors. - if (err !== this.ownerDocument().$__.validationError) { - Document.prototype.invalidate.call(this, path, err, val); - } +/*! + * ignore + */ - if (this.$__parent && this.$basePath) { - this.$__parent.invalidate([this.$basePath, path].join("."), err, val); - } else if (err.kind === "cast" || err.name === "CastError") { - throw err; - } +SchemaNumber._checkRequired = v => typeof v === 'number' || v instanceof Number; - return this.ownerDocument().$__.validationError; - }; +/** + * Override the function the required validator uses to check whether a string + * passes the `required` check. + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @static + * @api public + */ - /*! - * ignore - */ +SchemaNumber.checkRequired = SchemaType.checkRequired; - Subdocument.prototype.$ignore = function (path) { - Document.prototype.$ignore.call(this, path); - if (this.$__parent && this.$basePath) { - this.$__parent.$ignore([this.$basePath, path].join(".")); - } - }; +/** + * Check if the given value satisfies a required validator. + * + * @param {Any} value + * @param {Document} doc + * @return {Boolean} + * @api public + */ - /** - * Returns the top level document of this sub-document. - * - * @return {Document} - */ +SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } - Subdocument.prototype.ownerDocument = function () { - if (this.$__.ownerDocument) { - return this.$__.ownerDocument; - } + // `require('util').inherits()` does **not** copy static properties, and + // plugins like mongoose-float use `inherits()` for pre-ES6. + const _checkRequired = typeof this.constructor.checkRequired == 'function' ? + this.constructor.checkRequired() : + SchemaNumber.checkRequired(); - let parent = this.$__parent; - if (!parent) { - return this; - } + return _checkRequired(value); +}; - while (parent.$__parent || parent[documentArrayParent]) { - parent = parent.$__parent || parent[documentArrayParent]; - } +/** + * Sets a minimum number validator. + * + * ####Example: + * + * const s = new Schema({ n: { type: Number, min: 10 }) + * const M = db.model('M', s) + * const m = new M({ n: 9 }) + * m.save(function (err) { + * console.error(err) // validator error + * m.n = 10; + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MIN} token which will be replaced with the invalid value + * const min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; + * const schema = new Schema({ n: { type: Number, min: min }) + * const M = mongoose.model('Measurement', schema); + * const s= new M({ n: 4 }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10). + * }) + * + * @param {Number} value minimum number + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ - this.$__.ownerDocument = parent; - return this.$__.ownerDocument; - }; +SchemaNumber.prototype.min = function(value, message) { + if (this.minValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.minValidator; + }, this); + } + + if (value !== null && value !== undefined) { + let msg = message || MongooseError.messages.Number.min; + msg = msg.replace(/{MIN}/, value); + this.validators.push({ + validator: this.minValidator = function(v) { + return v == null || v >= value; + }, + message: msg, + type: 'min', + min: value + }); + } - /** - * Returns this sub-documents parent document. - * - * @api public - */ + return this; +}; - Subdocument.prototype.parent = function () { - return this.$__parent; - }; +/** + * Sets a maximum number validator. + * + * ####Example: + * + * const s = new Schema({ n: { type: Number, max: 10 }) + * const M = db.model('M', s) + * const m = new M({ n: 11 }) + * m.save(function (err) { + * console.error(err) // validator error + * m.n = 10; + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MAX} token which will be replaced with the invalid value + * const max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; + * const schema = new Schema({ n: { type: Number, max: max }) + * const M = mongoose.model('Measurement', schema); + * const s= new M({ n: 4 }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10). + * }) + * + * @param {Number} maximum number + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ - /** - * Returns this sub-documents parent document. - * - * @api public - */ +SchemaNumber.prototype.max = function(value, message) { + if (this.maxValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.maxValidator; + }, this); + } - Subdocument.prototype.$parent = Subdocument.prototype.parent; + if (value !== null && value !== undefined) { + let msg = message || MongooseError.messages.Number.max; + msg = msg.replace(/{MAX}/, value); + this.validators.push({ + validator: this.maxValidator = function(v) { + return v == null || v <= value; + }, + message: msg, + type: 'max', + max: value + }); + } - /*! - * no-op for hooks - */ + return this; +}; - Subdocument.prototype.$__remove = function (cb) { - return cb(null, this); - }; +/** + * Sets a enum validator + * + * ####Example: + * + * const s = new Schema({ n: { type: Number, enum: [1, 2, 3] }); + * const M = db.model('M', s); + * + * const m = new M({ n: 4 }); + * await m.save(); // throws validation error + * + * m.n = 3; + * await m.save(); // succeeds + * + * @param {Array} values allowed values + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ - /** - * Null-out this subdoc - * - * @param {Object} [options] - * @param {Function} [callback] optional callback for compatibility with Document.prototype.remove - */ +SchemaNumber.prototype.enum = function(values, message) { + if (this.enumValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.enumValidator; + }, this); + } - Subdocument.prototype.remove = function (options, callback) { - if (typeof options === "function") { - callback = options; - options = null; - } - registerRemoveListener(this); - // If removing entire doc, no need to remove subdoc - if (!options || !options.noop) { - this.$__parent.set(this.$basePath, null); - } + if (!Array.isArray(values)) { + const isObjectSyntax = utils.isPOJO(values) && values.values != null; + if (isObjectSyntax) { + message = values.message; + values = values.values; + } else if (typeof values === 'number') { + values = Array.prototype.slice.call(arguments); + message = null; + } - if (typeof callback === "function") { - callback(null); - } - }; + if (utils.isPOJO(values)) { + values = Object.values(values); + } + message = message || MongooseError.messages.Number.enum; + } - /*! - * ignore - */ + message = message == null ? MongooseError.messages.Number.enum : message; - Subdocument.prototype.populate = function () { - throw new Error( - "Mongoose does not support calling populate() on nested " + - 'docs. Instead of `doc.nested.populate("path")`, use ' + - '`doc.populate("nested.path")`' - ); - }; + this.enumValidator = v => v == null || values.indexOf(v) !== -1; + this.validators.push({ + validator: this.enumValidator, + message: message, + type: 'enum', + enumValues: values + }); - /*! - * Registers remove event listeners for triggering - * on subdocuments. - * - * @param {Subdocument} sub - * @api private - */ + return this; +}; - function registerRemoveListener(sub) { - let owner = sub.ownerDocument(); +/** + * Casts to number + * + * @param {Object} value value to cast + * @param {Document} doc document that triggers the casting + * @param {Boolean} init + * @api private + */ - function emitRemove() { - owner.removeListener("save", emitRemove); - owner.removeListener("remove", emitRemove); - sub.emit("remove", sub); - sub.constructor.emit("remove", sub); - owner = sub = null; - } +SchemaNumber.prototype.cast = function(value, doc, init) { + if (SchemaType._isRef(this, value, doc, init)) { + if (typeof value === 'number') { + return value; + } - owner.on("save", emitRemove); - owner.on("remove", emitRemove); - } + if (value == null || utils.isNonBuiltinObject(value)) { + return this._castRef(value, doc, init); + } + } - /***/ - }, + const val = value && typeof value._id !== 'undefined' ? + value._id : // documents + value; + + let castNumber; + if (typeof this._castFunction === 'function') { + castNumber = this._castFunction; + } else if (typeof this.constructor.cast === 'function') { + castNumber = this.constructor.cast(); + } else { + castNumber = SchemaNumber.cast(); + } - /***/ 9232: /***/ ( - __unused_webpack_module, - exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies. - */ - - const ms = __nccwpck_require__(900); - const mpath = __nccwpck_require__(8586); - const sliced = __nccwpck_require__(9889); - const Buffer = __nccwpck_require__(1867).Buffer; - const Decimal = __nccwpck_require__(8319); - const ObjectId = __nccwpck_require__(2706); - const PopulateOptions = __nccwpck_require__(7038); - const clone = __nccwpck_require__(5092); - const immediate = __nccwpck_require__(4830); - const isObject = __nccwpck_require__(273); - const isBsonType = __nccwpck_require__(1238); - const getFunctionName = __nccwpck_require__(6621); - const isMongooseObject = __nccwpck_require__(7104); - const promiseOrCallback = __nccwpck_require__(4046); - const schemaMerge = __nccwpck_require__(2830); - const specialProperties = __nccwpck_require__(6786); - - let Document; - - exports.specialProperties = specialProperties; - - /*! - * Produces a collection name from model `name`. By default, just returns - * the model name - * - * @param {String} name a model name - * @param {Function} pluralize function that pluralizes the collection name - * @return {String} a collection name - * @api private - */ - - exports.toCollectionName = function (name, pluralize) { - if (name === "system.profile") { - return name; - } - if (name === "system.indexes") { - return name; - } - if (typeof pluralize === "function") { - return pluralize(name); - } - return name; - }; + try { + return castNumber(val); + } catch (err) { + throw new CastError('Number', val, this.path, err, this); + } +}; - /*! - * Determines if `a` and `b` are deep equal. - * - * Modified from node/lib/assert.js - * - * @param {any} a a value to compare to `b` - * @param {any} b a value to compare to `a` - * @return {Boolean} - * @api private - */ - - exports.deepEqual = function deepEqual(a, b) { - if (a === b) { - return true; - } +/*! + * ignore + */ - if (typeof a !== "object" && typeof b !== "object") { - return a === b; - } +function handleSingle(val) { + return this.cast(val); +} - if (a instanceof Date && b instanceof Date) { - return a.getTime() === b.getTime(); - } +function handleArray(val) { + const _this = this; + if (!Array.isArray(val)) { + return [this.cast(val)]; + } + return val.map(function(m) { + return _this.cast(m); + }); +} + +SchemaNumber.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $bitsAllClear: handleBitwiseOperator, + $bitsAnyClear: handleBitwiseOperator, + $bitsAllSet: handleBitwiseOperator, + $bitsAnySet: handleBitwiseOperator, + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle, + $mod: handleArray + }); - if ( - (isBsonType(a, "ObjectID") && isBsonType(b, "ObjectID")) || - (isBsonType(a, "Decimal128") && isBsonType(b, "Decimal128")) - ) { - return a.toString() === b.toString(); - } +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ - if (a instanceof RegExp && b instanceof RegExp) { - return ( - a.source === b.source && - a.ignoreCase === b.ignoreCase && - a.multiline === b.multiline && - a.global === b.global - ); - } +SchemaNumber.prototype.castForQuery = function($conditional, val) { + let handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new CastError('number', val, this.path, null, this); + } + return handler.call(this, val); + } + val = this._castForQuery($conditional); + return val; +}; - if (a == null || b == null) { - return false; - } +/*! + * Module exports. + */ - if (a.prototype !== b.prototype) { - return false; - } +module.exports = SchemaNumber; - if (a instanceof Map && b instanceof Map) { - return ( - deepEqual(Array.from(a.keys()), Array.from(b.keys())) && - deepEqual(Array.from(a.values()), Array.from(b.values())) - ); - } - // Handle MongooseNumbers - if (a instanceof Number && b instanceof Number) { - return a.valueOf() === b.valueOf(); - } +/***/ }), - if (Buffer.isBuffer(a)) { - return exports.buffer.areEqual(a, b); - } +/***/ 9259: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (Array.isArray(a) && Array.isArray(b)) { - const len = a.length; - if (len !== b.length) { - return false; - } - for (let i = 0; i < len; ++i) { - if (!deepEqual(a[i], b[i])) { - return false; - } - } - return true; - } +"use strict"; +/*! + * Module dependencies. + */ - if (a.$__ != null) { - a = a._doc; - } else if (isMongooseObject(a)) { - a = a.toObject(); - } - if (b.$__ != null) { - b = b._doc; - } else if (isMongooseObject(b)) { - b = b.toObject(); - } - const ka = Object.keys(a); - const kb = Object.keys(b); - const kaLength = ka.length; +const SchemaObjectIdOptions = __nccwpck_require__(1374); +const SchemaType = __nccwpck_require__(5660); +const castObjectId = __nccwpck_require__(5552); +const getConstructorName = __nccwpck_require__(7323); +const oid = __nccwpck_require__(2706); +const utils = __nccwpck_require__(9232); - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (kaLength !== kb.length) { - return false; - } +const CastError = SchemaType.CastError; +let Document; - // the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); +/** + * ObjectId SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ - // ~~~cheap key test - for (let i = kaLength - 1; i >= 0; i--) { - if (ka[i] !== kb[i]) { - return false; - } - } +function ObjectId(key, options) { + const isKeyHexStr = typeof key === 'string' && key.length === 24 && /^[a-f0-9]+$/i.test(key); + const suppressWarning = options && options.suppressWarning; + if ((isKeyHexStr || typeof key === 'undefined') && !suppressWarning) { + utils.warn('mongoose: To create a new ObjectId please try ' + + '`Mongoose.Types.ObjectId` instead of using ' + + '`Mongoose.Schema.ObjectId`. Set the `suppressWarning` option if ' + + 'you\'re trying to create a hex char path in your schema.'); + } + SchemaType.call(this, key, options, 'ObjectID'); +} - // equivalent values for every corresponding key, and - // ~~~possibly expensive deep test - for (const key of ka) { - if (!deepEqual(a[key], b[key])) { - return false; - } - } +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +ObjectId.schemaName = 'ObjectId'; - return true; - }; +ObjectId.defaultOptions = {}; - /*! - * Get the last element of an array - */ +/*! + * Inherits from SchemaType. + */ +ObjectId.prototype = Object.create(SchemaType.prototype); +ObjectId.prototype.constructor = ObjectId; +ObjectId.prototype.OptionsConstructor = SchemaObjectIdOptions; - exports.last = function (arr) { - if (arr.length > 0) { - return arr[arr.length - 1]; - } - return void 0; - }; +/** + * Attaches a getter for all ObjectId instances + * + * ####Example: + * + * // Always convert to string when getting an ObjectId + * mongoose.ObjectId.get(v => v.toString()); + * + * const Model = mongoose.model('Test', new Schema({})); + * typeof (new Model({})._id); // 'string' + * + * @param {Function} getter + * @return {this} + * @function get + * @static + * @api public + */ - exports.clone = clone; +ObjectId.get = SchemaType.get; - /*! - * ignore - */ +/** + * Sets a default option for all ObjectId instances. + * + * ####Example: + * + * // Make all object ids have option `required` equal to true. + * mongoose.Schema.ObjectId.set('required', true); + * + * const Order = mongoose.model('Order', new Schema({ userId: ObjectId })); + * new Order({ }).validateSync().errors.userId.message; // Path `userId` is required. + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ - exports.promiseOrCallback = promiseOrCallback; +ObjectId.set = SchemaType.set; - /*! - * ignore - */ +/** + * Adds an auto-generated ObjectId default if turnOn is true. + * @param {Boolean} turnOn auto generated ObjectId defaults + * @api public + * @return {SchemaType} this + */ - exports.omit = function omit(obj, keys) { - if (keys == null) { - return Object.assign({}, obj); - } - if (!Array.isArray(keys)) { - keys = [keys]; - } +ObjectId.prototype.auto = function(turnOn) { + if (turnOn) { + this.default(defaultId); + this.set(resetId); + } - const ret = Object.assign({}, obj); - for (const key of keys) { - delete ret[key]; - } - return ret; - }; + return this; +}; - /*! - * Shallow copies defaults into options. - * - * @param {Object} defaults - * @param {Object} options - * @return {Object} the merged object - * @api private - */ +/*! + * ignore + */ - exports.options = function (defaults, options) { - const keys = Object.keys(defaults); - let i = keys.length; - let k; +ObjectId._checkRequired = v => v instanceof oid; - options = options || {}; +/*! + * ignore + */ - while (i--) { - k = keys[i]; - if (!(k in options)) { - options[k] = defaults[k]; - } - } +ObjectId._cast = castObjectId; - return options; - }; +/** + * Get/set the function used to cast arbitrary values to objectids. + * + * ####Example: + * + * // Make Mongoose only try to cast length 24 strings. By default, any 12 + * // char string is a valid ObjectId. + * const original = mongoose.ObjectId.cast(); + * mongoose.ObjectId.cast(v => { + * assert.ok(typeof v !== 'string' || v.length === 24); + * return original(v); + * }); + * + * // Or disable casting entirely + * mongoose.ObjectId.cast(false); + * + * @param {Function} caster + * @return {Function} + * @function get + * @static + * @api public + */ - /*! - * Generates a random string - * - * @api private - */ +ObjectId.cast = function cast(caster) { + if (arguments.length === 0) { + return this._cast; + } + if (caster === false) { + caster = this._defaultCaster; + } + this._cast = caster; - exports.random = function () { - return Math.random().toString().substr(3); - }; + return this._cast; +}; - /*! - * Merges `from` into `to` without overwriting existing properties. - * - * @param {Object} to - * @param {Object} from - * @api private - */ +/*! + * ignore + */ - exports.merge = function merge(to, from, options, path) { - options = options || {}; +ObjectId._defaultCaster = v => { + if (!(v instanceof oid)) { + throw new Error(v + ' is not an instance of ObjectId'); + } + return v; +}; - const keys = Object.keys(from); - let i = 0; - const len = keys.length; - let key; +/** + * Override the function the required validator uses to check whether a string + * passes the `required` check. + * + * ####Example: + * + * // Allow empty strings to pass `required` check + * mongoose.Schema.Types.String.checkRequired(v => v != null); + * + * const M = mongoose.model({ str: { type: String, required: true } }); + * new M({ str: '' }).validateSync(); // `null`, validation passes! + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @static + * @api public + */ - path = path || ""; - const omitNested = options.omitNested || {}; +ObjectId.checkRequired = SchemaType.checkRequired; - while (i < len) { - key = keys[i++]; - if (options.omit && options.omit[key]) { - continue; - } - if (omitNested[path]) { - continue; - } - if (specialProperties.has(key)) { - continue; - } - if (to[key] == null) { - to[key] = from[key]; - } else if (exports.isObject(from[key])) { - if (!exports.isObject(to[key])) { - to[key] = {}; - } - if (from[key] != null) { - // Skip merging schemas if we're creating a discriminator schema and - // base schema has a given path as a single nested but discriminator schema - // has the path as a document array, or vice versa (gh-9534) - if ( - (options.isDiscriminatorSchemaMerge && - from[key].$isSingleNested && - to[key].$isMongooseDocumentArray) || - (from[key].$isMongooseDocumentArray && to[key].$isSingleNested) - ) { - continue; - } else if (from[key].instanceOfSchema) { - if (to[key].instanceOfSchema) { - schemaMerge( - to[key], - from[key].clone(), - options.isDiscriminatorSchemaMerge - ); - } else { - to[key] = from[key].clone(); - } - continue; - } else if (from[key] instanceof ObjectId) { - to[key] = new ObjectId(from[key]); - continue; - } - } - merge(to[key], from[key], options, path ? path + "." + key : key); - } else if (options.overwrite) { - to[key] = from[key]; - } - } - }; +/** + * Check if the given value satisfies a required validator. + * + * @param {Any} value + * @param {Document} doc + * @return {Boolean} + * @api public + */ - /*! - * Applies toObject recursively. - * - * @param {Document|Array|Object} obj - * @return {Object} - * @api private - */ +ObjectId.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } - exports.toObject = function toObject(obj) { - Document || (Document = __nccwpck_require__(6717)); - let ret; + // `require('util').inherits()` does **not** copy static properties, and + // plugins like mongoose-float use `inherits()` for pre-ES6. + const _checkRequired = typeof this.constructor.checkRequired == 'function' ? + this.constructor.checkRequired() : + ObjectId.checkRequired(); - if (obj == null) { - return obj; - } + return _checkRequired(value); +}; - if (obj instanceof Document) { - return obj.toObject(); - } +/** + * Casts to ObjectId + * + * @param {Object} value + * @param {Object} doc + * @param {Boolean} init whether this is an initialization cast + * @api private + */ - if (Array.isArray(obj)) { - ret = []; +ObjectId.prototype.cast = function(value, doc, init) { + if (SchemaType._isRef(this, value, doc, init)) { + // wait! we may need to cast this to a document + if (value instanceof oid) { + return value; + } else if ((getConstructorName(value) || '').toLowerCase() === 'objectid') { + return new oid(value.toHexString()); + } - for (const doc of obj) { - ret.push(toObject(doc)); - } + if (value == null || utils.isNonBuiltinObject(value)) { + return this._castRef(value, doc, init); + } + } - return ret; - } + let castObjectId; + if (typeof this._castFunction === 'function') { + castObjectId = this._castFunction; + } else if (typeof this.constructor.cast === 'function') { + castObjectId = this.constructor.cast(); + } else { + castObjectId = ObjectId.cast(); + } - if (exports.isPOJO(obj)) { - ret = {}; + try { + return castObjectId(value); + } catch (error) { + throw new CastError('ObjectId', value, this.path, error, this); + } +}; - for (const k of Object.keys(obj)) { - if (specialProperties.has(k)) { - continue; - } - ret[k] = toObject(obj[k]); - } +/*! + * ignore + */ - return ret; - } +function handleSingle(val) { + return this.cast(val); +} - return obj; - }; +ObjectId.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle + }); - exports.isObject = isObject; - - /*! - * Determines if `arg` is a plain old JavaScript object (POJO). Specifically, - * `arg` must be an object but not an instance of any special class, like String, - * ObjectId, etc. - * - * `Object.getPrototypeOf()` is part of ES5: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf - * - * @param {Object|Array|String|Function|RegExp|any} arg - * @api private - * @return {Boolean} - */ - - exports.isPOJO = function isPOJO(arg) { - if (arg == null || typeof arg !== "object") { - return false; - } - const proto = Object.getPrototypeOf(arg); - // Prototype may be null if you used `Object.create(null)` - // Checking `proto`'s constructor is safe because `getPrototypeOf()` - // explicitly crosses the boundary from object data to object metadata - return !proto || proto.constructor.name === "Object"; - }; +/*! + * ignore + */ - /*! - * Determines if `obj` is a built-in object like an array, date, boolean, - * etc. - */ - - exports.isNativeObject = function (arg) { - return ( - Array.isArray(arg) || - arg instanceof Date || - arg instanceof Boolean || - arg instanceof Number || - arg instanceof String - ); - }; +function defaultId() { + return new oid(); +} - /*! - * Determines if `val` is an object that has no own keys - */ +defaultId.$runBeforeSetters = true; - exports.isEmptyObject = function (val) { - return ( - val != null && - typeof val === "object" && - Object.keys(val).length === 0 - ); - }; +function resetId(v) { + Document || (Document = __nccwpck_require__(6717)); - /*! - * Search if `obj` or any POJOs nested underneath `obj` has a property named - * `key` - */ + if (this instanceof Document) { + if (v === void 0) { + const _v = new oid; + this.$__._id = _v; + return _v; + } - exports.hasKey = function hasKey(obj, key) { - const props = Object.keys(obj); - for (const prop of props) { - if (prop === key) { - return true; - } - if (exports.isPOJO(obj[prop]) && exports.hasKey(obj[prop], key)) { - return true; - } - } - return false; - }; + this.$__._id = v; + } - /*! - * A faster Array.prototype.slice.call(arguments) alternative - * @api private - */ - - exports.args = sliced; - - /*! - * process.nextTick helper. - * - * Wraps `callback` in a try/catch + nextTick. - * - * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback. - * - * @param {Function} callback - * @api private - */ - - exports.tick = function tick(callback) { - if (typeof callback !== "function") { - return; - } - return function () { - try { - callback.apply(this, arguments); - } catch (err) { - // only nextTick on err to get out of - // the event loop and avoid state corruption. - immediate(function () { - throw err; - }); - } - }; - }; + return v; +} - /*! - * Returns true if `v` is an object that can be serialized as a primitive in - * MongoDB - */ +/*! + * Module exports. + */ - exports.isMongooseType = function (v) { - return ( - v instanceof ObjectId || v instanceof Decimal || v instanceof Buffer - ); - }; +module.exports = ObjectId; - exports.isMongooseObject = isMongooseObject; - /*! - * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB. - * - * @param {Object} object - * @api private - */ +/***/ }), - exports.expires = function expires(object) { - if (!(object && object.constructor.name === "Object")) { - return; - } - if (!("expires" in object)) { - return; - } +/***/ 9547: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - let when; - if (typeof object.expires !== "string") { - when = object.expires; - } else { - when = Math.round(ms(object.expires) / 1000); - } - object.expireAfterSeconds = when; - delete object.expires; - }; +"use strict"; +/*! + * Module requirements. + */ - /*! - * populate helper - */ - - exports.populate = function populate( - path, - select, - model, - match, - options, - subPopulate, - justOne, - count - ) { - // might have passed an object specifying all arguments - let obj = null; - if (arguments.length === 1) { - if (path instanceof PopulateOptions) { - return [path]; - } - if (Array.isArray(path)) { - const singles = makeSingles(path); - return singles.map((o) => exports.populate(o)[0]); - } - if (exports.isObject(path)) { - obj = Object.assign({}, path); - } else { - obj = { path: path }; - } - } else if (typeof model === "object") { - obj = { - path: path, - select: select, - match: model, - options: match, - }; - } else { - obj = { - path: path, - select: select, - model: model, - match: match, - options: options, - populate: subPopulate, - justOne: justOne, - count: count, - }; - } +const CastError = __nccwpck_require__(2798); - if (typeof obj.path !== "string") { - throw new TypeError( - "utils.populate: invalid path. Expected string. Got typeof `" + - typeof path + - "`" - ); - } +/*! + * ignore + */ - return _populateObj(obj); - - // The order of select/conditions args is opposite Model.find but - // necessary to keep backward compatibility (select could be - // an array, string, or object literal). - function makeSingles(arr) { - const ret = []; - arr.forEach(function (obj) { - if (/[\s]/.test(obj.path)) { - const paths = obj.path.split(" "); - paths.forEach(function (p) { - const copy = Object.assign({}, obj); - copy.path = p; - ret.push(copy); - }); - } else { - ret.push(obj); - } - }); +function handleBitwiseOperator(val) { + const _this = this; + if (Array.isArray(val)) { + return val.map(function(v) { + return _castNumber(_this.path, v); + }); + } else if (Buffer.isBuffer(val)) { + return val; + } + // Assume trying to cast to number + return _castNumber(_this.path, val); +} - return ret; - } - }; +/*! + * ignore + */ - function _populateObj(obj) { - if (Array.isArray(obj.populate)) { - const ret = []; - obj.populate.forEach(function (obj) { - if (/[\s]/.test(obj.path)) { - const copy = Object.assign({}, obj); - const paths = copy.path.split(" "); - paths.forEach(function (p) { - copy.path = p; - ret.push(exports.populate(copy)[0]); - }); - } else { - ret.push(exports.populate(obj)[0]); - } - }); - obj.populate = exports.populate(ret); - } else if (obj.populate != null && typeof obj.populate === "object") { - obj.populate = exports.populate(obj.populate); - } +function _castNumber(path, num) { + const v = Number(num); + if (isNaN(v)) { + throw new CastError('number', num, path); + } + return v; +} - const ret = []; - const paths = obj.path.split(" "); - if (obj.options != null) { - obj.options = exports.clone(obj.options); - } +module.exports = handleBitwiseOperator; - for (const path of paths) { - ret.push(new PopulateOptions(Object.assign({}, obj, { path: path }))); - } - return ret; - } +/***/ }), - /*! - * Return the value of `obj` at the given `path`. - * - * @param {String} path - * @param {Object} obj - */ +/***/ 1426: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - exports.getValue = function (path, obj, map) { - return mpath.get(path, obj, "_doc", map); - }; +"use strict"; - /*! - * Sets the value of `obj` at the given `path`. - * - * @param {String} path - * @param {Anything} val - * @param {Object} obj - */ - exports.setValue = function (path, val, obj, map, _copying) { - mpath.set(path, val, obj, "_doc", map, _copying); - }; +const castBoolean = __nccwpck_require__(66); - /*! - * Returns an array of values from object `o`. - * - * @param {Object} o - * @return {Array} - * @private - */ +/*! + * ignore + */ - exports.object = {}; - exports.object.vals = function vals(o) { - const keys = Object.keys(o); - let i = keys.length; - const ret = []; +module.exports = function(val) { + const path = this != null ? this.path : null; + return castBoolean(val, path); +}; - while (i--) { - ret.push(o[keys[i]]); - } - return ret; - }; +/***/ }), - /*! - * @see exports.options - */ +/***/ 5061: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - exports.object.shallowCopy = exports.options; +"use strict"; +/*! + * Module requirements. + */ - /*! - * Safer helper for hasOwnProperty checks - * - * @param {Object} obj - * @param {String} prop - */ - const hop = Object.prototype.hasOwnProperty; - exports.object.hasOwnProperty = function (obj, prop) { - return hop.call(obj, prop); - }; - /*! - * Determine if `val` is null or undefined - * - * @return {Boolean} - */ +const castArraysOfNumbers = __nccwpck_require__(9446)/* .castArraysOfNumbers */ .i; +const castToNumber = __nccwpck_require__(9446)/* .castToNumber */ .W; - exports.isNullOrUndefined = function (val) { - return val === null || val === undefined; - }; +/*! + * ignore + */ - /*! - * ignore - */ - - exports.array = {}; - - /*! - * Flattens an array. - * - * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4] - * - * @param {Array} arr - * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsy value, the item will not be included in the results. - * @return {Array} - * @private - */ - - exports.array.flatten = function flatten(arr, filter, ret) { - ret || (ret = []); - - arr.forEach(function (item) { - if (Array.isArray(item)) { - flatten(item, filter, ret); - } else { - if (!filter || filter(item)) { - ret.push(item); - } - } - }); +exports.cast$geoIntersects = cast$geoIntersects; +exports.cast$near = cast$near; +exports.cast$within = cast$within; - return ret; - }; +function cast$near(val) { + const SchemaArray = __nccwpck_require__(6090); - /*! - * ignore - */ + if (Array.isArray(val)) { + castArraysOfNumbers(val, this); + return val; + } - const _hasOwnProperty = Object.prototype.hasOwnProperty; + _castMinMaxDistance(this, val); - exports.hasUserDefinedProperty = function (obj, key) { - if (obj == null) { - return false; - } + if (val && val.$geometry) { + return cast$geometry(val, this); + } - if (Array.isArray(key)) { - for (const k of key) { - if (exports.hasUserDefinedProperty(obj, k)) { - return true; - } - } - return false; - } + if (!Array.isArray(val)) { + throw new TypeError('$near must be either an array or an object ' + + 'with a $geometry property'); + } - if (_hasOwnProperty.call(obj, key)) { - return true; - } - if (typeof obj === "object" && key in obj) { - const v = obj[key]; - return v !== Object.prototype[key] && v !== Array.prototype[key]; - } + return SchemaArray.prototype.castForQuery.call(this, val); +} + +function cast$geometry(val, self) { + switch (val.$geometry.type) { + case 'Polygon': + case 'LineString': + case 'Point': + castArraysOfNumbers(val.$geometry.coordinates, self); + break; + default: + // ignore unknowns + break; + } - return false; - }; + _castMinMaxDistance(self, val); - /*! - * ignore - */ + return val; +} - const MAX_ARRAY_INDEX = Math.pow(2, 32) - 1; +function cast$within(val) { + _castMinMaxDistance(this, val); - exports.isArrayIndex = function (val) { - if (typeof val === "number") { - return val >= 0 && val <= MAX_ARRAY_INDEX; - } - if (typeof val === "string") { - if (!/^\d+$/.test(val)) { - return false; - } - val = +val; - return val >= 0 && val <= MAX_ARRAY_INDEX; - } + if (val.$box || val.$polygon) { + const type = val.$box ? '$box' : '$polygon'; + val[type].forEach(arr => { + if (!Array.isArray(arr)) { + const msg = 'Invalid $within $box argument. ' + + 'Expected an array, received ' + arr; + throw new TypeError(msg); + } + arr.forEach((v, i) => { + arr[i] = castToNumber.call(this, v); + }); + }); + } else if (val.$center || val.$centerSphere) { + const type = val.$center ? '$center' : '$centerSphere'; + val[type].forEach((item, i) => { + if (Array.isArray(item)) { + item.forEach((v, j) => { + item[j] = castToNumber.call(this, v); + }); + } else { + val[type][i] = castToNumber.call(this, item); + } + }); + } else if (val.$geometry) { + cast$geometry(val, this); + } - return false; - }; + return val; +} - /*! - * Removes duplicate values from an array - * - * [1, 2, 3, 3, 5] => [1, 2, 3, 5] - * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ] - * => [ObjectId("550988ba0c19d57f697dc45e")] - * - * @param {Array} arr - * @return {Array} - * @private - */ - - exports.array.unique = function (arr) { - const primitives = new Set(); - const ids = new Set(); - const ret = []; - - for (const item of arr) { - if ( - typeof item === "number" || - typeof item === "string" || - item == null - ) { - if (primitives.has(item)) { - continue; - } - ret.push(item); - primitives.add(item); - } else if (item instanceof ObjectId) { - if (ids.has(item.toString())) { - continue; - } - ret.push(item); - ids.add(item.toString()); - } else { - ret.push(item); - } - } +function cast$geoIntersects(val) { + const geo = val.$geometry; + if (!geo) { + return; + } - return ret; - }; + cast$geometry(val, this); + return val; +} - /*! - * Determines if two buffers are equal. - * - * @param {Buffer} a - * @param {Object} b - */ +function _castMinMaxDistance(self, val) { + if (val.$maxDistance) { + val.$maxDistance = castToNumber.call(self, val.$maxDistance); + } + if (val.$minDistance) { + val.$minDistance = castToNumber.call(self, val.$minDistance); + } +} - exports.buffer = {}; - exports.buffer.areEqual = function (a, b) { - if (!Buffer.isBuffer(a)) { - return false; - } - if (!Buffer.isBuffer(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (let i = 0, len = a.length; i < len; ++i) { - if (a[i] !== b[i]) { - return false; - } - } - return true; - }; - exports.getFunctionName = getFunctionName; - /*! - * Decorate buffers - */ +/***/ }), - exports.decorate = function (destination, source) { - for (const key in source) { - if (specialProperties.has(key)) { - continue; - } - destination[key] = source[key]; - } - }; +/***/ 9446: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * merges to with a copy of from - * - * @param {Object} to - * @param {Object} fromObj - * @api private - */ - - exports.mergeClone = function (to, fromObj) { - if (isMongooseObject(fromObj)) { - fromObj = fromObj.toObject({ - transform: false, - virtuals: false, - depopulate: true, - getters: false, - flattenDecimals: false, - }); - } - const keys = Object.keys(fromObj); - const len = keys.length; - let i = 0; - let key; +"use strict"; - while (i < len) { - key = keys[i++]; - if (specialProperties.has(key)) { - continue; - } - if (typeof to[key] === "undefined") { - to[key] = exports.clone(fromObj[key], { - transform: false, - virtuals: false, - depopulate: true, - getters: false, - flattenDecimals: false, - }); - } else { - let val = fromObj[key]; - if (val != null && val.valueOf && !(val instanceof Date)) { - val = val.valueOf(); - } - if (exports.isObject(val)) { - let obj = val; - if (isMongooseObject(val) && !val.isMongooseBuffer) { - obj = obj.toObject({ - transform: false, - virtuals: false, - depopulate: true, - getters: false, - flattenDecimals: false, - }); - } - if (val.isMongooseBuffer) { - obj = Buffer.from(obj); - } - exports.mergeClone(to[key], obj); - } else { - to[key] = exports.clone(val, { - flattenDecimals: false, - }); - } - } - } - }; - /** - * Executes a function on each element of an array (like _.each) - * - * @param {Array} arr - * @param {Function} fn - * @api private - */ +/*! + * Module requirements. + */ - exports.each = function (arr, fn) { - for (const item of arr) { - fn(item); - } - }; +const SchemaNumber = __nccwpck_require__(188); - /*! - * ignore - */ +/*! + * @ignore + */ - exports.getOption = function (name) { - const sources = Array.prototype.slice.call(arguments, 1); +exports.W = castToNumber; +exports.i = castArraysOfNumbers; - for (const source of sources) { - if (source[name] != null) { - return source[name]; - } - } +/*! + * @ignore + */ - return null; - }; +function castToNumber(val) { + return SchemaNumber.cast()(val); +} - /*! - * ignore - */ +function castArraysOfNumbers(arr, self) { + arr.forEach(function(v, i) { + if (Array.isArray(v)) { + castArraysOfNumbers(v, self); + } else { + arr[i] = castToNumber.call(self, v); + } + }); +} - exports.noop = function () {}; - exports.errorToPOJO = function errorToPOJO(error) { - const isError = error instanceof Error; - if (!isError) { - throw new Error("`error` must be `instanceof Error`."); - } +/***/ }), - const ret = {}; - for (const properyName of Object.getOwnPropertyNames(error)) { - ret[properyName] = error[properyName]; - } - return ret; - }; +/***/ 8807: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /***/ - }, +"use strict"; - /***/ 481: /***/ (module) => { - "use strict"; - - /*! - * Valid mongoose options - */ - - const VALID_OPTIONS = Object.freeze([ - "applyPluginsToChildSchemas", - "applyPluginsToDiscriminators", - "autoCreate", - "autoIndex", - "bufferCommands", - "bufferTimeoutMS", - "cloneSchemas", - "debug", - "maxTimeMS", - "objectIdGetter", - "overwriteModels", - "returnOriginal", - "runValidators", - "sanitizeProjection", - "selectPopulatedPaths", - "setDefaultsOnInsert", - "strict", - "strictQuery", - "toJSON", - "toObject", - "typePojoToMixed", - "useCreateIndex", - "useFindAndModify", - "useNewUrlParser", - "usePushEach", - "useUnifiedTopology", - ]); - - module.exports = VALID_OPTIONS; - - /***/ - }, - /***/ 1423: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const utils = __nccwpck_require__(9232); - - /** - * VirtualType constructor - * - * This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`. - * - * ####Example: - * - * const fullname = schema.virtual('fullname'); - * fullname instanceof mongoose.VirtualType // true - * - * @param {Object} options - * @param {string|function} [options.ref] if `ref` is not nullish, this becomes a [populated virtual](/docs/populate.html#populate-virtuals) - * @param {string|function} [options.localField] the local field to populate on if this is a populated virtual. - * @param {string|function} [options.foreignField] the foreign field to populate on if this is a populated virtual. - * @param {boolean} [options.justOne=false] by default, a populated virtual is an array. If you set `justOne`, the populated virtual will be a single doc or `null`. - * @param {boolean} [options.getters=false] if you set this to `true`, Mongoose will call any custom getters you defined on this virtual - * @param {boolean} [options.count=false] if you set this to `true`, `populate()` will set this virtual to the number of populated documents, as opposed to the documents themselves, using [`Query#countDocuments()`](./api.html#query_Query-countDocuments) - * @param {Object|Function} [options.match=null] add an extra match condition to `populate()` - * @param {Number} [options.limit=null] add a default `limit` to the `populate()` query - * @param {Number} [options.skip=null] add a default `skip` to the `populate()` query - * @param {Number} [options.perDocumentLimit=null] For legacy reasons, `limit` with `populate()` may give incorrect results because it only executes a single query for every document being populated. If you set `perDocumentLimit`, Mongoose will ensure correct `limit` per document by executing a separate query for each document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })` will execute 2 additional queries if `.find()` returns 2 documents. - * @param {Object} [options.options=null] Additional options like `limit` and `lean`. - * @api public - */ - - function VirtualType(options, name) { - this.path = name; - this.getters = []; - this.setters = []; - this.options = Object.assign({}, options); - } - - /** - * If no getters/getters, add a default - * - * @param {Function} fn - * @return {VirtualType} this - * @api private - */ - - VirtualType.prototype._applyDefaultGetters = function () { - if (this.getters.length > 0 || this.setters.length > 0) { - return; - } +const CastError = __nccwpck_require__(2798); +const castBoolean = __nccwpck_require__(66); +const castString = __nccwpck_require__(1318); - const path = this.path; - const internalProperty = "$" + path; - this.getters.push(function () { - return this[internalProperty]; - }); - this.setters.push(function (v) { - this[internalProperty] = v; - }); - }; +/*! + * Casts val to an object suitable for `$text`. Throws an error if the object + * can't be casted. + * + * @param {Any} val value to cast + * @param {String} [path] path to associate with any errors that occured + * @return {Object} casted object + * @see https://docs.mongodb.com/manual/reference/operator/query/text/ + * @api private + */ - /*! - * ignore - */ +module.exports = function(val, path) { + if (val == null || typeof val !== 'object') { + throw new CastError('$text', val, path); + } - VirtualType.prototype.clone = function () { - const clone = new VirtualType(this.options, this.path); - clone.getters = [].concat(this.getters); - clone.setters = [].concat(this.setters); - return clone; - }; + if (val.$search != null) { + val.$search = castString(val.$search, path + '.$search'); + } + if (val.$language != null) { + val.$language = castString(val.$language, path + '.$language'); + } + if (val.$caseSensitive != null) { + val.$caseSensitive = castBoolean(val.$caseSensitive, + path + '.$castSensitive'); + } + if (val.$diacriticSensitive != null) { + val.$diacriticSensitive = castBoolean(val.$diacriticSensitive, + path + '.$diacriticSensitive'); + } - /** - * Adds a custom getter to this virtual. - * - * Mongoose calls the getter function with the below 3 parameters. - * - * - `value`: the value returned by the previous getter. If there is only one getter, `value` will be `undefined`. - * - `virtual`: the virtual object you called `.get()` on - * - `doc`: the document this virtual is attached to. Equivalent to `this`. - * - * ####Example: - * - * const virtual = schema.virtual('fullname'); - * virtual.get(function(value, virtual, doc) { - * return this.name.first + ' ' + this.name.last; - * }); - * - * @param {Function(Any, VirtualType, Document)} fn - * @return {VirtualType} this - * @api public - */ - - VirtualType.prototype.get = function (fn) { - this.getters.push(fn); - return this; - }; + return val; +}; - /** - * Adds a custom setter to this virtual. - * - * Mongoose calls the setter function with the below 3 parameters. - * - * - `value`: the value being set - * - `virtual`: the virtual object you're calling `.set()` on - * - `doc`: the document this virtual is attached to. Equivalent to `this`. - * - * ####Example: - * - * const virtual = schema.virtual('fullname'); - * virtual.set(function(value, virtual, doc) { - * const parts = value.split(' '); - * this.name.first = parts[0]; - * this.name.last = parts[1]; - * }); - * - * const Model = mongoose.model('Test', schema); - * const doc = new Model(); - * // Calls the setter with `value = 'Jean-Luc Picard'` - * doc.fullname = 'Jean-Luc Picard'; - * doc.name.first; // 'Jean-Luc' - * doc.name.last; // 'Picard' - * - * @param {Function(Any, VirtualType, Document)} fn - * @return {VirtualType} this - * @api public - */ - - VirtualType.prototype.set = function (fn) { - this.setters.push(fn); - return this; - }; - /** - * Applies getters to `value`. - * - * @param {Object} value - * @param {Document} doc The document this virtual is attached to - * @return {any} the value after applying all getters - * @api public - */ +/***/ }), - VirtualType.prototype.applyGetters = function (value, doc) { - if ( - utils.hasUserDefinedProperty(this.options, ["ref", "refPath"]) && - doc.$$populatedVirtuals && - doc.$$populatedVirtuals.hasOwnProperty(this.path) - ) { - value = doc.$$populatedVirtuals[this.path]; - } +/***/ 4093: +/***/ ((module) => { - let v = value; - for (let l = this.getters.length - 1; l >= 0; l--) { - v = this.getters[l].call(doc, v, this, doc); - } - return v; - }; +"use strict"; - /** - * Applies setters to `value`. - * - * @param {Object} value - * @param {Document} doc - * @return {any} the value after applying all setters - * @api public - */ - VirtualType.prototype.applySetters = function (value, doc) { - let v = value; - for (let l = this.setters.length - 1; l >= 0; l--) { - v = this.setters[l].call(doc, v, this, doc); - } - return v; - }; +/*! + * ignore + */ - /*! - * exports - */ +module.exports = function(val) { + if (Array.isArray(val)) { + if (!val.every(v => typeof v === 'number' || typeof v === 'string')) { + throw new Error('$type array values must be strings or numbers'); + } + return val; + } - module.exports = VirtualType; + if (typeof val !== 'number' && typeof val !== 'string') { + throw new Error('$type parameter must be number, string, or array of numbers and strings'); + } - /***/ - }, + return val; +}; - /***/ 8586: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; - module.exports = exports = __nccwpck_require__(9741); +/***/ }), - /***/ - }, +/***/ 7451: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /***/ 9741: /***/ ( - __unused_webpack_module, - exports, - __nccwpck_require__ - ) => { - /* eslint strict:off */ - /* eslint no-var: off */ - /* eslint no-redeclare: off */ - - var stringToParts = __nccwpck_require__(9655); - - // These properties are special and can open client libraries to security - // issues - var ignoreProperties = ["__proto__", "constructor", "prototype"]; - - /** - * Returns the value of object `o` at the given `path`. - * - * ####Example: - * - * var obj = { - * comments: [ - * { title: 'exciting!', _doc: { title: 'great!' }} - * , { title: 'number dos' } - * ] - * } - * - * mpath.get('comments.0.title', o) // 'exciting!' - * mpath.get('comments.0.title', o, '_doc') // 'great!' - * mpath.get('comments.title', o) // ['exciting!', 'number dos'] - * - * // summary - * mpath.get(path, o) - * mpath.get(path, o, special) - * mpath.get(path, o, map) - * mpath.get(path, o, special, map) - * - * @param {String} path - * @param {Object} o - * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. - * @param {Function} [map] Optional function which receives each individual found value. The value returned from `map` is used in the original values place. - */ - - exports.get = function (path, o, special, map) { - var lookup; - - if ("function" == typeof special) { - if (special.length < 2) { - map = special; - special = undefined; - } else { - lookup = special; - special = undefined; - } - } +"use strict"; - map || (map = K); - var parts = "string" == typeof path ? stringToParts(path) : path; +/*! + * Module dependencies. + */ - if (!Array.isArray(parts)) { - throw new TypeError("Invalid `path`. Must be either string or array"); - } +const SchemaType = __nccwpck_require__(5660); +const MongooseError = __nccwpck_require__(4327); +const SchemaStringOptions = __nccwpck_require__(7692); +const castString = __nccwpck_require__(1318); +const utils = __nccwpck_require__(9232); - var obj = o, - part; +const CastError = SchemaType.CastError; - for (var i = 0; i < parts.length; ++i) { - part = parts[i]; +/** + * String SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ - if (Array.isArray(obj) && !/^\d+$/.test(part)) { - // reading a property from the array items - var paths = parts.slice(i); +function SchemaString(key, options) { + this.enumValues = []; + this.regExp = null; + SchemaType.call(this, key, options, 'String'); +} - // Need to `concat()` to avoid `map()` calling a constructor of an array - // subclass - return [].concat(obj).map(function (item) { - return item - ? exports.get(paths, item, special || lookup, map) - : map(undefined); - }); - } +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaString.schemaName = 'String'; - if (lookup) { - obj = lookup(obj, part); - } else { - var _from = special && obj[special] ? obj[special] : obj; - obj = _from instanceof Map ? _from.get(part) : _from[part]; - } +SchemaString.defaultOptions = {}; - if (!obj) return map(obj); - } +/*! + * Inherits from SchemaType. + */ +SchemaString.prototype = Object.create(SchemaType.prototype); +SchemaString.prototype.constructor = SchemaString; +Object.defineProperty(SchemaString.prototype, 'OptionsConstructor', { + configurable: false, + enumerable: false, + writable: false, + value: SchemaStringOptions +}); + +/*! + * ignore + */ - return map(obj); - }; +SchemaString._cast = castString; - /** - * Returns true if `in` returns true for every piece of the path - * - * @param {String} path - * @param {Object} o - */ +/** + * Get/set the function used to cast arbitrary values to strings. + * + * ####Example: + * + * // Throw an error if you pass in an object. Normally, Mongoose allows + * // objects with custom `toString()` functions. + * const original = mongoose.Schema.Types.String.cast(); + * mongoose.Schema.Types.String.cast(v => { + * assert.ok(v == null || typeof v !== 'object'); + * return original(v); + * }); + * + * // Or disable casting entirely + * mongoose.Schema.Types.String.cast(false); + * + * @param {Function} caster + * @return {Function} + * @function get + * @static + * @api public + */ - exports.has = function (path, o) { - var parts = typeof path === "string" ? stringToParts(path) : path; +SchemaString.cast = function cast(caster) { + if (arguments.length === 0) { + return this._cast; + } + if (caster === false) { + caster = this._defaultCaster; + } + this._cast = caster; - if (!Array.isArray(parts)) { - throw new TypeError("Invalid `path`. Must be either string or array"); - } + return this._cast; +}; - var len = parts.length; - var cur = o; - for (var i = 0; i < len; ++i) { - if (cur == null || typeof cur !== "object" || !(parts[i] in cur)) { - return false; - } - cur = cur[parts[i]]; - } +/*! + * ignore + */ - return true; - }; +SchemaString._defaultCaster = v => { + if (v != null && typeof v !== 'string') { + throw new Error(); + } + return v; +}; - /** - * Deletes the last piece of `path` - * - * @param {String} path - * @param {Object} o - */ +/** + * Attaches a getter for all String instances. + * + * ####Example: + * + * // Make all numbers round down + * mongoose.Schema.String.get(v => v.toLowerCase()); + * + * const Model = mongoose.model('Test', new Schema({ test: String })); + * new Model({ test: 'FOO' }).test; // 'foo' + * + * @param {Function} getter + * @return {this} + * @function get + * @static + * @api public + */ - exports.unset = function (path, o) { - var parts = typeof path === "string" ? stringToParts(path) : path; +SchemaString.get = SchemaType.get; - if (!Array.isArray(parts)) { - throw new TypeError("Invalid `path`. Must be either string or array"); - } +/** + * Sets a default option for all String instances. + * + * ####Example: + * + * // Make all strings have option `trim` equal to true. + * mongoose.Schema.String.set('trim', true); + * + * const User = mongoose.model('User', new Schema({ name: String })); + * new User({ name: ' John Doe ' }).name; // 'John Doe' + * + * @param {String} option - The option you'd like to set the value for + * @param {*} value - value for option + * @return {undefined} + * @function set + * @static + * @api public + */ - var len = parts.length; - var cur = o; - for (var i = 0; i < len; ++i) { - if (cur == null || typeof cur !== "object" || !(parts[i] in cur)) { - return false; - } - // Disallow any updates to __proto__ or special properties. - if (ignoreProperties.indexOf(parts[i]) !== -1) { - return false; - } - if (i === len - 1) { - delete cur[parts[i]]; - return true; - } - cur = cur instanceof Map ? cur.get(parts[i]) : cur[parts[i]]; - } +SchemaString.set = SchemaType.set; - return true; - }; +/*! + * ignore + */ - /** - * Sets the `val` at the given `path` of object `o`. - * - * @param {String} path - * @param {Anything} val - * @param {Object} o - * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. - * @param {Function} [map] Optional function which is passed each individual value before setting it. The value returned from `map` is used in the original values place. - */ - - exports.set = function (path, val, o, special, map, _copying) { - var lookup; - - if ("function" == typeof special) { - if (special.length < 2) { - map = special; - special = undefined; - } else { - lookup = special; - special = undefined; - } - } +SchemaString._checkRequired = v => (v instanceof String || typeof v === 'string') && v.length; - map || (map = K); +/** + * Override the function the required validator uses to check whether a string + * passes the `required` check. + * + * ####Example: + * + * // Allow empty strings to pass `required` check + * mongoose.Schema.Types.String.checkRequired(v => v != null); + * + * const M = mongoose.model({ str: { type: String, required: true } }); + * new M({ str: '' }).validateSync(); // `null`, validation passes! + * + * @param {Function} fn + * @return {Function} + * @function checkRequired + * @static + * @api public + */ - var parts = "string" == typeof path ? stringToParts(path) : path; +SchemaString.checkRequired = SchemaType.checkRequired; - if (!Array.isArray(parts)) { - throw new TypeError("Invalid `path`. Must be either string or array"); - } +/** + * Adds an enum validator + * + * ####Example: + * + * const states = ['opening', 'open', 'closing', 'closed'] + * const s = new Schema({ state: { type: String, enum: states }}) + * const M = db.model('M', s) + * const m = new M({ state: 'invalid' }) + * m.save(function (err) { + * console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`. + * m.state = 'open' + * m.save(callback) // success + * }) + * + * // or with custom error messages + * const enum = { + * values: ['opening', 'open', 'closing', 'closed'], + * message: 'enum validator failed for path `{PATH}` with value `{VALUE}`' + * } + * const s = new Schema({ state: { type: String, enum: enum }) + * const M = db.model('M', s) + * const m = new M({ state: 'invalid' }) + * m.save(function (err) { + * console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid` + * m.state = 'open' + * m.save(callback) // success + * }) + * + * @param {String|Object} [args...] enumeration values + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ - if (null == o) return; +SchemaString.prototype.enum = function() { + if (this.enumValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.enumValidator; + }, this); + this.enumValidator = false; + } - for (var i = 0; i < parts.length; ++i) { - // Silently ignore any updates to `__proto__`, these are potentially - // dangerous if using mpath with unsanitized data. - if (ignoreProperties.indexOf(parts[i]) !== -1) { - return; - } - } + if (arguments[0] === void 0 || arguments[0] === false) { + return this; + } - // the existance of $ in a path tells us if the user desires - // the copying of an array instead of setting each value of - // the array to the one by one to matching positions of the - // current array. Unless the user explicitly opted out by passing - // false, see Automattic/mongoose#6273 - var copy = _copying || (/\$/.test(path) && _copying !== false), - obj = o, - part; + let values; + let errorMessage; - for (var i = 0, len = parts.length - 1; i < len; ++i) { - part = parts[i]; + if (utils.isObject(arguments[0])) { + if (Array.isArray(arguments[0].values)) { + values = arguments[0].values; + errorMessage = arguments[0].message; + } else { + values = utils.object.vals(arguments[0]); + errorMessage = MongooseError.messages.String.enum; + } + } else { + values = arguments; + errorMessage = MongooseError.messages.String.enum; + } - if ("$" == part) { - if (i == len - 1) { - break; - } else { - continue; - } - } + for (const value of values) { + if (value !== undefined) { + this.enumValues.push(this.cast(value)); + } + } - if (Array.isArray(obj) && !/^\d+$/.test(part)) { - var paths = parts.slice(i); - if (!copy && Array.isArray(val)) { - for (var j = 0; j < obj.length && j < val.length; ++j) { - // assignment of single values of array - exports.set( - paths, - val[j], - obj[j], - special || lookup, - map, - copy - ); - } - } else { - for (var j = 0; j < obj.length; ++j) { - // assignment of entire value - exports.set(paths, val, obj[j], special || lookup, map, copy); - } - } - return; - } + const vals = this.enumValues; + this.enumValidator = function(v) { + return undefined === v || ~vals.indexOf(v); + }; + this.validators.push({ + validator: this.enumValidator, + message: errorMessage, + type: 'enum', + enumValues: vals + }); + + return this; +}; + +/** + * Adds a lowercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). + * + * ####Example: + * + * const s = new Schema({ email: { type: String, lowercase: true }}) + * const M = db.model('M', s); + * const m = new M({ email: 'SomeEmail@example.COM' }); + * console.log(m.email) // someemail@example.com + * M.find({ email: 'SomeEmail@example.com' }); // Queries by 'someemail@example.com' + * + * Note that `lowercase` does **not** affect regular expression queries: + * + * ####Example: + * // Still queries for documents whose `email` matches the regular + * // expression /SomeEmail/. Mongoose does **not** convert the RegExp + * // to lowercase. + * M.find({ email: /SomeEmail/ }); + * + * @api public + * @return {SchemaType} this + */ - if (lookup) { - obj = lookup(obj, part); - } else { - var _to = special && obj[special] ? obj[special] : obj; - obj = _to instanceof Map ? _to.get(part) : _to[part]; - } +SchemaString.prototype.lowercase = function(shouldApply) { + if (arguments.length > 0 && !shouldApply) { + return this; + } + return this.set(v => { + if (typeof v !== 'string') { + v = this.cast(v); + } + if (v) { + return v.toLowerCase(); + } + return v; + }); +}; - if (!obj) return; - } +/** + * Adds an uppercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). + * + * ####Example: + * + * const s = new Schema({ caps: { type: String, uppercase: true }}) + * const M = db.model('M', s); + * const m = new M({ caps: 'an example' }); + * console.log(m.caps) // AN EXAMPLE + * M.find({ caps: 'an example' }) // Matches documents where caps = 'AN EXAMPLE' + * + * Note that `uppercase` does **not** affect regular expression queries: + * + * ####Example: + * // Mongoose does **not** convert the RegExp to uppercase. + * M.find({ email: /an example/ }); + * + * @api public + * @return {SchemaType} this + */ - // process the last property of the path +SchemaString.prototype.uppercase = function(shouldApply) { + if (arguments.length > 0 && !shouldApply) { + return this; + } + return this.set(v => { + if (typeof v !== 'string') { + v = this.cast(v); + } + if (v) { + return v.toUpperCase(); + } + return v; + }); +}; - part = parts[len]; +/** + * Adds a trim [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). + * + * The string value will be [trimmed](https://masteringjs.io/tutorials/fundamentals/trim-string) when set. + * + * ####Example: + * + * const s = new Schema({ name: { type: String, trim: true }}); + * const M = db.model('M', s); + * const string = ' some name '; + * console.log(string.length); // 11 + * const m = new M({ name: string }); + * console.log(m.name.length); // 9 + * + * // Equivalent to `findOne({ name: string.trim() })` + * M.findOne({ name: string }); + * + * Note that `trim` does **not** affect regular expression queries: + * + * ####Example: + * // Mongoose does **not** trim whitespace from the RegExp. + * M.find({ name: / some name / }); + * + * @api public + * @return {SchemaType} this + */ - // use the special property if exists - if (special && obj[special]) { - obj = obj[special]; - } +SchemaString.prototype.trim = function(shouldTrim) { + if (arguments.length > 0 && !shouldTrim) { + return this; + } + return this.set(v => { + if (typeof v !== 'string') { + v = this.cast(v); + } + if (v) { + return v.trim(); + } + return v; + }); +}; - // set the value on the last branch - if (Array.isArray(obj) && !/^\d+$/.test(part)) { - if (!copy && Array.isArray(val)) { - _setArray(obj, val, part, lookup, special, map); - } else { - for (var j = 0; j < obj.length; ++j) { - var item = obj[j]; - if (item) { - if (lookup) { - lookup(item, part, map(val)); - } else { - if (item[special]) item = item[special]; - item[part] = map(val); - } - } - } - } - } else { - if (lookup) { - lookup(obj, part, map(val)); - } else if (obj instanceof Map) { - obj.set(part, map(val)); - } else { - obj[part] = map(val); - } - } - }; +/** + * Sets a minimum length validator. + * + * ####Example: + * + * const schema = new Schema({ postalCode: { type: String, minlength: 5 }) + * const Address = db.model('Address', schema) + * const address = new Address({ postalCode: '9512' }) + * address.save(function (err) { + * console.error(err) // validator error + * address.postalCode = '95125'; + * address.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MINLENGTH} token which will be replaced with the minimum allowed length + * const minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).']; + * const schema = new Schema({ postalCode: { type: String, minlength: minlength }) + * const Address = mongoose.model('Address', schema); + * const address = new Address({ postalCode: '9512' }); + * address.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5). + * }) + * + * @param {Number} value minimum string length + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ - /*! - * Recursively set nested arrays - */ - - function _setArray(obj, val, part, lookup, special, map) { - for (var item, j = 0; j < obj.length && j < val.length; ++j) { - item = obj[j]; - if (Array.isArray(item) && Array.isArray(val[j])) { - _setArray(item, val[j], part, lookup, special, map); - } else if (item) { - if (lookup) { - lookup(item, part, map(val[j])); - } else { - if (item[special]) item = item[special]; - item[part] = map(val[j]); - } - } - } - } +SchemaString.prototype.minlength = function(value, message) { + if (this.minlengthValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.minlengthValidator; + }, this); + } - /*! - * Returns the value passed to it. - */ + if (value !== null && value !== undefined) { + let msg = message || MongooseError.messages.String.minlength; + msg = msg.replace(/{MINLENGTH}/, value); + this.validators.push({ + validator: this.minlengthValidator = function(v) { + return v === null || v.length >= value; + }, + message: msg, + type: 'minlength', + minlength: value + }); + } - function K(v) { - return v; - } + return this; +}; - /***/ - }, +SchemaString.prototype.minLength = SchemaString.prototype.minlength; - /***/ 9655: /***/ (module) => { - "use strict"; - - module.exports = function stringToParts(str) { - const result = []; - - let curPropertyName = ""; - let state = "DEFAULT"; - for (let i = 0; i < str.length; ++i) { - // Fall back to treating as property name rather than bracket notation if - // square brackets contains something other than a number. - if ( - state === "IN_SQUARE_BRACKETS" && - !/\d/.test(str[i]) && - str[i] !== "]" - ) { - state = "DEFAULT"; - curPropertyName = result[result.length - 1] + "[" + curPropertyName; - result.splice(result.length - 1, 1); - } +/** + * Sets a maximum length validator. + * + * ####Example: + * + * const schema = new Schema({ postalCode: { type: String, maxlength: 9 }) + * const Address = db.model('Address', schema) + * const address = new Address({ postalCode: '9512512345' }) + * address.save(function (err) { + * console.error(err) // validator error + * address.postalCode = '95125'; + * address.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MAXLENGTH} token which will be replaced with the maximum allowed length + * const maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).']; + * const schema = new Schema({ postalCode: { type: String, maxlength: maxlength }) + * const Address = mongoose.model('Address', schema); + * const address = new Address({ postalCode: '9512512345' }); + * address.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (9). + * }) + * + * @param {Number} value maximum string length + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ - if (str[i] === "[") { - if (state !== "IMMEDIATELY_AFTER_SQUARE_BRACKETS") { - result.push(curPropertyName); - curPropertyName = ""; - } - state = "IN_SQUARE_BRACKETS"; - } else if (str[i] === "]") { - if (state === "IN_SQUARE_BRACKETS") { - state = "IMMEDIATELY_AFTER_SQUARE_BRACKETS"; - result.push(curPropertyName); - curPropertyName = ""; - } else { - state = "DEFAULT"; - curPropertyName += str[i]; - } - } else if (str[i] === ".") { - if (state !== "IMMEDIATELY_AFTER_SQUARE_BRACKETS") { - result.push(curPropertyName); - curPropertyName = ""; - } - state = "DEFAULT"; - } else { - curPropertyName += str[i]; - } - } +SchemaString.prototype.maxlength = function(value, message) { + if (this.maxlengthValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.maxlengthValidator; + }, this); + } - if (state !== "IMMEDIATELY_AFTER_SQUARE_BRACKETS") { - result.push(curPropertyName); - } + if (value !== null && value !== undefined) { + let msg = message || MongooseError.messages.String.maxlength; + msg = msg.replace(/{MAXLENGTH}/, value); + this.validators.push({ + validator: this.maxlengthValidator = function(v) { + return v === null || v.length <= value; + }, + message: msg, + type: 'maxlength', + maxlength: value + }); + } - return result; - }; + return this; +}; - /***/ - }, +SchemaString.prototype.maxLength = SchemaString.prototype.maxlength; - /***/ 5257: /***/ (module, exports) => { - "use strict"; - - /** - * methods a collection must implement - */ - - var methods = [ - "find", - "findOne", - "update", - "updateMany", - "updateOne", - "replaceOne", - "remove", - "count", - "distinct", - "findAndModify", - "aggregate", - "findStream", - "deleteOne", - "deleteMany", - ]; +/** + * Sets a regexp validator. + * + * Any value that does not pass `regExp`.test(val) will fail validation. + * + * ####Example: + * + * const s = new Schema({ name: { type: String, match: /^a/ }}) + * const M = db.model('M', s) + * const m = new M({ name: 'I am invalid' }) + * m.validate(function (err) { + * console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)." + * m.name = 'apples' + * m.validate(function (err) { + * assert.ok(err) // success + * }) + * }) + * + * // using a custom error message + * const match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ]; + * const s = new Schema({ file: { type: String, match: match }}) + * const M = db.model('M', s); + * const m = new M({ file: 'invalid' }); + * m.validate(function (err) { + * console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)" + * }) + * + * Empty strings, `undefined`, and `null` values always pass the match validator. If you require these values, enable the `required` validator also. + * + * const s = new Schema({ name: { type: String, match: /^a/, required: true }}) + * + * @param {RegExp} regExp regular expression to test against + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ - /** - * Collection base class from which implementations inherit - */ +SchemaString.prototype.match = function match(regExp, message) { + // yes, we allow multiple match validators - function Collection() {} + const msg = message || MongooseError.messages.String.match; - for (var i = 0, len = methods.length; i < len; ++i) { - var method = methods[i]; - Collection.prototype[method] = notImplemented(method); - } + const matchValidator = function(v) { + if (!regExp) { + return false; + } - module.exports = exports = Collection; - Collection.methods = methods; + // In case RegExp happens to have `/g` flag set, we need to reset the + // `lastIndex`, otherwise `match` will intermittently fail. + regExp.lastIndex = 0; - /** - * creates a function which throws an implementation error - */ + const ret = ((v != null && v !== '') + ? regExp.test(v) + : true); + return ret; + }; - function notImplemented(method) { - return function () { - throw new Error("collection." + method + " not implemented"); - }; - } + this.validators.push({ + validator: matchValidator, + message: msg, + type: 'regexp', + regexp: regExp + }); + return this; +}; + +/** + * Check if the given value satisfies the `required` validator. The value is + * considered valid if it is a string (that is, not `null` or `undefined`) and + * has positive length. The `required` validator **will** fail for empty + * strings. + * + * @param {Any} value + * @param {Document} doc + * @return {Boolean} + * @api public + */ - /***/ - }, +SchemaString.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } - /***/ 5680: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + // `require('util').inherits()` does **not** copy static properties, and + // plugins like mongoose-float use `inherits()` for pre-ES6. + const _checkRequired = typeof this.constructor.checkRequired == 'function' ? + this.constructor.checkRequired() : + SchemaString.checkRequired(); - var env = __nccwpck_require__(5928); + return _checkRequired(value); +}; - if ("unknown" == env.type) { - throw new Error("Unknown environment"); - } +/** + * Casts to String + * + * @api private + */ - module.exports = env.isNode - ? __nccwpck_require__(7901) - : env.isMongo - ? __nccwpck_require__(5257) - : __nccwpck_require__(5257); +SchemaString.prototype.cast = function(value, doc, init) { + if (SchemaType._isRef(this, value, doc, init)) { + if (typeof value === 'string') { + return value; + } - /***/ - }, + return this._castRef(value, doc, init); + } - /***/ 7901: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; + let castString; + if (typeof this._castFunction === 'function') { + castString = this._castFunction; + } else if (typeof this.constructor.cast === 'function') { + castString = this.constructor.cast(); + } else { + castString = SchemaString.cast(); + } - /** - * Module dependencies - */ + try { + return castString(value); + } catch (error) { + throw new CastError('string', value, this.path, null, this); + } +}; - var Collection = __nccwpck_require__(5257); - var utils = __nccwpck_require__(7483); +/*! + * ignore + */ - function NodeCollection(col) { - this.collection = col; - this.collectionName = col.collectionName; - } +function handleSingle(val) { + return this.castForQuery(val); +} - /** - * inherit from collection base class - */ +function handleArray(val) { + const _this = this; + if (!Array.isArray(val)) { + return [this.castForQuery(val)]; + } + return val.map(function(m) { + return _this.castForQuery(m); + }); +} + +const $conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { + $all: handleArray, + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle, + $options: String, + $regex: handleSingle, + $not: handleSingle +}); + +Object.defineProperty(SchemaString.prototype, '$conditionalHandlers', { + configurable: false, + enumerable: false, + writable: false, + value: Object.freeze($conditionalHandlers) +}); + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [val] + * @api private + */ - utils.inherits(NodeCollection, Collection); +SchemaString.prototype.castForQuery = function($conditional, val) { + let handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with String.'); + } + return handler.call(this, val); + } + val = $conditional; + if (Object.prototype.toString.call(val) === '[object RegExp]') { + return val; + } - /** - * find(match, options, function(err, docs)) - */ + return this._castForQuery(val); +}; - NodeCollection.prototype.find = function (match, options, cb) { - this.collection.find(match, options, function (err, cursor) { - if (err) return cb(err); +/*! + * Module exports. + */ - try { - cursor.toArray(cb); - } catch (error) { - cb(error); - } - }); - }; +module.exports = SchemaString; - /** - * findOne(match, options, function(err, doc)) - */ - NodeCollection.prototype.findOne = function (match, options, cb) { - this.collection.findOne(match, options, cb); - }; +/***/ }), - /** - * count(match, options, function(err, count)) - */ +/***/ 1205: +/***/ ((__unused_webpack_module, exports) => { - NodeCollection.prototype.count = function (match, options, cb) { - this.collection.count(match, options, cb); - }; +"use strict"; - /** - * distinct(prop, match, options, function(err, count)) - */ - NodeCollection.prototype.distinct = function (prop, match, options, cb) { - this.collection.distinct(prop, match, options, cb); - }; +exports.schemaMixedSymbol = Symbol.for('mongoose:schema_mixed'); - /** - * update(match, update, options, function(err[, result])) - */ +exports.builtInMiddleware = Symbol.for('mongoose:built-in-middleware'); - NodeCollection.prototype.update = function (match, update, options, cb) { - this.collection.update(match, update, options, cb); - }; +/***/ }), - /** - * update(match, update, options, function(err[, result])) - */ - - NodeCollection.prototype.updateMany = function ( - match, - update, - options, - cb - ) { - this.collection.updateMany(match, update, options, cb); - }; +/***/ 5660: +/***/ ((module, exports, __nccwpck_require__) => { - /** - * update(match, update, options, function(err[, result])) - */ - - NodeCollection.prototype.updateOne = function ( - match, - update, - options, - cb - ) { - this.collection.updateOne(match, update, options, cb); - }; +"use strict"; - /** - * replaceOne(match, update, options, function(err[, result])) - */ - - NodeCollection.prototype.replaceOne = function ( - match, - update, - options, - cb - ) { - this.collection.replaceOne(match, update, options, cb); - }; - /** - * deleteOne(match, options, function(err[, result]) - */ +/*! + * Module dependencies. + */ - NodeCollection.prototype.deleteOne = function (match, options, cb) { - this.collection.deleteOne(match, options, cb); - }; +const MongooseError = __nccwpck_require__(4327); +const SchemaTypeOptions = __nccwpck_require__(7544); +const $exists = __nccwpck_require__(1426); +const $type = __nccwpck_require__(4093); +const get = __nccwpck_require__(8730); +const handleImmutable = __nccwpck_require__(773); +const isAsyncFunction = __nccwpck_require__(6073); +const immediate = __nccwpck_require__(4830); +const schemaTypeSymbol = __nccwpck_require__(3240).schemaTypeSymbol; +const utils = __nccwpck_require__(9232); +const validatorErrorSymbol = __nccwpck_require__(3240).validatorErrorSymbol; +const documentIsModified = __nccwpck_require__(3240).documentIsModified; + +const populateModelSymbol = __nccwpck_require__(3240).populateModelSymbol; + +const CastError = MongooseError.CastError; +const ValidatorError = MongooseError.ValidatorError; + +/** + * SchemaType constructor. Do **not** instantiate `SchemaType` directly. + * Mongoose converts your schema paths into SchemaTypes automatically. + * + * ####Example: + * + * const schema = new Schema({ name: String }); + * schema.path('name') instanceof SchemaType; // true + * + * @param {String} path + * @param {SchemaTypeOptions} [options] See [SchemaTypeOptions docs](/docs/api/schematypeoptions.html) + * @param {String} [instance] + * @api public + */ - /** - * deleteMany(match, options, function(err[, result]) - */ +function SchemaType(path, options, instance) { + this[schemaTypeSymbol] = true; + this.path = path; + this.instance = instance; + this.validators = []; + this.getters = this.constructor.hasOwnProperty('getters') ? + this.constructor.getters.slice() : + []; + this.setters = []; + + this.splitPath(); + + options = options || {}; + const defaultOptions = this.constructor.defaultOptions || {}; + const defaultOptionsKeys = Object.keys(defaultOptions); + + for (const option of defaultOptionsKeys) { + if (defaultOptions.hasOwnProperty(option) && !options.hasOwnProperty(option)) { + options[option] = defaultOptions[option]; + } + } - NodeCollection.prototype.deleteMany = function (match, options, cb) { - this.collection.deleteMany(match, options, cb); - }; + if (options.select == null) { + delete options.select; + } - /** - * remove(match, options, function(err[, result]) - */ + const Options = this.OptionsConstructor || SchemaTypeOptions; + this.options = new Options(options); + this._index = null; - NodeCollection.prototype.remove = function (match, options, cb) { - this.collection.remove(match, options, cb); - }; - /** - * findAndModify(match, update, options, function(err, doc)) - */ - - NodeCollection.prototype.findAndModify = function ( - match, - update, - options, - cb - ) { - var sort = Array.isArray(options.sort) ? options.sort : []; - this.collection.findAndModify(match, sort, update, options, cb); - }; + if (utils.hasUserDefinedProperty(this.options, 'immutable')) { + this.$immutable = this.options.immutable; - /** - * var stream = findStream(match, findOptions, streamOptions) - */ + handleImmutable(this); + } - NodeCollection.prototype.findStream = function ( - match, - findOptions, - streamOptions - ) { - return this.collection.find(match, findOptions).stream(streamOptions); - }; + const keys = Object.keys(this.options); + for (const prop of keys) { + if (prop === 'cast') { + this.castFunction(this.options[prop]); + continue; + } + if (utils.hasUserDefinedProperty(this.options, prop) && typeof this[prop] === 'function') { + // { unique: true, index: true } + if (prop === 'index' && this._index) { + if (options.index === false) { + const index = this._index; + if (typeof index === 'object' && index != null) { + if (index.unique) { + throw new Error('Path "' + this.path + '" may not have `index` ' + + 'set to false and `unique` set to true'); + } + if (index.sparse) { + throw new Error('Path "' + this.path + '" may not have `index` ' + + 'set to false and `sparse` set to true'); + } + } - /** - * var cursor = findCursor(match, findOptions) - */ + this._index = false; + } + continue; + } - NodeCollection.prototype.findCursor = function (match, findOptions) { - return this.collection.find(match, findOptions); - }; + const val = options[prop]; + // Special case so we don't screw up array defaults, see gh-5780 + if (prop === 'default') { + this.default(val); + continue; + } - /** - * aggregation(operators..., function(err, doc)) - * TODO - */ + const opts = Array.isArray(val) ? val : [val]; - /** - * Expose - */ + this[prop].apply(this, opts); + } + } - module.exports = exports = NodeCollection; + Object.defineProperty(this, '$$context', { + enumerable: false, + configurable: false, + writable: true, + value: null + }); +} - /***/ - }, +/*! + * The class that Mongoose uses internally to instantiate this SchemaType's `options` property. + */ - /***/ 5928: /***/ (__unused_webpack_module, exports) => { - "use strict"; - - exports.isNode = - "undefined" != typeof process && - "object" == "object" && - "object" == typeof global && - "function" == typeof Buffer && - process.argv; - - exports.isMongo = - !exports.isNode && - "function" == typeof printjson && - "function" == typeof ObjectId && - "function" == typeof rs && - "function" == typeof sh; - - exports.isBrowser = - !exports.isNode && !exports.isMongo && "undefined" != typeof window; - - exports.type = exports.isNode - ? "node" - : exports.isMongo - ? "mongo" - : exports.isBrowser - ? "browser" - : "unknown"; - - /***/ - }, +SchemaType.prototype.OptionsConstructor = SchemaTypeOptions; - /***/ 3821: /***/ (module, exports, __nccwpck_require__) => { - "use strict"; +/*! + * ignore + */ - /** - * Dependencies - */ +SchemaType.prototype.splitPath = function() { + if (this._presplitPath != null) { + return this._presplitPath; + } + if (this.path == null) { + return undefined; + } - var slice = __nccwpck_require__(9889); - var assert = __nccwpck_require__(2357); - var util = __nccwpck_require__(1669); - var utils = __nccwpck_require__(7483); - var debug = __nccwpck_require__(5831)("mquery"); + this._presplitPath = this.path.indexOf('.') === -1 ? [this.path] : this.path.split('.'); + return this._presplitPath; +}; - /* global Map */ +/** + * Get/set the function used to cast arbitrary values to this type. + * + * ####Example: + * + * // Disallow `null` for numbers, and don't try to cast any values to + * // numbers, so even strings like '123' will cause a CastError. + * mongoose.Number.cast(function(v) { + * assert.ok(v === undefined || typeof v === 'number'); + * return v; + * }); + * + * @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed + * @return {Function} + * @static + * @receiver SchemaType + * @function cast + * @api public + */ - /** - * Query constructor used for building queries. - * - * ####Example: - * - * var query = new Query({ name: 'mquery' }); - * query.setOptions({ collection: moduleCollection }) - * query.where('age').gte(21).exec(callback); - * - * @param {Object} [criteria] - * @param {Object} [options] - * @api public - */ +SchemaType.cast = function cast(caster) { + if (arguments.length === 0) { + return this._cast; + } + if (caster === false) { + caster = v => v; + } + this._cast = caster; - function Query(criteria, options) { - if (!(this instanceof Query)) return new Query(criteria, options); + return this._cast; +}; - var proto = this.constructor.prototype; +/** + * Get/set the function used to cast arbitrary values to this particular schematype instance. + * Overrides `SchemaType.cast()`. + * + * ####Example: + * + * // Disallow `null` for numbers, and don't try to cast any values to + * // numbers, so even strings like '123' will cause a CastError. + * const number = new mongoose.Number('mypath', {}); + * number.cast(function(v) { + * assert.ok(v === undefined || typeof v === 'number'); + * return v; + * }); + * + * @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed + * @return {Function} + * @static + * @receiver SchemaType + * @function cast + * @api public + */ - this.op = proto.op || undefined; +SchemaType.prototype.castFunction = function castFunction(caster) { + if (arguments.length === 0) { + return this._castFunction; + } + if (caster === false) { + caster = this.constructor._defaultCaster || (v => v); + } + this._castFunction = caster; - this.options = Object.assign({}, proto.options); + return this._castFunction; +}; - this._conditions = proto._conditions - ? utils.clone(proto._conditions) - : {}; +/** + * The function that Mongoose calls to cast arbitrary values to this SchemaType. + * + * @param {Object} value value to cast + * @param {Document} doc document that triggers the casting + * @param {Boolean} init + * @api public + */ - this._fields = proto._fields ? utils.clone(proto._fields) : undefined; +SchemaType.prototype.cast = function cast() { + throw new Error('Base SchemaType class does not implement a `cast()` function'); +}; - this._update = proto._update ? utils.clone(proto._update) : undefined; +/** + * Sets a default option for this schema type. + * + * ####Example: + * + * // Make all strings be trimmed by default + * mongoose.SchemaTypes.String.set('trim', true); + * + * @param {String} option The name of the option you'd like to set (e.g. trim, lowercase, etc...) + * @param {*} value The value of the option you'd like to set. + * @return {void} + * @static + * @receiver SchemaType + * @function set + * @api public + */ - this._path = proto._path || undefined; - this._distinct = proto._distinct || undefined; - this._collection = proto._collection || undefined; - this._traceFunction = proto._traceFunction || undefined; +SchemaType.set = function set(option, value) { + if (!this.hasOwnProperty('defaultOptions')) { + this.defaultOptions = Object.assign({}, this.defaultOptions); + } + this.defaultOptions[option] = value; +}; - if (options) { - this.setOptions(options); - } +/** + * Attaches a getter for all instances of this schema type. + * + * ####Example: + * + * // Make all numbers round down + * mongoose.Number.get(function(v) { return Math.floor(v); }); + * + * @param {Function} getter + * @return {this} + * @static + * @receiver SchemaType + * @function get + * @api public + */ - if (criteria) { - if (criteria.find && criteria.remove && criteria.update) { - // quack quack! - this.collection(criteria); - } else { - this.find(criteria); - } - } - } +SchemaType.get = function(getter) { + this.getters = this.hasOwnProperty('getters') ? this.getters : []; + this.getters.push(getter); +}; - /** - * This is a parameter that the user can set which determines if mquery - * uses $within or $geoWithin for queries. It defaults to true which - * means $geoWithin will be used. If using MongoDB < 2.4 you should - * set this to false. - * - * @api public - * @property use$geoWithin - */ +/** + * Sets a default value for this SchemaType. + * + * ####Example: + * + * const schema = new Schema({ n: { type: Number, default: 10 }) + * const M = db.model('M', schema) + * const m = new M; + * console.log(m.n) // 10 + * + * Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation. + * + * ####Example: + * + * // values are cast: + * const schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }}) + * const M = db.model('M', schema) + * const m = new M; + * console.log(m.aNumber) // 4.815162342 + * + * // default unique objects for Mixed types: + * const schema = new Schema({ mixed: Schema.Types.Mixed }); + * schema.path('mixed').default(function () { + * return {}; + * }); + * + * // if we don't use a function to return object literals for Mixed defaults, + * // each document will receive a reference to the same object literal creating + * // a "shared" object instance: + * const schema = new Schema({ mixed: Schema.Types.Mixed }); + * schema.path('mixed').default({}); + * const M = db.model('M', schema); + * const m1 = new M; + * m1.mixed.added = 1; + * console.log(m1.mixed); // { added: 1 } + * const m2 = new M; + * console.log(m2.mixed); // { added: 1 } + * + * @param {Function|any} val the default value + * @return {defaultValue} + * @api public + */ - var $withinCmd = "$geoWithin"; - Object.defineProperty(Query, "use$geoWithin", { - get: function () { - return $withinCmd == "$geoWithin"; - }, - set: function (v) { - if (true === v) { - // mongodb >= 2.4 - $withinCmd = "$geoWithin"; - } else { - $withinCmd = "$within"; - } - }, - }); +SchemaType.prototype.default = function(val) { + if (arguments.length === 1) { + if (val === void 0) { + this.defaultValue = void 0; + return void 0; + } - /** - * Converts this query to a constructor function with all arguments and options retained. - * - * ####Example - * - * // Create a query that will read documents with a "video" category from - * // `aCollection` on the primary node in the replica-set unless it is down, - * // in which case we'll read from a secondary node. - * var query = mquery({ category: 'video' }) - * query.setOptions({ collection: aCollection, read: 'primaryPreferred' }); - * - * // create a constructor based off these settings - * var Video = query.toConstructor(); - * - * // Video is now a subclass of mquery() and works the same way but with the - * // default query parameters and options set. - * - * // run a query with the previous settings but filter for movies with names - * // that start with "Life". - * Video().where({ name: /^Life/ }).exec(cb); - * - * @return {Query} new Query - * @api public - */ - - Query.prototype.toConstructor = function toConstructor() { - function CustomQuery(criteria, options) { - if (!(this instanceof CustomQuery)) - return new CustomQuery(criteria, options); - Query.call(this, criteria, options); - } - - utils.inherits(CustomQuery, Query); - - // set inherited defaults - var p = CustomQuery.prototype; - - p.options = {}; - p.setOptions(this.options); - - p.op = this.op; - p._conditions = utils.clone(this._conditions); - p._fields = utils.clone(this._fields); - p._update = utils.clone(this._update); - p._path = this._path; - p._distinct = this._distinct; - p._collection = this._collection; - p._traceFunction = this._traceFunction; - - return CustomQuery; - }; + if (val != null && val.instanceOfSchema) { + throw new MongooseError('Cannot set default value of path `' + this.path + + '` to a mongoose Schema instance.'); + } - /** - * Sets query options. - * - * ####Options: - * - * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) * - * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) * - * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) * - * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) * - * - [maxScan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) * - * - [maxTime](http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS) * - * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) * - * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) * - * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) * - * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) * - * - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) * - * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command) - * - collection the collection to query against - * - * _* denotes a query helper method is also available_ - * - * @param {Object} options - * @api public - */ - - Query.prototype.setOptions = function (options) { - if (!(options && utils.isObject(options))) return this; - - // set arbitrary options - var methods = utils.keys(options), - method; - - for (var i = 0; i < methods.length; ++i) { - method = methods[i]; - - // use methods if exist (safer option manipulation) - if ("function" == typeof this[method]) { - var args = utils.isArray(options[method]) - ? options[method] - : [options[method]]; - this[method].apply(this, args); - } else { - this.options[method] = options[method]; - } - } + this.defaultValue = val; + return this.defaultValue; + } else if (arguments.length > 1) { + this.defaultValue = utils.args(arguments); + } + return this.defaultValue; +}; - return this; - }; +/** + * Declares the index options for this schematype. + * + * ####Example: + * + * const s = new Schema({ name: { type: String, index: true }) + * const s = new Schema({ loc: { type: [Number], index: 'hashed' }) + * const s = new Schema({ loc: { type: [Number], index: '2d', sparse: true }) + * const s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }}) + * const s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }}) + * s.path('my.path').index(true); + * s.path('my.date').index({ expires: 60 }); + * s.path('my.path').index({ unique: true, sparse: true }); + * + * ####NOTE: + * + * _Indexes are created [in the background](https://docs.mongodb.com/manual/core/index-creation/#index-creation-background) + * by default. If `background` is set to `false`, MongoDB will not execute any + * read/write operations you send until the index build. + * Specify `background: false` to override Mongoose's default._ + * + * @param {Object|Boolean|String} options + * @return {SchemaType} this + * @api public + */ - /** - * Sets this Querys collection. - * - * @param {Collection} coll - * @return {Query} this - */ +SchemaType.prototype.index = function(options) { + this._index = options; + utils.expires(this._index); + return this; +}; - Query.prototype.collection = function collection(coll) { - this._collection = new Query.Collection(coll); +/** + * Declares an unique index. + * + * ####Example: + * + * const s = new Schema({ name: { type: String, unique: true }}); + * s.path('name').index({ unique: true }); + * + * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._ + * + * @param {Boolean} bool + * @return {SchemaType} this + * @api public + */ - return this; - }; +SchemaType.prototype.unique = function(bool) { + if (this._index === false) { + if (!bool) { + return; + } + throw new Error('Path "' + this.path + '" may not have `index` set to ' + + 'false and `unique` set to true'); + } - /** - * Adds a collation to this op (MongoDB 3.4 and up) - * - * ####Example - * - * query.find().collation({ locale: "en_US", strength: 1 }) - * - * @param {Object} value - * @return {Query} this - * @see MongoDB docs https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation - * @api public - */ - - Query.prototype.collation = function (value) { - this.options.collation = value; - return this; - }; + if (!this.options.hasOwnProperty('index') && bool === false) { + return this; + } - /** - * Specifies a `$where` condition - * - * Use `$where` when you need to select documents using a JavaScript expression. - * - * ####Example - * - * query.$where('this.comments.length > 10 || this.name.length > 5') - * - * query.$where(function () { - * return this.comments.length > 10 || this.name.length > 5; - * }) - * - * @param {String|Function} js javascript string or function - * @return {Query} this - * @memberOf Query - * @method $where - * @api public - */ - - Query.prototype.$where = function (js) { - this._conditions.$where = js; - return this; - }; + if (this._index == null || this._index === true) { + this._index = {}; + } else if (typeof this._index === 'string') { + this._index = { type: this._index }; + } - /** - * Specifies a `path` for use with chaining. - * - * ####Example - * - * // instead of writing: - * User.find({age: {$gte: 21, $lte: 65}}, callback); - * - * // we can instead write: - * User.where('age').gte(21).lte(65); - * - * // passing query conditions is permitted - * User.find().where({ name: 'vonderful' }) - * - * // chaining - * User - * .where('age').gte(21).lte(65) - * .where('name', /^vonderful/i) - * .where('friends').slice(10) - * .exec(callback) - * - * @param {String} [path] - * @param {Object} [val] - * @return {Query} this - * @api public - */ - - Query.prototype.where = function () { - if (!arguments.length) return this; - if (!this.op) this.op = "find"; - - var type = typeof arguments[0]; - - if ("string" == type) { - this._path = arguments[0]; - - if (2 === arguments.length) { - this._conditions[this._path] = arguments[1]; - } + this._index.unique = bool; + return this; +}; - return this; - } +/** + * Declares a full text index. + * + * ###Example: + * + * const s = new Schema({name : {type: String, text : true }) + * s.path('name').index({text : true}); + * @param {Boolean} bool + * @return {SchemaType} this + * @api public + */ - if ("object" == type && !Array.isArray(arguments[0])) { - return this.merge(arguments[0]); - } +SchemaType.prototype.text = function(bool) { + if (this._index === false) { + if (!bool) { + return; + } + throw new Error('Path "' + this.path + '" may not have `index` set to ' + + 'false and `text` set to true'); + } - throw new TypeError("path must be a string or object"); - }; + if (!this.options.hasOwnProperty('index') && bool === false) { + return this; + } - /** - * Specifies the complementary comparison value for paths specified with `where()` - * - * ####Example - * - * User.where('age').equals(49); - * - * // is the same as - * - * User.where('age', 49); - * - * @param {Object} val - * @return {Query} this - * @api public - */ - - Query.prototype.equals = function equals(val) { - this._ensurePath("equals"); - var path = this._path; - this._conditions[path] = val; - return this; - }; + if (this._index === null || this._index === undefined || + typeof this._index === 'boolean') { + this._index = {}; + } else if (typeof this._index === 'string') { + this._index = { type: this._index }; + } - /** - * Specifies the complementary comparison value for paths specified with `where()` - * This is alias of `equals` - * - * ####Example - * - * User.where('age').eq(49); - * - * // is the same as - * - * User.shere('age').equals(49); - * - * // is the same as - * - * User.where('age', 49); - * - * @param {Object} val - * @return {Query} this - * @api public - */ - - Query.prototype.eq = function eq(val) { - this._ensurePath("eq"); - var path = this._path; - this._conditions[path] = val; - return this; - }; + this._index.text = bool; + return this; +}; - /** - * Specifies arguments for an `$or` condition. - * - * ####Example - * - * query.or([{ color: 'red' }, { status: 'emergency' }]) - * - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - - Query.prototype.or = function or(array) { - var or = this._conditions.$or || (this._conditions.$or = []); - if (!utils.isArray(array)) array = [array]; - or.push.apply(or, array); - return this; - }; +/** + * Declares a sparse index. + * + * ####Example: + * + * const s = new Schema({ name: { type: String, sparse: true } }); + * s.path('name').index({ sparse: true }); + * + * @param {Boolean} bool + * @return {SchemaType} this + * @api public + */ - /** - * Specifies arguments for a `$nor` condition. - * - * ####Example - * - * query.nor([{ color: 'green' }, { status: 'ok' }]) - * - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - - Query.prototype.nor = function nor(array) { - var nor = this._conditions.$nor || (this._conditions.$nor = []); - if (!utils.isArray(array)) array = [array]; - nor.push.apply(nor, array); - return this; - }; +SchemaType.prototype.sparse = function(bool) { + if (this._index === false) { + if (!bool) { + return; + } + throw new Error('Path "' + this.path + '" may not have `index` set to ' + + 'false and `sparse` set to true'); + } - /** - * Specifies arguments for a `$and` condition. - * - * ####Example - * - * query.and([{ color: 'green' }, { status: 'ok' }]) - * - * @see $and http://docs.mongodb.org/manual/reference/operator/and/ - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - - Query.prototype.and = function and(array) { - var and = this._conditions.$and || (this._conditions.$and = []); - if (!Array.isArray(array)) array = [array]; - and.push.apply(and, array); - return this; - }; + if (!this.options.hasOwnProperty('index') && bool === false) { + return this; + } - /** - * Specifies a $gt query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * ####Example - * - * Thing.find().where('age').gt(21) - * - * // or - * Thing.find().gt('age', 21) - * - * @method gt - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - - /** - * Specifies a $gte query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method gte - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - - /** - * Specifies a $lt query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lt - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - - /** - * Specifies a $lte query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lte - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - - /** - * Specifies a $ne query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method ne - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - - /** - * Specifies an $in query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method in - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - - /** - * Specifies an $nin query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method nin - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - - /** - * Specifies an $all query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method all - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - - /** - * Specifies a $size query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method size - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - - /** - * Specifies a $regex query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method regex - * @memberOf Query - * @param {String} [path] - * @param {String|RegExp} val - * @api public - */ - - /** - * Specifies a $maxDistance query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method maxDistance - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - - /*! - * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance - * - * Thing.where('type').nin(array) - */ - - "gt gte lt lte ne in nin all regex size maxDistance minDistance" - .split(" ") - .forEach(function ($conditional) { - Query.prototype[$conditional] = function () { - var path, val; - - if (1 === arguments.length) { - this._ensurePath($conditional); - val = arguments[0]; - path = this._path; - } else { - val = arguments[1]; - path = arguments[0]; - } + if (this._index == null || typeof this._index === 'boolean') { + this._index = {}; + } else if (typeof this._index === 'string') { + this._index = { type: this._index }; + } - var conds = - this._conditions[path] === null || - typeof this._conditions[path] === "object" - ? this._conditions[path] - : (this._conditions[path] = {}); - conds["$" + $conditional] = val; - return this; - }; - }); + this._index.sparse = bool; + return this; +}; - /** - * Specifies a `$mod` condition - * - * @param {String} [path] - * @param {Number} val - * @return {Query} this - * @api public - */ - - Query.prototype.mod = function () { - var val, path; - - if (1 === arguments.length) { - this._ensurePath("mod"); - val = arguments[0]; - path = this._path; - } else if (2 === arguments.length && !utils.isArray(arguments[1])) { - this._ensurePath("mod"); - val = slice(arguments); - path = this._path; - } else if (3 === arguments.length) { - val = slice(arguments, 1); - path = arguments[0]; - } else { - val = arguments[1]; - path = arguments[0]; - } +/** + * Defines this path as immutable. Mongoose prevents you from changing + * immutable paths unless the parent document has [`isNew: true`](/docs/api.html#document_Document-isNew). + * + * ####Example: + * + * const schema = new Schema({ + * name: { type: String, immutable: true }, + * age: Number + * }); + * const Model = mongoose.model('Test', schema); + * + * await Model.create({ name: 'test' }); + * const doc = await Model.findOne(); + * + * doc.isNew; // false + * doc.name = 'new name'; + * doc.name; // 'test', because `name` is immutable + * + * Mongoose also prevents changing immutable properties using `updateOne()` + * and `updateMany()` based on [strict mode](/docs/guide.html#strict). + * + * ####Example: + * + * // Mongoose will strip out the `name` update, because `name` is immutable + * Model.updateOne({}, { $set: { name: 'test2' }, $inc: { age: 1 } }); + * + * // If `strict` is set to 'throw', Mongoose will throw an error if you + * // update `name` + * const err = await Model.updateOne({}, { name: 'test2' }, { strict: 'throw' }). + * then(() => null, err => err); + * err.name; // StrictModeError + * + * // If `strict` is `false`, Mongoose allows updating `name` even though + * // the property is immutable. + * Model.updateOne({}, { name: 'test2' }, { strict: false }); + * + * @param {Boolean} bool + * @return {SchemaType} this + * @see isNew /docs/api.html#document_Document-isNew + * @api public + */ - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds.$mod = val; - return this; - }; +SchemaType.prototype.immutable = function(bool) { + this.$immutable = bool; + handleImmutable(this); - /** - * Specifies an `$exists` condition - * - * ####Example - * - * // { name: { $exists: true }} - * Thing.where('name').exists() - * Thing.where('name').exists(true) - * Thing.find().exists('name') - * - * // { name: { $exists: false }} - * Thing.where('name').exists(false); - * Thing.find().exists('name', false); - * - * @param {String} [path] - * @param {Number} val - * @return {Query} this - * @api public - */ - - Query.prototype.exists = function () { - var path, val; - - if (0 === arguments.length) { - this._ensurePath("exists"); - path = this._path; - val = true; - } else if (1 === arguments.length) { - if ("boolean" === typeof arguments[0]) { - this._ensurePath("exists"); - path = this._path; - val = arguments[0]; - } else { - path = arguments[0]; - val = true; - } - } else if (2 === arguments.length) { - path = arguments[0]; - val = arguments[1]; - } + return this; +}; - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds.$exists = val; - return this; - }; +/** + * Defines a custom function for transforming this path when converting a document to JSON. + * + * Mongoose calls this function with one parameter: the current `value` of the path. Mongoose + * then uses the return value in the JSON output. + * + * ####Example: + * + * const schema = new Schema({ + * date: { type: Date, transform: v => v.getFullYear() } + * }); + * const Model = mongoose.model('Test', schema); + * + * await Model.create({ date: new Date('2016-06-01') }); + * const doc = await Model.findOne(); + * + * doc.date instanceof Date; // true + * + * doc.toJSON().date; // 2016 as a number + * JSON.stringify(doc); // '{"_id":...,"date":2016}' + * + * @param {Function} fn + * @return {SchemaType} this + * @api public + */ - /** - * Specifies an `$elemMatch` condition - * - * ####Example - * - * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) - * - * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) - * - * query.elemMatch('comment', function (elem) { - * elem.where('author').equals('autobot'); - * elem.where('votes').gte(5); - * }) - * - * query.where('comment').elemMatch(function (elem) { - * elem.where({ author: 'autobot' }); - * elem.where('votes').gte(5); - * }) - * - * @param {String|Object|Function} path - * @param {Object|Function} criteria - * @return {Query} this - * @api public - */ - - Query.prototype.elemMatch = function () { - if (null == arguments[0]) throw new TypeError("Invalid argument"); - - var fn, path, criteria; - - if ("function" === typeof arguments[0]) { - this._ensurePath("elemMatch"); - path = this._path; - fn = arguments[0]; - } else if (utils.isObject(arguments[0])) { - this._ensurePath("elemMatch"); - path = this._path; - criteria = arguments[0]; - } else if ("function" === typeof arguments[1]) { - path = arguments[0]; - fn = arguments[1]; - } else if (arguments[1] && utils.isObject(arguments[1])) { - path = arguments[0]; - criteria = arguments[1]; - } else { - throw new TypeError("Invalid argument"); - } +SchemaType.prototype.transform = function(fn) { + this.options.transform = fn; - if (fn) { - criteria = new Query(); - fn(criteria); - criteria = criteria._conditions; - } + return this; +}; - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds.$elemMatch = criteria; - return this; - }; +/** + * Adds a setter to this schematype. + * + * ####Example: + * + * function capitalize (val) { + * if (typeof val !== 'string') val = ''; + * return val.charAt(0).toUpperCase() + val.substring(1); + * } + * + * // defining within the schema + * const s = new Schema({ name: { type: String, set: capitalize }}); + * + * // or with the SchemaType + * const s = new Schema({ name: String }) + * s.path('name').set(capitalize); + * + * Setters allow you to transform the data before it gets to the raw mongodb + * document or query. + * + * Suppose you are implementing user registration for a website. Users provide + * an email and password, which gets saved to mongodb. The email is a string + * that you will want to normalize to lower case, in order to avoid one email + * having more than one account -- e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM. + * + * You can set up email lower case normalization easily via a Mongoose setter. + * + * function toLower(v) { + * return v.toLowerCase(); + * } + * + * const UserSchema = new Schema({ + * email: { type: String, set: toLower } + * }); + * + * const User = db.model('User', UserSchema); + * + * const user = new User({email: 'AVENUE@Q.COM'}); + * console.log(user.email); // 'avenue@q.com' + * + * // or + * const user = new User(); + * user.email = 'Avenue@Q.com'; + * console.log(user.email); // 'avenue@q.com' + * User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } }); // update to 'avenue@q.com' + * + * As you can see above, setters allow you to transform the data before it + * stored in MongoDB, or before executing a query. + * + * _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._ + * + * new Schema({ email: { type: String, lowercase: true }}) + * + * Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema. + * + * function inspector (val, priorValue, schematype) { + * if (schematype.options.required) { + * return schematype.path + ' is required'; + * } else { + * return val; + * } + * } + * + * const VirusSchema = new Schema({ + * name: { type: String, required: true, set: inspector }, + * taxonomy: { type: String, set: inspector } + * }) + * + * const Virus = db.model('Virus', VirusSchema); + * const v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' }); + * + * console.log(v.name); // name is required + * console.log(v.taxonomy); // Parvovirinae + * + * You can also use setters to modify other properties on the document. If + * you're setting a property `name` on a document, the setter will run with + * `this` as the document. Be careful, in mongoose 5 setters will also run + * when querying by `name` with `this` as the query. + * + * ```javascript + * const nameSchema = new Schema({ name: String, keywords: [String] }); + * nameSchema.path('name').set(function(v) { + * // Need to check if `this` is a document, because in mongoose 5 + * // setters will also run on queries, in which case `this` will be a + * // mongoose query object. + * if (this instanceof Document && v != null) { + * this.keywords = v.split(' '); + * } + * return v; + * }); + * ``` + * + * @param {Function} fn + * @return {SchemaType} this + * @api public + */ - // Spatial queries - - /** - * Sugar for geo-spatial queries. - * - * ####Example - * - * query.within().box() - * query.within().circle() - * query.within().geometry() - * - * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); - * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); - * query.where('loc').within({ polygon: [[],[],[],[]] }); - * - * query.where('loc').within([], [], []) // polygon - * query.where('loc').within([], []) // box - * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry - * - * ####NOTE: - * - * Must be used after `where()`. - * - * @memberOf Query - * @return {Query} this - * @api public - */ - - Query.prototype.within = function within() { - // opinionated, must be used after where - this._ensurePath("within"); - this._geoComparison = $withinCmd; - - if (0 === arguments.length) { - return this; - } +SchemaType.prototype.set = function(fn) { + if (typeof fn !== 'function') { + throw new TypeError('A setter must be a function.'); + } + this.setters.push(fn); + return this; +}; - if (2 === arguments.length) { - return this.box.apply(this, arguments); - } else if (2 < arguments.length) { - return this.polygon.apply(this, arguments); - } +/** + * Adds a getter to this schematype. + * + * ####Example: + * + * function dob (val) { + * if (!val) return val; + * return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear(); + * } + * + * // defining within the schema + * const s = new Schema({ born: { type: Date, get: dob }) + * + * // or by retreiving its SchemaType + * const s = new Schema({ born: Date }) + * s.path('born').get(dob) + * + * Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see. + * + * Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way: + * + * function obfuscate (cc) { + * return '****-****-****-' + cc.slice(cc.length-4, cc.length); + * } + * + * const AccountSchema = new Schema({ + * creditCardNumber: { type: String, get: obfuscate } + * }); + * + * const Account = db.model('Account', AccountSchema); + * + * Account.findById(id, function (err, found) { + * console.log(found.creditCardNumber); // '****-****-****-1234' + * }); + * + * Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema. + * + * function inspector (val, priorValue, schematype) { + * if (schematype.options.required) { + * return schematype.path + ' is required'; + * } else { + * return schematype.path + ' is not'; + * } + * } + * + * const VirusSchema = new Schema({ + * name: { type: String, required: true, get: inspector }, + * taxonomy: { type: String, get: inspector } + * }) + * + * const Virus = db.model('Virus', VirusSchema); + * + * Virus.findById(id, function (err, virus) { + * console.log(virus.name); // name is required + * console.log(virus.taxonomy); // taxonomy is not + * }) + * + * @param {Function} fn + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.get = function(fn) { + if (typeof fn !== 'function') { + throw new TypeError('A getter must be a function.'); + } + this.getters.push(fn); + return this; +}; - var area = arguments[0]; +/** + * Adds validator(s) for this document path. + * + * Validators always receive the value to validate as their first argument and + * must return `Boolean`. Returning `false` or throwing an error means + * validation failed. + * + * The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used. + * + * ####Examples: + * + * // make sure every value is equal to "something" + * function validator (val) { + * return val == 'something'; + * } + * new Schema({ name: { type: String, validate: validator }}); + * + * // with a custom error message + * + * const custom = [validator, 'Uh oh, {PATH} does not equal "something".'] + * new Schema({ name: { type: String, validate: custom }}); + * + * // adding many validators at a time + * + * const many = [ + * { validator: validator, msg: 'uh oh' } + * , { validator: anotherValidator, msg: 'failed' } + * ] + * new Schema({ name: { type: String, validate: many }}); + * + * // or utilizing SchemaType methods directly: + * + * const schema = new Schema({ name: 'string' }); + * schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`'); + * + * ####Error message templates: + * + * From the examples above, you may have noticed that error messages support + * basic templating. There are a few other template keywords besides `{PATH}` + * and `{VALUE}` too. To find out more, details are available + * [here](#error_messages_MongooseError.messages). + * + * If Mongoose's built-in error message templating isn't enough, Mongoose + * supports setting the `message` property to a function. + * + * schema.path('name').validate({ + * validator: function() { return v.length > 5; }, + * // `errors['name']` will be "name must have length 5, got 'foo'" + * message: function(props) { + * return `${props.path} must have length 5, got '${props.value}'`; + * } + * }); + * + * To bypass Mongoose's error messages and just copy the error message that + * the validator throws, do this: + * + * schema.path('name').validate({ + * validator: function() { throw new Error('Oops!'); }, + * // `errors['name']` will be "Oops!" + * message: function(props) { return props.reason.message; } + * }); + * + * ####Asynchronous validation: + * + * Mongoose supports validators that return a promise. A validator that returns + * a promise is called an _async validator_. Async validators run in + * parallel, and `validate()` will wait until all async validators have settled. + * + * schema.path('name').validate({ + * validator: function (value) { + * return new Promise(function (resolve, reject) { + * resolve(false); // validation failed + * }); + * } + * }); + * + * You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs. + * + * Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate). + * + * If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along. + * + * const conn = mongoose.createConnection(..); + * conn.on('error', handleError); + * + * const Product = conn.model('Product', yourSchema); + * const dvd = new Product(..); + * dvd.save(); // emits error on the `conn` above + * + * If you want to handle these errors at the Model level, add an `error` + * listener to your Model as shown below. + * + * // registering an error listener on the Model lets us handle errors more locally + * Product.on('error', handleError); + * + * @param {RegExp|Function|Object} obj validator function, or hash describing options + * @param {Function} [obj.validator] validator function. If the validator function returns `undefined` or a truthy value, validation succeeds. If it returns [falsy](https://masteringjs.io/tutorials/fundamentals/falsy) (except `undefined`) or throws an error, validation fails. + * @param {String|Function} [obj.message] optional error message. If function, should return the error message as a string + * @param {Boolean} [obj.propsParameter=false] If true, Mongoose will pass the validator properties object (with the `validator` function, `message`, etc.) as the 2nd arg to the validator function. This is disabled by default because many validators [rely on positional args](https://github.com/chriso/validator.js#validators), so turning this on may cause unpredictable behavior in external validators. + * @param {String|Function} [errorMsg] optional error message. If function, should return the error message as a string + * @param {String} [type] optional validator type + * @return {SchemaType} this + * @api public + */ - if (!area) throw new TypeError("Invalid argument"); +SchemaType.prototype.validate = function(obj, message, type) { + if (typeof obj === 'function' || obj && utils.getFunctionName(obj.constructor) === 'RegExp') { + let properties; + if (typeof message === 'function') { + properties = { validator: obj, message: message }; + properties.type = type || 'user defined'; + } else if (message instanceof Object && !type) { + properties = utils.clone(message); + if (!properties.message) { + properties.message = properties.msg; + } + properties.validator = obj; + properties.type = properties.type || 'user defined'; + } else { + if (message == null) { + message = MongooseError.messages.general.default; + } + if (!type) { + type = 'user defined'; + } + properties = { message: message, type: type, validator: obj }; + } - if (area.center) return this.circle(area); + this.validators.push(properties); + return this; + } - if (area.box) return this.box.apply(this, area.box); + let i; + let length; + let arg; - if (area.polygon) return this.polygon.apply(this, area.polygon); + for (i = 0, length = arguments.length; i < length; i++) { + arg = arguments[i]; + if (!utils.isPOJO(arg)) { + const msg = 'Invalid validator. Received (' + typeof arg + ') ' + + arg + + '. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate'; - if (area.type && area.coordinates) return this.geometry(area); + throw new Error(msg); + } + this.validate(arg.validator, arg); + } - throw new TypeError("Invalid argument"); - }; + return this; +}; - /** - * Specifies a $box condition - * - * ####Example - * - * var lowerLeft = [40.73083, -73.99756] - * var upperRight= [40.741404, -73.988135] - * - * query.where('loc').within().box(lowerLeft, upperRight) - * query.box('loc', lowerLeft, upperRight ) - * - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @see Query#within #query_Query-within - * @param {String} path - * @param {Object} val - * @return {Query} this - * @api public - */ - - Query.prototype.box = function () { - var path, box; - - if (3 === arguments.length) { - // box('loc', [], []) - path = arguments[0]; - box = [arguments[1], arguments[2]]; - } else if (2 === arguments.length) { - // box([], []) - this._ensurePath("box"); - path = this._path; - box = [arguments[0], arguments[1]]; - } else { - throw new TypeError("Invalid argument"); - } +/** + * Adds a required validator to this SchemaType. The validator gets added + * to the front of this SchemaType's validators array using `unshift()`. + * + * ####Example: + * + * const s = new Schema({ born: { type: Date, required: true }) + * + * // or with custom error message + * + * const s = new Schema({ born: { type: Date, required: '{PATH} is required!' }) + * + * // or with a function + * + * const s = new Schema({ + * userId: ObjectId, + * username: { + * type: String, + * required: function() { return this.userId != null; } + * } + * }) + * + * // or with a function and a custom message + * const s = new Schema({ + * userId: ObjectId, + * username: { + * type: String, + * required: [ + * function() { return this.userId != null; }, + * 'username is required if id is specified' + * ] + * } + * }) + * + * // or through the path API + * + * s.path('name').required(true); + * + * // with custom error messaging + * + * s.path('name').required(true, 'grrr :( '); + * + * // or make a path conditionally required based on a function + * const isOver18 = function() { return this.age >= 18; }; + * s.path('voterRegistrationId').required(isOver18); + * + * The required validator uses the SchemaType's `checkRequired` function to + * determine whether a given value satisfies the required validator. By default, + * a value satisfies the required validator if `val != null` (that is, if + * the value is not null nor undefined). However, most built-in mongoose schema + * types override the default `checkRequired` function: + * + * @param {Boolean|Function|Object} required enable/disable the validator, or function that returns required boolean, or options object + * @param {Boolean|Function} [options.isRequired] enable/disable the validator, or function that returns required boolean + * @param {Function} [options.ErrorConstructor] custom error constructor. The constructor receives 1 parameter, an object containing the validator properties. + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @see SchemaArray#checkRequired #schema_array_SchemaArray.checkRequired + * @see SchemaBoolean#checkRequired #schema_boolean_SchemaBoolean-checkRequired + * @see SchemaBuffer#checkRequired #schema_buffer_SchemaBuffer.schemaName + * @see SchemaNumber#checkRequired #schema_number_SchemaNumber-min + * @see SchemaObjectId#checkRequired #schema_objectid_ObjectId-auto + * @see SchemaString#checkRequired #schema_string_SchemaString-checkRequired + * @api public + */ - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds[this._geoComparison || $withinCmd] = { $box: box }; - return this; - }; +SchemaType.prototype.required = function(required, message) { + let customOptions = {}; - /** - * Specifies a $polygon condition - * - * ####Example - * - * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) - * query.polygon('loc', [10,20], [13, 25], [7,15]) - * - * @param {String|Array} [path] - * @param {Array|Object} [val] - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - - Query.prototype.polygon = function () { - var val, path; - - if ("string" == typeof arguments[0]) { - // polygon('loc', [],[],[]) - path = arguments[0]; - val = slice(arguments, 1); - } else { - // polygon([],[],[]) - this._ensurePath("polygon"); - path = this._path; - val = slice(arguments); - } + if (arguments.length > 0 && required == null) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.requiredValidator; + }, this); - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds[this._geoComparison || $withinCmd] = { $polygon: val }; - return this; - }; + this.isRequired = false; + delete this.originalRequiredValue; + return this; + } - /** - * Specifies a $center or $centerSphere condition. - * - * ####Example - * - * var area = { center: [50, 50], radius: 10, unique: true } - * query.where('loc').within().circle(area) - * query.center('loc', area); - * - * // for spherical calculations - * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } - * query.where('loc').within().circle(area) - * query.center('loc', area); - * - * @param {String} [path] - * @param {Object} area - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - - Query.prototype.circle = function () { - var path, val; - - if (1 === arguments.length) { - this._ensurePath("circle"); - path = this._path; - val = arguments[0]; - } else if (2 === arguments.length) { - path = arguments[0]; - val = arguments[1]; - } else { - throw new TypeError("Invalid argument"); - } + if (typeof required === 'object') { + customOptions = required; + message = customOptions.message || message; + required = required.isRequired; + } - if (!("radius" in val && val.center)) - throw new Error("center and radius are required"); + if (required === false) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.requiredValidator; + }, this); - var conds = this._conditions[path] || (this._conditions[path] = {}); + this.isRequired = false; + delete this.originalRequiredValue; + return this; + } - var type = val.spherical ? "$centerSphere" : "$center"; + const _this = this; + this.isRequired = true; - var wKey = this._geoComparison || $withinCmd; - conds[wKey] = {}; - conds[wKey][type] = [val.center, val.radius]; + this.requiredValidator = function(v) { + const cachedRequired = get(this, '$__.cachedRequired'); - if ("unique" in val) conds[wKey].$uniqueDocs = !!val.unique; + // no validation when this path wasn't selected in the query. + if (cachedRequired != null && !this.$__isSelected(_this.path) && !this[documentIsModified](_this.path)) { + return true; + } - return this; - }; + // `$cachedRequired` gets set in `_evaluateRequiredFunctions()` so we + // don't call required functions multiple times in one validate call + // See gh-6801 + if (cachedRequired != null && _this.path in cachedRequired) { + const res = cachedRequired[_this.path] ? + _this.checkRequired(v, this) : + true; + delete cachedRequired[_this.path]; + return res; + } else if (typeof required === 'function') { + return required.apply(this) ? _this.checkRequired(v, this) : true; + } - /** - * Specifies a `$near` or `$nearSphere` condition - * - * These operators return documents sorted by distance. - * - * ####Example - * - * query.where('loc').near({ center: [10, 10] }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); - * query.near('loc', { center: [10, 10], maxDistance: 5 }); - * query.near({ center: { type: 'Point', coordinates: [..] }}) - * query.near().geometry({ type: 'Point', coordinates: [..] }) - * - * @param {String} [path] - * @param {Object} val - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - - Query.prototype.near = function near() { - var path, val; - - this._geoComparison = "$near"; - - if (0 === arguments.length) { - return this; - } else if (1 === arguments.length) { - this._ensurePath("near"); - path = this._path; - val = arguments[0]; - } else if (2 === arguments.length) { - path = arguments[0]; - val = arguments[1]; - } else { - throw new TypeError("Invalid argument"); - } + return _this.checkRequired(v, this); + }; + this.originalRequiredValue = required; - if (!val.center) { - throw new Error("center is required"); - } + if (typeof required === 'string') { + message = required; + required = undefined; + } - var conds = this._conditions[path] || (this._conditions[path] = {}); + const msg = message || MongooseError.messages.general.required; + this.validators.unshift(Object.assign({}, customOptions, { + validator: this.requiredValidator, + message: msg, + type: 'required' + })); - var type = val.spherical ? "$nearSphere" : "$near"; + return this; +}; - // center could be a GeoJSON object or an Array - if (Array.isArray(val.center)) { - conds[type] = val.center; +/** + * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html) + * looks at to determine the foreign collection it should query. + * + * ####Example: + * const userSchema = new Schema({ name: String }); + * const User = mongoose.model('User', userSchema); + * + * const postSchema = new Schema({ user: mongoose.ObjectId }); + * postSchema.path('user').ref('User'); // Can set ref to a model name + * postSchema.path('user').ref(User); // Or a model class + * postSchema.path('user').ref(() => 'User'); // Or a function that returns the model name + * postSchema.path('user').ref(() => User); // Or a function that returns the model class + * + * // Or you can just declare the `ref` inline in your schema + * const postSchema2 = new Schema({ + * user: { type: mongoose.ObjectId, ref: User } + * }); + * + * @param {String|Model|Function} ref either a model name, a [Model](https://mongoosejs.com/docs/models.html), or a function that returns a model name or model. + * @return {SchemaType} this + * @api public + */ - var radius = "maxDistance" in val ? val.maxDistance : null; +SchemaType.prototype.ref = function(ref) { + this.options.ref = ref; + return this; +}; - if (null != radius) { - conds.$maxDistance = radius; - } - if (null != val.minDistance) { - conds.$minDistance = val.minDistance; - } - } else { - // GeoJSON? - if ( - val.center.type != "Point" || - !Array.isArray(val.center.coordinates) - ) { - throw new Error( - util.format("Invalid GeoJSON specified for %s", type) - ); - } - conds[type] = { $geometry: val.center }; +/** + * Gets the default value + * + * @param {Object} scope the scope which callback are executed + * @param {Boolean} init + * @api private + */ - // MongoDB 2.6 insists on maxDistance being in $near / $nearSphere - if ("maxDistance" in val) { - conds[type]["$maxDistance"] = val.maxDistance; - } - if ("minDistance" in val) { - conds[type]["$minDistance"] = val.minDistance; - } - } +SchemaType.prototype.getDefault = function(scope, init) { + let ret; + if (typeof this.defaultValue === 'function') { + if ( + this.defaultValue === Date.now || + this.defaultValue === Array || + this.defaultValue.name.toLowerCase() === 'objectid' + ) { + ret = this.defaultValue.call(scope); + } else { + ret = this.defaultValue.call(scope, scope); + } + } else { + ret = this.defaultValue; + } - return this; - }; - /** - * Declares an intersects query for `geometry()`. - * - * ####Example - * - * query.where('path').intersects().geometry({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * query.where('path').intersects({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * @param {Object} [arg] - * @return {Query} this - * @api public - */ - - Query.prototype.intersects = function intersects() { - // opinionated, must be used after where - this._ensurePath("intersects"); - - this._geoComparison = "$geoIntersects"; - - if (0 === arguments.length) { - return this; - } + if (ret !== null && ret !== undefined) { + if (typeof ret === 'object' && (!this.options || !this.options.shared)) { + ret = utils.clone(ret); + } - var area = arguments[0]; + const casted = this.applySetters(ret, scope, init); + if (casted && casted.$isSingleNested) { + casted.$__parent = scope; + } + return casted; + } + return ret; +}; - if (null != area && area.type && area.coordinates) - return this.geometry(area); +/*! + * Applies setters without casting + * + * @api private + */ - throw new TypeError("Invalid argument"); - }; +SchemaType.prototype._applySetters = function(value, scope, init, priorVal) { + let v = value; + if (init) { + return v; + } + const setters = this.setters; - /** - * Specifies a `$geometry` condition - * - * ####Example - * - * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] - * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) - * - * // or - * var polyB = [[ 0, 0 ], [ 1, 1 ]] - * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) - * - * // or - * var polyC = [ 0, 0 ] - * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) - * - * // or - * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) - * - * ####NOTE: - * - * `geometry()` **must** come after either `intersects()` or `within()`. - * - * The `object` argument must contain `type` and `coordinates` properties. - * - type {String} - * - coordinates {Array} - * - * The most recent path passed to `where()` is used. - * - * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. - * @return {Query} this - * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @api public - */ - - Query.prototype.geometry = function geometry() { - if ( - !( - "$within" == this._geoComparison || - "$geoWithin" == this._geoComparison || - "$near" == this._geoComparison || - "$geoIntersects" == this._geoComparison - ) - ) { - throw new Error( - "geometry() must come after `within()`, `intersects()`, or `near()" - ); - } + for (let i = setters.length - 1; i >= 0; i--) { + v = setters[i].call(scope, v, priorVal, this); + } - var val, path; + return v; +}; - if (1 === arguments.length) { - this._ensurePath("geometry"); - path = this._path; - val = arguments[0]; - } else { - throw new TypeError("Invalid argument"); - } +/*! + * ignore + */ - if (!(val.type && Array.isArray(val.coordinates))) { - throw new TypeError("Invalid argument"); - } +SchemaType.prototype._castNullish = function _castNullish(v) { + return v; +}; - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds[this._geoComparison] = { $geometry: val }; +/** + * Applies setters + * + * @param {Object} value + * @param {Object} scope + * @param {Boolean} init + * @api private + */ - return this; - }; +SchemaType.prototype.applySetters = function(value, scope, init, priorVal, options) { + let v = this._applySetters(value, scope, init, priorVal, options); + if (v == null) { + return this._castNullish(v); + } - // end spatial - - /** - * Specifies which document fields to include or exclude - * - * ####String syntax - * - * When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. - * - * ####Example - * - * // include a and b, exclude c - * query.select('a b -c'); - * - * // or you may use object notation, useful when - * // you have keys already prefixed with a "-" - * query.select({a: 1, b: 1, c: 0}); - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object|String} arg - * @return {Query} this - * @see SchemaType - * @api public - */ - - Query.prototype.select = function select() { - var arg = arguments[0]; - if (!arg) return this; - - if (arguments.length !== 1) { - throw new Error("Invalid select: select only takes 1 argument"); - } - - this._validate("select"); - - var fields = this._fields || (this._fields = {}); - var type = typeof arg; - var i, len; + // do not cast until all setters are applied #665 + v = this.cast(v, scope, init, priorVal, options); - if ( - (("string" == type || utils.isArgumentsObject(arg)) && - "number" == typeof arg.length) || - Array.isArray(arg) - ) { - if ("string" == type) arg = arg.split(/\s+/); - - for (i = 0, len = arg.length; i < len; ++i) { - var field = arg[i]; - if (!field) continue; - var include = "-" == field[0] ? 0 : 1; - if (include === 0) field = field.substring(1); - fields[field] = include; - } + return v; +}; - return this; - } +/** + * Applies getters to a value + * + * @param {Object} value + * @param {Object} scope + * @api private + */ - if (utils.isObject(arg)) { - var keys = utils.keys(arg); - for (i = 0; i < keys.length; ++i) { - fields[keys[i]] = arg[keys[i]]; - } - return this; - } +SchemaType.prototype.applyGetters = function(value, scope) { + let v = value; + const getters = this.getters; + const len = getters.length; - throw new TypeError( - "Invalid select() argument. Must be string or object." - ); - }; + if (len === 0) { + return v; + } - /** - * Specifies a $slice condition for a `path` - * - * ####Example - * - * query.slice('comments', 5) - * query.slice('comments', -5) - * query.slice('comments', [10, 5]) - * query.where('comments').slice(5) - * query.where('comments').slice([-10, 5]) - * - * @param {String} [path] - * @param {Number} val number/range of elements to slice - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements - * @api public - */ - - Query.prototype.slice = function () { - if (0 === arguments.length) return this; - - this._validate("slice"); - - var path, val; - - if (1 === arguments.length) { - var arg = arguments[0]; - if (typeof arg === "object" && !Array.isArray(arg)) { - var keys = Object.keys(arg); - var numKeys = keys.length; - for (var i = 0; i < numKeys; ++i) { - this.slice(keys[i], arg[keys[i]]); - } - return this; - } - this._ensurePath("slice"); - path = this._path; - val = arguments[0]; - } else if (2 === arguments.length) { - if ("number" === typeof arguments[0]) { - this._ensurePath("slice"); - path = this._path; - val = slice(arguments); - } else { - path = arguments[0]; - val = arguments[1]; - } - } else if (3 === arguments.length) { - path = arguments[0]; - val = slice(arguments, 1); - } + for (let i = 0; i < len; ++i) { + v = getters[i].call(scope, v, this); + } - var myFields = this._fields || (this._fields = {}); - myFields[path] = { $slice: val }; - return this; - }; + return v; +}; - /** - * Sets the sort order - * - * If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1. - * - * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. - * - * ####Example - * - * // these are equivalent - * query.sort({ field: 'asc', test: -1 }); - * query.sort('field -test'); - * query.sort([['field', 1], ['test', -1]]); - * - * ####Note - * - * - The array syntax `.sort([['field', 1], ['test', -1]])` can only be used with [mongodb driver >= 2.0.46](https://github.com/mongodb/node-mongodb-native/blob/2.1/HISTORY.md#2046-2015-10-15). - * - Cannot be used with `distinct()` - * - * @param {Object|String|Array} arg - * @return {Query} this - * @api public - */ - - Query.prototype.sort = function (arg) { - if (!arg) return this; - var i, len, field; - - this._validate("sort"); - - var type = typeof arg; - - // .sort([['field', 1], ['test', -1]]) - if (Array.isArray(arg)) { - len = arg.length; - for (i = 0; i < arg.length; ++i) { - if (!Array.isArray(arg[i])) { - throw new Error( - "Invalid sort() argument, must be array of arrays" - ); - } - _pushArr(this.options, arg[i][0], arg[i][1]); - } - return this; - } +/** + * Sets default `select()` behavior for this path. + * + * Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level. + * + * ####Example: + * + * T = db.model('T', new Schema({ x: { type: String, select: true }})); + * T.find(..); // field x will always be selected .. + * // .. unless overridden; + * T.find().select('-x').exec(callback); + * + * @param {Boolean} val + * @return {SchemaType} this + * @api public + */ - // .sort('field -test') - if (1 === arguments.length && "string" == type) { - arg = arg.split(/\s+/); - len = arg.length; - for (i = 0; i < len; ++i) { - field = arg[i]; - if (!field) continue; - var ascend = "-" == field[0] ? -1 : 1; - if (ascend === -1) field = field.substring(1); - push(this.options, field, ascend); - } +SchemaType.prototype.select = function select(val) { + this.selected = !!val; + return this; +}; - return this; - } +/** + * Performs a validation of `value` using the validators declared for this SchemaType. + * + * @param {any} value + * @param {Function} callback + * @param {Object} scope + * @api private + */ - // .sort({ field: 1, test: -1 }) - if (utils.isObject(arg)) { - var keys = utils.keys(arg); - for (i = 0; i < keys.length; ++i) { - field = keys[i]; - push(this.options, field, arg[field]); - } +SchemaType.prototype.doValidate = function(value, fn, scope, options) { + let err = false; + const path = this.path; - return this; - } + // Avoid non-object `validators` + const validators = this.validators. + filter(v => v != null && typeof v === 'object'); - if (typeof Map !== "undefined" && arg instanceof Map) { - _pushMap(this.options, arg); - return this; - } - throw new TypeError( - "Invalid sort() argument. Must be a string, object, or array." - ); - }; + let count = validators.length; - /*! - * @ignore - */ - - var _validSortValue = { - 1: 1, - "-1": -1, - asc: 1, - ascending: 1, - desc: -1, - descending: -1, - }; + if (!count) { + return fn(null); + } - function push(opts, field, value) { - if (Array.isArray(opts.sort)) { - throw new TypeError( - "Can't mix sort syntaxes. Use either array or object:" + - "\n- `.sort([['field', 1], ['test', -1]])`" + - "\n- `.sort({ field: 1, test: -1 })`" - ); - } + const _this = this; + validators.forEach(function(v) { + if (err) { + return; + } - var s; - if (value && value.$meta) { - s = opts.sort || (opts.sort = {}); - s[field] = { $meta: value.$meta }; - return; - } + const validator = v.validator; + let ok; - s = opts.sort || (opts.sort = {}); - var val = String(value || 1).toLowerCase(); - val = _validSortValue[val]; - if (!val) - throw new TypeError( - "Invalid sort value: { " + field + ": " + value + " }" - ); + const validatorProperties = utils.clone(v); + validatorProperties.path = options && options.path ? options.path : path; + validatorProperties.value = value; - s[field] = val; - } + if (validator instanceof RegExp) { + validate(validator.test(value), validatorProperties); + return; + } - function _pushArr(opts, field, value) { - opts.sort = opts.sort || []; - if (!Array.isArray(opts.sort)) { - throw new TypeError( - "Can't mix sort syntaxes. Use either array or object:" + - "\n- `.sort([['field', 1], ['test', -1]])`" + - "\n- `.sort({ field: 1, test: -1 })`" - ); - } + if (typeof validator !== 'function') { + return; + } - var val = String(value || 1).toLowerCase(); - val = _validSortValue[val]; - if (!val) - throw new TypeError( - "Invalid sort value: [ " + field + ", " + value + " ]" - ); + if (value === undefined && validator !== _this.requiredValidator) { + validate(true, validatorProperties); + return; + } - opts.sort.push([field, val]); + try { + if (validatorProperties.propsParameter) { + ok = validator.call(scope, value, validatorProperties); + } else { + ok = validator.call(scope, value); } + } catch (error) { + ok = false; + validatorProperties.reason = error; + if (error.message) { + validatorProperties.message = error.message; + } + } - function _pushMap(opts, map) { - opts.sort = opts.sort || new Map(); - if (!(opts.sort instanceof Map)) { - throw new TypeError( - "Can't mix sort syntaxes. Use either array or " + - "object or map consistently" - ); - } - map.forEach(function (value, key) { - var val = String(value || 1).toLowerCase(); - val = _validSortValue[val]; - if (!val) - throw new TypeError( - "Invalid sort value: < " + key + ": " + value + " >" - ); + if (ok != null && typeof ok.then === 'function') { + ok.then( + function(ok) { validate(ok, validatorProperties); }, + function(error) { + validatorProperties.reason = error; + validatorProperties.message = error.message; + ok = false; + validate(ok, validatorProperties); + }); + } else { + validate(ok, validatorProperties); + } - opts.sort.set(key, val); + }); + + function validate(ok, validatorProperties) { + if (err) { + return; + } + if (ok === undefined || ok) { + if (--count <= 0) { + immediate(function() { + fn(null); }); } - - /** - * Specifies the limit option. - * - * ####Example - * - * query.limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method limit - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D - * @api public - */ - /** - * Specifies the skip option. - * - * ####Example - * - * query.skip(100).limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method skip - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D - * @api public - */ - /** - * Specifies the maxScan option. - * - * ####Example - * - * query.maxScan(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method maxScan - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan - * @api public - */ - /** - * Specifies the batchSize option. - * - * ####Example - * - * query.batchSize(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method batchSize - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D - * @api public - */ - /** - * Specifies the `comment` option. - * - * ####Example - * - * query.comment('login query') - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method comment - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment - * @api public - */ - - /*! - * limit, skip, maxScan, batchSize, comment - * - * Sets these associated options. - * - * query.comment('feed query'); - */ - - ["limit", "skip", "maxScan", "batchSize", "comment"].forEach(function ( - method - ) { - Query.prototype[method] = function (v) { - this._validate(method); - this.options[method] = v; - return this; - }; + } else { + const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; + err = new ErrorConstructor(validatorProperties); + err[validatorErrorSymbol] = true; + immediate(function() { + fn(err); }); + } + } +}; - /** - * Specifies the maxTimeMS option. - * - * ####Example - * - * query.maxTime(100) - * query.maxTimeMS(100) - * - * @method maxTime - * @memberOf Query - * @param {Number} ms - * @see mongodb http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS - * @api public - */ - - Query.prototype.maxTime = Query.prototype.maxTimeMS = function (ms) { - this._validate("maxTime"); - this.options.maxTimeMS = ms; - return this; - }; +/** + * Performs a validation of `value` using the validators declared for this SchemaType. + * + * ####Note: + * + * This method ignores the asynchronous validators. + * + * @param {any} value + * @param {Object} scope + * @return {MongooseError|undefined} + * @api private + */ - /** - * Specifies this query as a `snapshot` query. - * - * ####Example - * - * mquery().snapshot() // true - * mquery().snapshot(true) - * mquery().snapshot(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D - * @return {Query} this - * @api public - */ - - Query.prototype.snapshot = function () { - this._validate("snapshot"); - - this.options.snapshot = arguments.length ? !!arguments[0] : true; +SchemaType.prototype.doValidateSync = function(value, scope, options) { + const path = this.path; + const count = this.validators.length; - return this; - }; + if (!count) { + return null; + } - /** - * Sets query hints. - * - * ####Example - * - * query.hint({ indexA: 1, indexB: -1}); - * query.hint('indexA_1_indexB_1'); - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object|string} val a hint object or the index name - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint - * @api public - */ - - Query.prototype.hint = function () { - if (0 === arguments.length) return this; - - this._validate("hint"); - - var arg = arguments[0]; - if (utils.isObject(arg)) { - var hint = this.options.hint || (this.options.hint = {}); - - // must keep object keys in order so don't use Object.keys() - for (var k in arg) { - hint[k] = arg[k]; - } + let validators = this.validators; + if (value === void 0) { + if (this.validators.length > 0 && this.validators[0].type === 'required') { + validators = [this.validators[0]]; + } else { + return null; + } + } - return this; - } - if (typeof arg === "string") { - this.options.hint = arg; - return this; - } + let err = null; + validators.forEach(function(v) { + if (err) { + return; + } - throw new TypeError("Invalid hint. " + arg); - }; + if (v == null || typeof v !== 'object') { + return; + } - /** - * Requests acknowledgement that this operation has been persisted to MongoDB's - * on-disk journal. - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the `j` value if it is specified in writeConcern options - * - * ####Example: - * - * mquery().w(2).j(true).wtimeout(2000); - * - * @method j - * @memberOf Query - * @instance - * @param {boolean} val - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#j-option - * @return {Query} this - * @api public - */ - - Query.prototype.j = function j(val) { - this.options.j = val; - return this; - }; + const validator = v.validator; + const validatorProperties = utils.clone(v); + validatorProperties.path = options && options.path ? options.path : path; + validatorProperties.value = value; + let ok; - /** - * Sets the slaveOk option. _Deprecated_ in MongoDB 2.2 in favor of read preferences. - * - * ####Example: - * - * query.slaveOk() // true - * query.slaveOk(true) - * query.slaveOk(false) - * - * @deprecated use read() preferences instead if on mongodb >= 2.2 - * @param {Boolean} v defaults to true - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see read() - * @return {Query} this - * @api public - */ - - Query.prototype.slaveOk = function (v) { - this.options.slaveOk = arguments.length ? !!v : true; - return this; - }; + // Skip any explicit async validators. Validators that return a promise + // will still run, but won't trigger any errors. + if (isAsyncFunction(validator)) { + return; + } - /** - * Sets the readPreference option for the query. - * - * ####Example: - * - * new Query().read('primary') - * new Query().read('p') // same as primary - * - * new Query().read('primaryPreferred') - * new Query().read('pp') // same as primaryPreferred - * - * new Query().read('secondary') - * new Query().read('s') // same as secondary - * - * new Query().read('secondaryPreferred') - * new Query().read('sp') // same as secondaryPreferred - * - * new Query().read('nearest') - * new Query().read('n') // same as nearest - * - * // you can also use mongodb.ReadPreference class to also specify tags - * new Query().read(mongodb.ReadPreference('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])) - * - * new Query().setReadPreference('primary') // alias of .read() - * - * ####Preferences: - * - * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. - * secondary Read from secondary if available, otherwise error. - * primaryPreferred Read from primary if available, otherwise a secondary. - * secondaryPreferred Read from a secondary if available, otherwise read from the primary. - * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. - * - * Aliases - * - * p primary - * pp primaryPreferred - * s secondary - * sp secondaryPreferred - * n nearest - * - * Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). - * - * @param {String|ReadPreference} pref one of the listed preference options or their aliases - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences - * @return {Query} this - * @api public - */ - - Query.prototype.read = Query.prototype.setReadPreference = function ( - pref - ) { - if ( - arguments.length > 1 && - !Query.prototype.read.deprecationWarningIssued - ) { - console.error( - "Deprecation warning: 'tags' argument is not supported anymore in Query.read() method. Please use mongodb.ReadPreference object instead." - ); - Query.prototype.read.deprecationWarningIssued = true; - } - this.options.readPreference = utils.readPref(pref); - return this; - }; + if (validator instanceof RegExp) { + validate(validator.test(value), validatorProperties); + return; + } - /** - * Sets the readConcern option for the query. - * - * ####Example: - * - * new Query().readConcern('local') - * new Query().readConcern('l') // same as local - * - * new Query().readConcern('available') - * new Query().readConcern('a') // same as available - * - * new Query().readConcern('majority') - * new Query().readConcern('m') // same as majority - * - * new Query().readConcern('linearizable') - * new Query().readConcern('lz') // same as linearizable - * - * new Query().readConcern('snapshot') - * new Query().readConcern('s') // same as snapshot - * - * new Query().r('s') // r is alias of readConcern - * - * - * ####Read Concern Level: - * - * local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). - * available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). - * majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. - * linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. - * snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. + if (typeof validator !== 'function') { + return; + } + try { + if (validatorProperties.propsParameter) { + ok = validator.call(scope, value, validatorProperties); + } else { + ok = validator.call(scope, value); + } + } catch (error) { + ok = false; + validatorProperties.reason = error; + } + // Skip any validators that return a promise, we can't handle those + // synchronously + if (ok != null && typeof ok.then === 'function') { + return; + } + validate(ok, validatorProperties); + }); + + return err; + + function validate(ok, validatorProperties) { + if (err) { + return; + } + if (ok !== undefined && !ok) { + const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; + err = new ErrorConstructor(validatorProperties); + err[validatorErrorSymbol] = true; + } + } +}; + +/** + * Determines if value is a valid Reference. * - * - * Aliases - * - * l local - * a available - * m majority - * lz linearizable - * s snapshot - * - * Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/). - * - * @param {String} level one of the listed read concern level or their aliases - * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/ - * @return {Query} this - * @api public + * @param {SchemaType} self + * @param {Object} value + * @param {Document} doc + * @param {Boolean} init + * @return {Boolean} + * @api private */ - Query.prototype.readConcern = Query.prototype.r = function (level) { - this.options.readConcern = utils.readConcern(level); - return this; - }; - - /** - * Sets tailable option. - * - * ####Example - * - * query.tailable() <== true - * query.tailable(true) - * query.tailable(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Boolean} v defaults to true - * @see mongodb http://www.mongodb.org/display/DOCS/Tailable+Cursors - * @api public - */ - - Query.prototype.tailable = function () { - this._validate("tailable"); - - this.options.tailable = arguments.length ? !!arguments[0] : true; +SchemaType._isRef = function(self, value, doc, init) { + // fast path + let ref = init && self.options && (self.options.ref || self.options.refPath); - return this; - }; + if (!ref && doc && doc.$__ != null) { + // checks for + // - this populated with adhoc model and no ref was set in schema OR + // - setting / pushing values after population + const path = doc.$__fullPath(self.path, true); - /** - * Sets the specified number of `mongod` servers, or tag set of `mongod` servers, - * that must acknowledge this write before this write is considered successful. - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the `w` value if it is specified in writeConcern options - * - * ####Example: - * - * mquery().writeConcern(0) - * mquery().writeConcern(1) - * mquery().writeConcern({ w: 1, j: true, wtimeout: 2000 }) - * mquery().writeConcern('majority') - * mquery().writeConcern('m') // same as majority - * mquery().writeConcern('tagSetName') // if the tag set is 'm', use .writeConcern({ w: 'm' }) instead - * mquery().w(1) // w is alias of writeConcern - * - * @method writeConcern - * @memberOf Query - * @instance - * @param {String|number|object} concern 0 for fire-and-forget, 1 for acknowledged by one server, 'majority' for majority of the replica set, or [any of the more advanced options](https://docs.mongodb.com/manual/reference/write-concern/#w-option). - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#w-option - * @return {Query} this - * @api public - */ - - Query.prototype.writeConcern = Query.prototype.w = function writeConcern( - concern - ) { - if ("object" === typeof concern) { - if ("undefined" !== typeof concern.j) this.options.j = concern.j; - if ("undefined" !== typeof concern.w) this.options.w = concern.w; - if ("undefined" !== typeof concern.wtimeout) - this.options.wtimeout = concern.wtimeout; - } else { - this.options.w = "m" === concern ? "majority" : concern; - } - return this; - }; + const owner = doc.ownerDocument(); + ref = (path != null && owner.$populated(path)) || doc.$populated(self.path); + } - /** - * Specifies a time limit, in milliseconds, for the write concern. - * If `ms > 1`, it is maximum amount of time to wait for this write - * to propagate through the replica set before this operation fails. - * The default is `0`, which means no timeout. - * - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to `wtimeout` value if it is specified in writeConcern - * - * ####Example: - * - * mquery().w(2).j(true).wtimeout(2000) - * - * @method wtimeout - * @memberOf Query - * @instance - * @param {number} ms number of milliseconds to wait - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#wtimeout - * @return {Query} this - * @api public - */ - - Query.prototype.wtimeout = Query.prototype.wTimeout = function wtimeout( - ms - ) { - this.options.wtimeout = ms; - return this; - }; + if (ref) { + if (value == null) { + return true; + } + if (!Buffer.isBuffer(value) && // buffers are objects too + value._bsontype !== 'Binary' // raw binary value from the db + && utils.isObject(value) // might have deselected _id in population query + ) { + return true; + } - /** - * Merges another Query or conditions object into this one. - * - * When a Query is passed, conditions, field selection and options are merged. - * - * @param {Query|Object} source - * @return {Query} this - */ - - Query.prototype.merge = function (source) { - if (!source) return this; - - if (!Query.canMerge(source)) - throw new TypeError( - "Invalid argument. Expected instanceof mquery or plain object" - ); + return init; + } - if (source instanceof Query) { - // if source has a feature, apply it to ourselves + return false; +}; - if (source._conditions) { - utils.merge(this._conditions, source._conditions); - } +/*! + * ignore + */ - if (source._fields) { - this._fields || (this._fields = {}); - utils.merge(this._fields, source._fields); - } +SchemaType.prototype._castRef = function _castRef(value, doc, init) { + if (value == null) { + return value; + } - if (source.options) { - this.options || (this.options = {}); - utils.merge(this.options, source.options); - } + if (value.$__ != null) { + value.$__.wasPopulated = true; + return value; + } - if (source._update) { - this._update || (this._update = {}); - utils.mergeClone(this._update, source._update); - } + // setting a populated path + if (Buffer.isBuffer(value) || !utils.isObject(value)) { + if (init) { + return value; + } + throw new CastError(this.instance, value, this.path, null, this); + } - if (source._distinct) { - this._distinct = source._distinct; - } + // Handle the case where user directly sets a populated + // path to a plain object; cast to the Model used in + // the population query. + const path = doc.$__fullPath(this.path, true); + const owner = doc.ownerDocument(); + const pop = owner.$populated(path, true); + let ret = value; + if (!doc.$__.populated || + !doc.$__.populated[path] || + !doc.$__.populated[path].options || + !doc.$__.populated[path].options.options || + !doc.$__.populated[path].options.options.lean) { + ret = new pop.options[populateModelSymbol](value); + ret.$__.wasPopulated = true; + } - return this; - } + return ret; +}; - // plain object - utils.merge(this._conditions, source); +/*! + * ignore + */ - return this; - }; +function handleSingle(val) { + return this.castForQuery(val); +} - /** - * Finds documents. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * query.find() - * query.find(callback) - * query.find({ name: 'Burning Lights' }, callback) - * - * @param {Object} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - - Query.prototype.find = function (criteria, callback) { - this.op = "find"; - - if ("function" === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } +/*! + * ignore + */ - if (!callback) return this; +function handleArray(val) { + const _this = this; + if (!Array.isArray(val)) { + return [this.castForQuery(val)]; + } + return val.map(function(m) { + return _this.castForQuery(m); + }); +} + +/*! + * Just like handleArray, except also allows `[]` because surprisingly + * `$in: [1, []]` works fine + */ - var conds = this._conditions; - var options = this._optionsForExec(); +function handle$in(val) { + const _this = this; + if (!Array.isArray(val)) { + return [this.castForQuery(val)]; + } + return val.map(function(m) { + if (Array.isArray(m) && m.length === 0) { + return m; + } + return _this.castForQuery(m); + }); +} - if (this.$useProjection) { - options.projection = this._fieldsForExec(); - } else { - options.fields = this._fieldsForExec(); - } +/*! + * ignore + */ - debug("find", this._collection.collectionName, conds, options); - callback = this._wrapCallback("find", callback, { - conditions: conds, - options: options, - }); +SchemaType.prototype.$conditionalHandlers = { + $all: handleArray, + $eq: handleSingle, + $in: handle$in, + $ne: handleSingle, + $nin: handle$in, + $exists: $exists, + $type: $type +}; + +/*! + * Wraps `castForQuery` to handle context + */ - this._collection.find(conds, options, utils.tick(callback)); - return this; - }; +SchemaType.prototype.castForQueryWrapper = function(params) { + this.$$context = params.context; + if ('$conditional' in params) { + const ret = this.castForQuery(params.$conditional, params.val); + this.$$context = null; + return ret; + } + if (params.$skipQueryCastForUpdate || params.$applySetters) { + const ret = this._castForQuery(params.val); + this.$$context = null; + return ret; + } - /** - * Returns the query cursor - * - * ####Examples - * - * query.find().cursor(); - * query.cursor({ name: 'Burning Lights' }); - * - * @param {Object} [criteria] mongodb selector - * @return {Object} cursor - * @api public - */ - - Query.prototype.cursor = function cursor(criteria) { - if (this.op) { - if (this.op !== "find") { - throw new TypeError(".cursor only support .find method"); - } - } else { - this.find(criteria); - } + const ret = this.castForQuery(params.val); + this.$$context = null; + return ret; +}; - var conds = this._conditions; - var options = this._optionsForExec(); +/** + * Cast the given value with the given optional query operator. + * + * @param {String} [$conditional] query operator, like `$eq` or `$in` + * @param {any} val + * @api private + */ - if (this.$useProjection) { - options.projection = this._fieldsForExec(); - } else { - options.fields = this._fieldsForExec(); - } +SchemaType.prototype.castForQuery = function($conditional, val) { + let handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional); + } + return handler.call(this, val); + } + val = $conditional; + return this._castForQuery(val); +}; - debug("findCursor", this._collection.collectionName, conds, options); - return this._collection.findCursor(conds, options); - }; +/*! + * Internal switch for runSetters + * + * @api private + */ - /** - * Executes the query as a findOne() operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * query.findOne().where('name', /^Burning/); - * - * query.findOne({ name: /^Burning/ }) - * - * query.findOne({ name: /^Burning/ }, callback); // executes - * - * query.findOne(function (err, doc) { - * if (err) return handleError(err); - * if (doc) { - * // doc may be null if no document matched - * - * } - * }); - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - - Query.prototype.findOne = function (criteria, callback) { - this.op = "findOne"; - - if ("function" === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } +SchemaType.prototype._castForQuery = function(val) { + return this.applySetters(val, this.$$context); +}; - if (!callback) return this; +/** + * Override the function the required validator uses to check whether a value + * passes the `required` check. Override this on the individual SchemaType. + * + * ####Example: + * + * // Use this to allow empty strings to pass the `required` validator + * mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string'); + * + * @param {Function} fn + * @return {Function} + * @static + * @receiver SchemaType + * @function checkRequired + * @api public + */ - var conds = this._conditions; - var options = this._optionsForExec(); +SchemaType.checkRequired = function(fn) { + if (arguments.length > 0) { + this._checkRequired = fn; + } - if (this.$useProjection) { - options.projection = this._fieldsForExec(); - } else { - options.fields = this._fieldsForExec(); - } + return this._checkRequired; +}; - debug("findOne", this._collection.collectionName, conds, options); - callback = this._wrapCallback("findOne", callback, { - conditions: conds, - options: options, - }); +/** + * Default check for if this path satisfies the `required` validator. + * + * @param {any} val + * @api private + */ - this._collection.findOne(conds, options, utils.tick(callback)); +SchemaType.prototype.checkRequired = function(val) { + return val != null; +}; - return this; - }; +/*! + * ignore + */ - /** - * Exectues the query as a count() operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * query.count().where('color', 'black').exec(callback); - * - * query.count({ color: 'black' }).count(callback) - * - * query.count({ color: 'black' }, callback) - * - * query.where('color', 'black').count(function (err, count) { - * if (err) return handleError(err); - * console.log('there are %d kittens', count); - * }) - * - * @param {Object} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Count - * @api public - */ - - Query.prototype.count = function (criteria, callback) { - this.op = "count"; - this._validate(); - - if ("function" === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } +SchemaType.prototype.clone = function() { + const options = Object.assign({}, this.options); + const schematype = new this.constructor(this.path, options, this.instance); + schematype.validators = this.validators.slice(); + if (this.requiredValidator !== undefined) schematype.requiredValidator = this.requiredValidator; + if (this.defaultValue !== undefined) schematype.defaultValue = this.defaultValue; + if (this.$immutable !== undefined && this.options.immutable === undefined) { + schematype.$immutable = this.$immutable; - if (!callback) return this; + handleImmutable(schematype); + } + if (this._index !== undefined) schematype._index = this._index; + if (this.selected !== undefined) schematype.selected = this.selected; + if (this.isRequired !== undefined) schematype.isRequired = this.isRequired; + if (this.originalRequiredValue !== undefined) schematype.originalRequiredValue = this.originalRequiredValue; + schematype.getters = this.getters.slice(); + schematype.setters = this.setters.slice(); + return schematype; +}; + +/*! + * Module exports. + */ - var conds = this._conditions, - options = this._optionsForExec(); +module.exports = exports = SchemaType; - debug("count", this._collection.collectionName, conds, options); - callback = this._wrapCallback("count", callback, { - conditions: conds, - options: options, - }); +exports.CastError = CastError; - this._collection.count(conds, options, utils.tick(callback)); - return this; - }; +exports.ValidatorError = ValidatorError; - /** - * Declares or executes a distinct() operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * distinct(criteria, field, fn) - * distinct(criteria, field) - * distinct(field, fn) - * distinct(field) - * distinct(fn) - * distinct() - * - * @param {Object|Query} [criteria] - * @param {String} [field] - * @param {Function} [callback] - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct - * @api public - */ - - Query.prototype.distinct = function (criteria, field, callback) { - this.op = "distinct"; - this._validate(); - if (!callback) { - switch (typeof field) { - case "function": - callback = field; - if ("string" == typeof criteria) { - field = criteria; - criteria = undefined; - } - break; - case "undefined": - case "string": - break; - default: - throw new TypeError( - "Invalid `field` argument. Must be string or function" - ); - } +/***/ }), - switch (typeof criteria) { - case "function": - callback = criteria; - criteria = field = undefined; - break; - case "string": - field = criteria; - criteria = undefined; - break; - } - } +/***/ 3532: +/***/ ((module, exports, __nccwpck_require__) => { - if ("string" == typeof field) { - this._distinct = field; - } +"use strict"; - if (Query.canMerge(criteria)) { - this.merge(criteria); - } +/*! + * Module dependencies. + */ - if (!callback) { - return this; - } - if (!this._distinct) { - throw new Error("No value for `distinct` has been declared"); - } - var conds = this._conditions, - options = this._optionsForExec(); +const utils = __nccwpck_require__(9232); - debug("distinct", this._collection.collectionName, conds, options); - callback = this._wrapCallback("distinct", callback, { - conditions: conds, - options: options, - }); +/*! + * StateMachine represents a minimal `interface` for the + * constructors it builds via StateMachine.ctor(...). + * + * @api private + */ - this._collection.distinct( - this._distinct, - conds, - options, - utils.tick(callback) - ); +const StateMachine = module.exports = exports = function StateMachine() { +}; - return this; - }; +/*! + * StateMachine.ctor('state1', 'state2', ...) + * A factory method for subclassing StateMachine. + * The arguments are a list of states. For each state, + * the constructor's prototype gets state transition + * methods named after each state. These transition methods + * place their path argument into the given state. + * + * @param {String} state + * @param {String} [state] + * @return {Function} subclass constructor + * @private + */ - /** - * Declare and/or execute this query as an update() operation. By default, - * `update()` only modifies the _first_ document that matches `criteria`. - * - * _All paths passed that are not $atomic operations will become $set ops._ - * - * ####Example - * - * mquery({ _id: id }).update({ title: 'words' }, ...) - * - * becomes - * - * collection.update({ _id: id }, { $set: { title: 'words' }}, ...) - * - * ####Note - * - * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. - * - * ####Note - * - * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method. - * - * var q = mquery(collection).where({ _id: id }); - * q.update({ $set: { name: 'bob' }}).update(); // not executed - * - * var q = mquery(collection).where({ _id: id }); - * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe - * - * // keys that are not $atomic ops become $set. - * // this executes the same command as the previous example. - * q.update({ name: 'bob' }).where({ _id: id }).exec(); - * - * var q = mquery(collection).update(); // not executed - * - * // overwriting with empty docs - * var q.where({ _id: id }).setOptions({ overwrite: true }) - * q.update({ }, callback); // executes - * - * // multi update with overwrite to empty doc - * var q = mquery(collection).where({ _id: id }); - * q.setOptions({ multi: true, overwrite: true }) - * q.update({ }); - * q.update(callback); // executed - * - * // multi updates - * mquery() - * .collection(coll) - * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) - * // more multi updates - * mquery({ }) - * .collection(coll) - * .setOptions({ multi: true }) - * .update({ $set: { arr: [] }}, callback) - * - * // single update by default - * mquery({ email: 'address@example.com' }) - * .collection(coll) - * .update({ $inc: { counter: 1 }}, callback) - * - * // summary - * update(criteria, doc, opts, cb) // executes - * update(criteria, doc, opts) - * update(criteria, doc, cb) // executes - * update(criteria, doc) - * update(doc, cb) // executes - * update(doc) - * update(cb) // executes - * update(true) // executes (unsafe write) - * update() - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - - Query.prototype.update = function update( - criteria, - doc, - options, - callback - ) { - var force; - - switch (arguments.length) { - case 3: - if ("function" == typeof options) { - callback = options; - options = undefined; - } - break; - case 2: - if ("function" == typeof doc) { - callback = doc; - doc = criteria; - criteria = undefined; - } - break; - case 1: - switch (typeof criteria) { - case "function": - callback = criteria; - criteria = options = doc = undefined; - break; - case "boolean": - // execution with no callback (unsafe write) - force = criteria; - criteria = undefined; - break; - default: - doc = criteria; - criteria = options = undefined; - break; - } - } +StateMachine.ctor = function() { + const states = utils.args(arguments); - return _update(this, "update", criteria, doc, options, force, callback); - }; + const ctor = function() { + StateMachine.apply(this, arguments); + this.paths = {}; + this.states = {}; + this.stateNames = states; - /** - * Declare and/or execute this query as an `updateMany()` operation. Identical - * to `update()` except `updateMany()` will update _all_ documents that match - * `criteria`, rather than just the first one. - * - * _All paths passed that are not $atomic operations will become $set ops._ - * - * ####Example - * - * // Update every document whose `title` contains 'test' - * mquery().updateMany({ title: /test/ }, { year: 2017 }) - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - - Query.prototype.updateMany = function updateMany( - criteria, - doc, - options, - callback - ) { - var force; - - switch (arguments.length) { - case 3: - if ("function" == typeof options) { - callback = options; - options = undefined; - } - break; - case 2: - if ("function" == typeof doc) { - callback = doc; - doc = criteria; - criteria = undefined; - } - break; - case 1: - switch (typeof criteria) { - case "function": - callback = criteria; - criteria = options = doc = undefined; - break; - case "boolean": - // execution with no callback (unsafe write) - force = criteria; - criteria = undefined; - break; - default: - doc = criteria; - criteria = options = undefined; - break; - } - } + let i = states.length, + state; - return _update( - this, - "updateMany", - criteria, - doc, - options, - force, - callback - ); - }; + while (i--) { + state = states[i]; + this.states[state] = {}; + } + }; - /** - * Declare and/or execute this query as an `updateOne()` operation. Identical - * to `update()` except `updateOne()` will _always_ update just one document, - * regardless of the `multi` option. - * - * _All paths passed that are not $atomic operations will become $set ops._ - * - * ####Example - * - * // Update the first document whose `title` contains 'test' - * mquery().updateMany({ title: /test/ }, { year: 2017 }) - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - - Query.prototype.updateOne = function updateOne( - criteria, - doc, - options, - callback - ) { - var force; - - switch (arguments.length) { - case 3: - if ("function" == typeof options) { - callback = options; - options = undefined; - } - break; - case 2: - if ("function" == typeof doc) { - callback = doc; - doc = criteria; - criteria = undefined; - } - break; - case 1: - switch (typeof criteria) { - case "function": - callback = criteria; - criteria = options = doc = undefined; - break; - case "boolean": - // execution with no callback (unsafe write) - force = criteria; - criteria = undefined; - break; - default: - doc = criteria; - criteria = options = undefined; - break; - } - } + ctor.prototype = new StateMachine(); - return _update( - this, - "updateOne", - criteria, - doc, - options, - force, - callback - ); - }; + states.forEach(function(state) { + // Changes the `path`'s state to `state`. + ctor.prototype[state] = function(path) { + this._changeState(path, state); + }; + }); - /** - * Declare and/or execute this query as an `replaceOne()` operation. Similar - * to `updateOne()`, except `replaceOne()` is not allowed to use atomic - * modifiers (`$set`, `$push`, etc.). Calling `replaceOne()` will always - * replace the existing doc. - * - * ####Example - * - * // Replace the document with `_id` 1 with `{ _id: 1, year: 2017 }` - * mquery().replaceOne({ _id: 1 }, { year: 2017 }) - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - - Query.prototype.replaceOne = function replaceOne( - criteria, - doc, - options, - callback - ) { - var force; - - switch (arguments.length) { - case 3: - if ("function" == typeof options) { - callback = options; - options = undefined; - } - break; - case 2: - if ("function" == typeof doc) { - callback = doc; - doc = criteria; - criteria = undefined; - } - break; - case 1: - switch (typeof criteria) { - case "function": - callback = criteria; - criteria = options = doc = undefined; - break; - case "boolean": - // execution with no callback (unsafe write) - force = criteria; - criteria = undefined; - break; - default: - doc = criteria; - criteria = options = undefined; - break; - } - } + return ctor; +}; - this.setOptions({ overwrite: true }); - return _update( - this, - "replaceOne", - criteria, - doc, - options, - force, - callback - ); - }; +/*! + * This function is wrapped by the state change functions: + * + * - `require(path)` + * - `modify(path)` + * - `init(path)` + * + * @api private + */ - /*! - * Internal helper for update, updateMany, updateOne - */ +StateMachine.prototype._changeState = function _changeState(path, nextState) { + const prevBucket = this.states[this.paths[path]]; + if (prevBucket) delete prevBucket[path]; - function _update(query, op, criteria, doc, options, force, callback) { - query.op = op; + this.paths[path] = nextState; + this.states[nextState][path] = true; +}; - if (Query.canMerge(criteria)) { - query.merge(criteria); - } +/*! + * ignore + */ - if (doc) { - query._mergeUpdate(doc); - } +StateMachine.prototype.clear = function clear(state) { + const keys = Object.keys(this.states[state]); + let i = keys.length; + let path; - if (utils.isObject(options)) { - // { overwrite: true } - query.setOptions(options); - } + while (i--) { + path = keys[i]; + delete this.states[state][path]; + delete this.paths[path]; + } +}; - // we are done if we don't have callback and they are - // not forcing an unsafe write. - if (!(force || callback)) { - return query; - } +/*! + * Checks to see if at least one path is in the states passed in via `arguments` + * e.g., this.some('required', 'inited') + * + * @param {String} state that we want to check for. + * @private + */ - if ( - !query._update || - (!query.options.overwrite && 0 === utils.keys(query._update).length) - ) { - callback && utils.soon(callback.bind(null, null, 0)); - return query; - } +StateMachine.prototype.some = function some() { + const _this = this; + const what = arguments.length ? arguments : this.stateNames; + return Array.prototype.some.call(what, function(state) { + return Object.keys(_this.states[state]).length; + }); +}; + +/*! + * This function builds the functions that get assigned to `forEach` and `map`, + * since both of those methods share a lot of the same logic. + * + * @param {String} iterMethod is either 'forEach' or 'map' + * @return {Function} + * @api private + */ - options = query._optionsForExec(); - if (!callback) options.safe = false; +StateMachine.prototype._iter = function _iter(iterMethod) { + return function() { + const numArgs = arguments.length; + let states = utils.args(arguments, 0, numArgs - 1); + const callback = arguments[numArgs - 1]; - criteria = query._conditions; - doc = query._updateForExec(); + if (!states.length) states = this.stateNames; - debug( - "update", - query._collection.collectionName, - criteria, - doc, - options - ); - callback = query._wrapCallback(op, callback, { - conditions: criteria, - doc: doc, - options: options, - }); + const _this = this; - query._collection[op](criteria, doc, options, utils.tick(callback)); - - return query; - } - - /** - * Declare and/or execute this query as a remove() operation. - * - * ####Example - * - * mquery(collection).remove({ artist: 'Anne Murray' }, callback) - * - * ####Note - * - * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the `exec()` method. - * - * // not executed - * var query = mquery(collection).remove({ name: 'Anne Murray' }) - * - * // executed - * mquery(collection).remove({ name: 'Anne Murray' }, callback) - * mquery(collection).remove({ name: 'Anne Murray' }).remove(callback) - * - * // executed without a callback (unsafe write) - * query.exec() - * - * // summary - * query.remove(conds, fn); // executes - * query.remove(conds) - * query.remove(fn) // executes - * query.remove() - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - - Query.prototype.remove = function (criteria, callback) { - this.op = "remove"; - var force; - - if ("function" === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } else if (true === criteria) { - force = criteria; - criteria = undefined; - } + const paths = states.reduce(function(paths, state) { + return paths.concat(Object.keys(_this.states[state])); + }, []); + + return paths[iterMethod](function(path, i, paths) { + return callback(path, i, paths); + }); + }; +}; - if (!(force || callback)) return this; +/*! + * Iterates over the paths that belong to one of the parameter states. + * + * The function profile can look like: + * this.forEach(state1, fn); // iterates over all paths in state1 + * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 + * this.forEach(fn); // iterates over all paths in all states + * + * @param {String} [state] + * @param {String} [state] + * @param {Function} callback + * @private + */ - var options = this._optionsForExec(); - if (!callback) options.safe = false; +StateMachine.prototype.forEach = function forEach() { + this.forEach = this._iter('forEach'); + return this.forEach.apply(this, arguments); +}; - var conds = this._conditions; +/*! + * Maps over the paths that belong to one of the parameter states. + * + * The function profile can look like: + * this.forEach(state1, fn); // iterates over all paths in state1 + * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 + * this.forEach(fn); // iterates over all paths in all states + * + * @param {String} [state] + * @param {String} [state] + * @param {Function} callback + * @return {Array} + * @private + */ - debug("remove", this._collection.collectionName, conds, options); - callback = this._wrapCallback("remove", callback, { - conditions: conds, - options: options, - }); +StateMachine.prototype.map = function map() { + this.map = this._iter('map'); + return this.map.apply(this, arguments); +}; - this._collection.remove(conds, options, utils.tick(callback)); - return this; - }; +/***/ }), - /** - * Declare and/or execute this query as a `deleteOne()` operation. Behaves like - * `remove()`, except for ignores the `justOne` option and always deletes at - * most one document. - * - * ####Example - * - * mquery(collection).deleteOne({ artist: 'Anne Murray' }, callback) - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - - Query.prototype.deleteOne = function (criteria, callback) { - this.op = "deleteOne"; - var force; - - if ("function" === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } else if (true === criteria) { - force = criteria; - criteria = undefined; - } +/***/ 9999: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!(force || callback)) return this; +"use strict"; +/* eslint no-func-assign: 1 */ - var options = this._optionsForExec(); - if (!callback) options.safe = false; - delete options.justOne; +/*! + * Module dependencies. + */ - var conds = this._conditions; - debug("deleteOne", this._collection.collectionName, conds, options); - callback = this._wrapCallback("deleteOne", callback, { - conditions: conds, - options: options, - }); - this._collection.deleteOne(conds, options, utils.tick(callback)); +const EventEmitter = __nccwpck_require__(8614).EventEmitter; +const Subdocument = __nccwpck_require__(7302); +const get = __nccwpck_require__(8730); - return this; - }; +const documentArrayParent = __nccwpck_require__(3240).documentArrayParent; - /** - * Declare and/or execute this query as a `deleteMany()` operation. Behaves like - * `remove()`, except for ignores the `justOne` option and always deletes - * _every_ document that matches `criteria`. - * - * ####Example - * - * mquery(collection).deleteMany({ artist: 'Anne Murray' }, callback) - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - - Query.prototype.deleteMany = function (criteria, callback) { - this.op = "deleteMany"; - var force; - - if ("function" === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } else if (true === criteria) { - force = criteria; - criteria = undefined; - } +/** + * A constructor. + * + * @param {Object} obj js object returned from the db + * @param {MongooseDocumentArray} parentArr the parent array of this document + * @param {Boolean} skipId + * @inherits Document + * @api private + */ - if (!(force || callback)) return this; +function ArraySubdocument(obj, parentArr, skipId, fields, index) { + if (parentArr != null && parentArr.isMongooseDocumentArray) { + this.__parentArray = parentArr; + this[documentArrayParent] = parentArr.$parent(); + } else { + this.__parentArray = undefined; + this[documentArrayParent] = undefined; + } + this.$setIndex(index); + this.$__parent = this[documentArrayParent]; - var options = this._optionsForExec(); - if (!callback) options.safe = false; - delete options.justOne; + Subdocument.call(this, obj, fields, this[documentArrayParent], void 0, { isNew: true }); +} - var conds = this._conditions; +/*! + * Inherit from Subdocument + */ +ArraySubdocument.prototype = Object.create(Subdocument.prototype); +ArraySubdocument.prototype.constructor = ArraySubdocument; + +Object.defineProperty(ArraySubdocument.prototype, '$isSingleNested', { + configurable: false, + writable: false, + value: false +}); + +Object.defineProperty(ArraySubdocument.prototype, '$isDocumentArrayElement', { + configurable: false, + writable: false, + value: true +}); + +for (const i in EventEmitter.prototype) { + ArraySubdocument[i] = EventEmitter.prototype[i]; +} + +/*! + * ignore + */ - debug("deleteOne", this._collection.collectionName, conds, options); - callback = this._wrapCallback("deleteOne", callback, { - conditions: conds, - options: options, - }); +ArraySubdocument.prototype.$setIndex = function(index) { + this.__index = index; - this._collection.deleteMany(conds, options, utils.tick(callback)); + if (get(this, '$__.validationError', null) != null) { + const keys = Object.keys(this.$__.validationError.errors); + for (const key of keys) { + this.invalidate(key, this.$__.validationError.errors[key]); + } + } +}; - return this; - }; +/*! + * ignore + */ - /** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. - * - * ####Available options - * - * - `new`: bool - true to return the modified document rather than the original. defaults to true - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - * ####Examples - * - * query.findOneAndUpdate(conditions, update, options, callback) // executes - * query.findOneAndUpdate(conditions, update, options) // returns Query - * query.findOneAndUpdate(conditions, update, callback) // executes - * query.findOneAndUpdate(conditions, update) // returns Query - * query.findOneAndUpdate(update, callback) // returns Query - * query.findOneAndUpdate(update) // returns Query - * query.findOneAndUpdate(callback) // executes - * query.findOneAndUpdate() // returns Query - * - * @param {Object|Query} [query] - * @param {Object} [doc] - * @param {Object} [options] - * @param {Function} [callback] - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @return {Query} this - * @api public - */ - - Query.prototype.findOneAndUpdate = function ( - criteria, - doc, - options, - callback - ) { - this.op = "findOneAndUpdate"; - this._validate(); - - switch (arguments.length) { - case 3: - if ("function" == typeof options) { - callback = options; - options = {}; - } - break; - case 2: - if ("function" == typeof doc) { - callback = doc; - doc = criteria; - criteria = undefined; - } - options = undefined; - break; - case 1: - if ("function" == typeof criteria) { - callback = criteria; - criteria = options = doc = undefined; - } else { - doc = criteria; - criteria = options = undefined; - } - } +ArraySubdocument.prototype.populate = function() { + throw new Error('Mongoose does not support calling populate() on nested ' + + 'docs. Instead of `doc.arr[0].populate("path")`, use ' + + '`doc.populate("arr.0.path")`'); +}; - if (Query.canMerge(criteria)) { - this.merge(criteria); - } +/*! + * ignore + */ - // apply doc - if (doc) { - this._mergeUpdate(doc); - } +ArraySubdocument.prototype.$__removeFromParent = function() { + const _id = this._doc._id; + if (!_id) { + throw new Error('For your own good, Mongoose does not know ' + + 'how to remove an ArraySubdocument that has no _id'); + } + this.__parentArray.pull({ _id: _id }); +}; - options && this.setOptions(options); +/** + * Returns the full path to this document. If optional `path` is passed, it is appended to the full path. + * + * @param {String} [path] + * @param {Boolean} [skipIndex] Skip adding the array index. For example `arr.foo` instead of `arr.0.foo`. + * @return {String} + * @api private + * @method $__fullPath + * @memberOf ArraySubdocument + * @instance + */ - if (!callback) return this; - return this._findAndModify("update", callback); - }; +ArraySubdocument.prototype.$__fullPath = function(path, skipIndex) { + if (this.__index == null) { + return null; + } + if (!this.$__.fullPath) { + this.ownerDocument(); + } - /** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. - * - * ####Available options - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - * ####Examples - * - * A.where().findOneAndRemove(conditions, options, callback) // executes - * A.where().findOneAndRemove(conditions, options) // return Query - * A.where().findOneAndRemove(conditions, callback) // executes - * A.where().findOneAndRemove(conditions) // returns Query - * A.where().findOneAndRemove(callback) // executes - * A.where().findOneAndRemove() // returns Query - * A.where().findOneAndDelete() // alias of .findOneAndRemove() - * - * @param {Object} [conditions] - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - - Query.prototype.findOneAndRemove = Query.prototype.findOneAndDelete = - function (conditions, options, callback) { - this.op = "findOneAndRemove"; - this._validate(); - - if ("function" == typeof options) { - callback = options; - options = undefined; - } else if ("function" == typeof conditions) { - callback = conditions; - conditions = undefined; - } + if (skipIndex) { + return path ? + this.$__.fullPath + '.' + path : + this.$__.fullPath; + } - // apply conditions - if (Query.canMerge(conditions)) { - this.merge(conditions); - } + return path ? + this.$__.fullPath + '.' + this.__index + '.' + path : + this.$__.fullPath + '.' + this.__index; +}; - // apply options - options && this.setOptions(options); +/*! + * Given a path relative to this document, return the path relative + * to the top-level document. + */ - if (!callback) return this; +ArraySubdocument.prototype.$__pathRelativeToParent = function(path, skipIndex) { + if (this.__index == null) { + return null; + } + if (skipIndex) { + return path == null ? this.__parentArray.$path() : this.__parentArray.$path() + '.' + path; + } + if (path == null) { + return this.__parentArray.$path() + '.' + this.__index; + } + return this.__parentArray.$path() + '.' + this.__index + '.' + path; +}; - return this._findAndModify("remove", callback); - }; +/*! + * Returns this sub-documents parent document. + */ - /** - * _findAndModify - * - * @param {String} type - either "remove" or "update" - * @param {Function} callback - * @api private - */ +ArraySubdocument.prototype.$parent = function() { + return this[documentArrayParent]; +}; - Query.prototype._findAndModify = function (type, callback) { - assert.equal("function", typeof callback); +/** + * Returns this sub-documents parent array. + * + * @api public + */ - var options = this._optionsForExec(); - var fields; - var doc; +ArraySubdocument.prototype.parentArray = function() { + return this.__parentArray; +}; - if ("remove" == type) { - options.remove = true; - } else { - if (!("new" in options)) options.new = true; - if (!("upsert" in options)) options.upsert = false; - - doc = this._updateForExec(); - if (!doc) { - if (options.upsert) { - // still need to do the upsert to empty doc - doc = { $set: {} }; - } else { - return this.findOne(callback); - } - } - } +/*! + * Module exports. + */ - fields = this._fieldsForExec(); - if (fields != null) { - if (this.$useProjection) { - options.projection = this._fieldsForExec(); - } else { - options.fields = this._fieldsForExec(); - } - } +module.exports = ArraySubdocument; - var conds = this._conditions; - debug( - "findAndModify", - this._collection.collectionName, - conds, - doc, - options - ); - callback = this._wrapCallback("findAndModify", callback, { - conditions: conds, - doc: doc, - options: options, - }); +/***/ }), - this._collection.findAndModify( - conds, - doc, - options, - utils.tick(callback) - ); +/***/ 3369: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return this; - }; +"use strict"; - /** - * Wrap callback to add tracing - * - * @param {Function} callback - * @param {Object} [queryInfo] - * @api private - */ - Query.prototype._wrapCallback = function (method, callback, queryInfo) { - var traceFunction = this._traceFunction || Query.traceFunction; - if (traceFunction) { - queryInfo.collectionName = this._collection.collectionName; +/*! + * Module dependencies. + */ - var traceCallback = - traceFunction && traceFunction.call(null, method, queryInfo, this); +const ArrayMethods = __nccwpck_require__(3919); +const DocumentArrayMethods = __nccwpck_require__(4152); +const Document = __nccwpck_require__(6717); - var startTime = new Date().getTime(); +const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; +const arrayAtomicsBackupSymbol = __nccwpck_require__(3240).arrayAtomicsBackupSymbol; +const arrayParentSymbol = __nccwpck_require__(3240).arrayParentSymbol; +const arrayPathSymbol = __nccwpck_require__(3240).arrayPathSymbol; +const arraySchemaSymbol = __nccwpck_require__(3240).arraySchemaSymbol; - return function wrapperCallback(err, result) { - if (traceCallback) { - var millis = new Date().getTime() - startTime; - traceCallback.call(null, err, result, millis); - } +const _basePush = Array.prototype.push; - if (callback) { - callback.apply(null, arguments); - } - }; - } +/** + * DocumentArray constructor + * + * @param {Array} values + * @param {String} path the path to this array + * @param {Document} doc parent document + * @api private + * @return {MongooseDocumentArray} + * @inherits MongooseArray + * @see http://bit.ly/f6CnZU + */ - return callback; - }; +function MongooseDocumentArray(values, path, doc) { + const arr = []; - /** - * Add trace function that gets called when the query is executed. - * The function will be called with (method, queryInfo, query) and - * should return a callback function which will be called - * with (err, result, millis) when the query is complete. - * - * queryInfo is an object containing: { - * collectionName: , - * conditions: , - * options: , - * doc: [document to update, if applicable] - * } - * - * NOTE: Does not trace stream queries. - * - * @param {Function} traceFunction - * @return {Query} this - * @api public - */ - Query.prototype.setTraceFunction = function (traceFunction) { - this._traceFunction = traceFunction; - return this; - }; + const internals = { + [arrayAtomicsSymbol]: {}, + [arrayAtomicsBackupSymbol]: void 0, + [arrayPathSymbol]: path, + [arraySchemaSymbol]: void 0, + [arrayParentSymbol]: void 0 + }; - /** - * Executes the query - * - * ####Examples - * - * query.exec(); - * query.exec(callback); - * query.exec('update'); - * query.exec('find', callback); - * - * @param {String|Function} [operation] - * @param {Function} [callback] - * @api public - */ - - Query.prototype.exec = function exec(op, callback) { - switch (typeof op) { - case "function": - callback = op; - op = null; - break; - case "string": - this.op = op; - break; - } + if (Array.isArray(values)) { + if (values[arrayPathSymbol] === path && + values[arrayParentSymbol] === doc) { + internals[arrayAtomicsSymbol] = Object.assign({}, values[arrayAtomicsSymbol]); + } + values.forEach(v => { + _basePush.call(arr, v); + }); + } + internals[arrayPathSymbol] = path; + + // Because doc comes from the context of another function, doc === global + // can happen if there was a null somewhere up the chain (see #3020 && #3034) + // RB Jun 17, 2015 updated to check for presence of expected paths instead + // to make more proof against unusual node environments + if (doc && doc instanceof Document) { + internals[arrayParentSymbol] = doc; + internals[arraySchemaSymbol] = doc.schema.path(path); + + // `schema.path()` doesn't drill into nested arrays properly yet, see + // gh-6398, gh-6602. This is a workaround because nested arrays are + // always plain non-document arrays, so once you get to a document array + // nesting is done. Matryoshka code. + while (internals[arraySchemaSymbol] != null && + internals[arraySchemaSymbol].$isMongooseArray && + !internals[arraySchemaSymbol].$isMongooseDocumentArray) { + internals[arraySchemaSymbol] = internals[arraySchemaSymbol].casterConstructor; + } + } - assert.ok(this.op, "Missing query type: (find, update, etc)"); + const proxy = new Proxy(arr, { + get: function(target, prop) { + if (prop === 'isMongooseArray' || + prop === 'isMongooseArrayProxy' || + prop === 'isMongooseDocumentArray' || + prop === 'isMongooseDocumentArrayProxy') { + return true; + } + if (prop === '__array') { + return arr; + } + if (prop === 'set') { + return set; + } + if (internals.hasOwnProperty(prop)) { + return internals[prop]; + } + if (DocumentArrayMethods.hasOwnProperty(prop)) { + return DocumentArrayMethods[prop]; + } + if (ArrayMethods.hasOwnProperty(prop)) { + return ArrayMethods[prop]; + } - if ("update" == this.op || "remove" == this.op) { - callback || (callback = true); - } + return arr[prop]; + }, + set: function(target, prop, value) { + if (typeof prop === 'string' && /^\d+$/.test(prop)) { + set.call(proxy, prop, value); + } else if (internals.hasOwnProperty(prop)) { + internals[prop] = value; + } else { + arr[prop] = value; + } - var _this = this; + return true; + } + }); - if ("function" == typeof callback) { - this[this.op](callback); - } else { - return new Query.Promise(function (success, error) { - _this[_this.op](function (err, val) { - if (err) error(err); - else success(val); - success = error = null; - }); - }); - } - }; + return proxy; +} - /** - * Returns a thunk which when called runs this.exec() - * - * The thunk receives a callback function which will be - * passed to `this.exec()` - * - * @return {Function} - * @api public - */ - - Query.prototype.thunk = function () { - var _this = this; - return function (cb) { - _this.exec(cb); - }; - }; +function set(i, val, skipModified) { + const arr = this.__array; + if (skipModified) { + arr[i] = val; + return arr; + } + const value = DocumentArrayMethods._cast.call(this, val, i); + arr[i] = value; + DocumentArrayMethods._markModified.call(this, i); + return arr; +} + +/*! + * Module exports. + */ - /** - * Executes the query returning a `Promise` which will be - * resolved with either the doc(s) or rejected with the error. - * - * @param {Function} [resolve] - * @param {Function} [reject] - * @return {Promise} - * @api public - */ - - Query.prototype.then = function (resolve, reject) { - var _this = this; - var promise = new Query.Promise(function (success, error) { - _this.exec(function (err, val) { - if (err) error(err); - else success(val); - success = error = null; - }); - }); - return promise.then(resolve, reject); - }; +module.exports = MongooseDocumentArray; - /** - * Returns a stream for the given find query. - * - * @throws Error if operation is not a find - * @returns {Stream} Node 0.8 style - */ - Query.prototype.stream = function (streamOptions) { - if ("find" != this.op) - throw new Error("stream() is only available for find"); +/***/ }), - var conds = this._conditions; +/***/ 4152: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var options = this._optionsForExec(); - if (this.$useProjection) { - options.projection = this._fieldsForExec(); - } else { - options.fields = this._fieldsForExec(); - } +"use strict"; - debug( - "stream", - this._collection.collectionName, - conds, - options, - streamOptions - ); - return this._collection.findStream(conds, options, streamOptions); - }; +const ArrayMethods = __nccwpck_require__(3919); +const Document = __nccwpck_require__(6717); +const ObjectId = __nccwpck_require__(2706); +const castObjectId = __nccwpck_require__(5552); +const getDiscriminatorByValue = __nccwpck_require__(8689); +const internalToObjectOptions = __nccwpck_require__(5684)/* .internalToObjectOptions */ .h; +const utils = __nccwpck_require__(9232); - /** - * Determines if field selection has been made. - * - * @return {Boolean} - * @api public - */ +const arrayParentSymbol = __nccwpck_require__(3240).arrayParentSymbol; +const arrayPathSymbol = __nccwpck_require__(3240).arrayPathSymbol; +const arraySchemaSymbol = __nccwpck_require__(3240).arraySchemaSymbol; +const documentArrayParent = __nccwpck_require__(3240).documentArrayParent; - Query.prototype.selected = function selected() { - return !!(this._fields && Object.keys(this._fields).length > 0); - }; +const methods = { + /*! + * ignore + */ - /** - * Determines if inclusive field selection has been made. - * - * query.selectedInclusively() // false - * query.select('name') - * query.selectedInclusively() // true - * query.selectedExlusively() // false - * - * @returns {Boolean} - */ - - Query.prototype.selectedInclusively = function selectedInclusively() { - if (!this._fields) return false; - - var keys = Object.keys(this._fields); - if (0 === keys.length) return false; - - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (0 === this._fields[key]) return false; - if ( - this._fields[key] && - typeof this._fields[key] === "object" && - this._fields[key].$meta - ) { - return false; - } - } + toBSON() { + return this.toObject(internalToObjectOptions); + }, - return true; - }; + /** + * Overrides MongooseArray#cast + * + * @method _cast + * @api private + * @receiver MongooseDocumentArray + */ - /** - * Determines if exclusive field selection has been made. - * - * query.selectedExlusively() // false - * query.select('-name') - * query.selectedExlusively() // true - * query.selectedInclusively() // false - * - * @returns {Boolean} - */ + _cast(value, index) { + if (this[arraySchemaSymbol] == null) { + return value; + } + let Constructor = this[arraySchemaSymbol].casterConstructor; + const isInstance = Constructor.$isMongooseDocumentArray ? + value && value.isMongooseDocumentArray : + value instanceof Constructor; + if (isInstance || + // Hack re: #5001, see #5005 + (value && value.constructor && value.constructor.baseCasterConstructor === Constructor)) { + if (!(value[documentArrayParent] && value.__parentArray)) { + // value may have been created using array.create() + value[documentArrayParent] = this[arrayParentSymbol]; + value.__parentArray = this; + } + value.$setIndex(index); + return value; + } - Query.prototype.selectedExclusively = function selectedExclusively() { - if (!this._fields) return false; + if (value === undefined || value === null) { + return null; + } - var keys = Object.keys(this._fields); - if (0 === keys.length) return false; + // handle cast('string') or cast(ObjectId) etc. + // only objects are permitted so we can safely assume that + // non-objects are to be interpreted as _id + if (Buffer.isBuffer(value) || + value instanceof ObjectId || !utils.isObject(value)) { + value = { _id: value }; + } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (0 === this._fields[key]) return true; + if (value && + Constructor.discriminators && + Constructor.schema && + Constructor.schema.options && + Constructor.schema.options.discriminatorKey) { + if (typeof value[Constructor.schema.options.discriminatorKey] === 'string' && + Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]) { + Constructor = Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]; + } else { + const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, value[Constructor.schema.options.discriminatorKey]); + if (constructorByValue) { + Constructor = constructorByValue; } + } + } - return false; - }; + if (Constructor.$isMongooseDocumentArray) { + return Constructor.cast(value, this, undefined, undefined, index); + } + const ret = new Constructor(value, this, undefined, undefined, index); + ret.isNew = true; + return ret; + }, + + /** + * Searches array items for the first document with a matching _id. + * + * ####Example: + * + * const embeddedDoc = m.array.id(some_id); + * + * @return {EmbeddedDocument|null} the subdocument or null if not found. + * @param {ObjectId|String|Number|Buffer} id + * @TODO cast to the _id based on schema for proper comparison + * @method id + * @api public + * @memberOf MongooseDocumentArray + */ + + id(id) { + let casted; + let sid; + let _id; + + try { + casted = castObjectId(id).toString(); + } catch (e) { + casted = null; + } - /** - * Merges `doc` with the current update object. - * - * @param {Object} doc - */ - - Query.prototype._mergeUpdate = function (doc) { - if (!this._update) this._update = {}; - if (doc instanceof Query) { - if (doc._update) { - utils.mergeClone(this._update, doc._update); - } - } else { - utils.mergeClone(this._update, doc); - } - }; + for (const val of this) { + if (!val) { + continue; + } - /** - * Returns default options. - * - * @return {Object} - * @api private - */ + _id = val.get('_id'); - Query.prototype._optionsForExec = function () { - var options = utils.clone(this.options); - return options; - }; + if (_id === null || typeof _id === 'undefined') { + continue; + } else if (_id instanceof Document) { + sid || (sid = String(id)); + if (sid == _id._id) { + return val; + } + } else if (!(id instanceof ObjectId) && !(_id instanceof ObjectId)) { + if (id == _id || utils.deepEqual(id, _id)) { + return val; + } + } else if (casted == _id) { + return val; + } + } + + return null; + }, + + /** + * Returns a native js Array of plain js objects + * + * ####NOTE: + * + * _Each sub-document is converted to a plain object by calling its `#toObject` method._ + * + * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion + * @return {Array} + * @method toObject + * @api public + * @memberOf MongooseDocumentArray + */ + + toObject(options) { + // `[].concat` coerces the return value into a vanilla JS array, rather + // than a Mongoose array. + return [].concat(this.map(function(doc) { + if (doc == null) { + return null; + } + if (typeof doc.toObject !== 'function') { + return doc; + } + return doc.toObject(options); + })); + }, + + $toObject() { + return this.constructor.prototype.toObject.apply(this, arguments); + }, + + /** + * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. + * + * @param {Object} [args...] + * @api public + * @method push + * @memberOf MongooseDocumentArray + */ + + push() { + const ret = ArrayMethods.push.apply(this, arguments); + + _updateParentPopulated(this); + + return ret; + }, + + /** + * Pulls items from the array atomically. + * + * @param {Object} [args...] + * @api public + * @method pull + * @memberOf MongooseDocumentArray + */ + + pull() { + const ret = ArrayMethods.pull.apply(this, arguments); + + _updateParentPopulated(this); + + return ret; + }, + + /*! + * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. + */ + + shift() { + const ret = ArrayMethods.shift.apply(this, arguments); + + _updateParentPopulated(this); + + return ret; + }, + + /*! + * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. + */ + + splice() { + const ret = ArrayMethods.splice.apply(this, arguments); + + _updateParentPopulated(this); + + return ret; + }, + + /** + * Helper for console.log + * + * @method inspect + * @api public + * @memberOf MongooseDocumentArray + */ + + inspect() { + return this.toObject(); + }, + + /** + * Creates a subdocument casted to this schema. + * + * This is the same subdocument constructor used for casting. + * + * @param {Object} obj the value to cast to this arrays SubDocument schema + * @method create + * @api public + * @memberOf MongooseDocumentArray + */ + + create(obj) { + let Constructor = this[arraySchemaSymbol].casterConstructor; + if (obj && + Constructor.discriminators && + Constructor.schema && + Constructor.schema.options && + Constructor.schema.options.discriminatorKey) { + if (typeof obj[Constructor.schema.options.discriminatorKey] === 'string' && + Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) { + Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]; + } else { + const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, obj[Constructor.schema.options.discriminatorKey]); + if (constructorByValue) { + Constructor = constructorByValue; + } + } + } - /** - * Returns fields selection for this query. - * - * @return {Object} - * @api private - */ + return new Constructor(obj, this); + }, - Query.prototype._fieldsForExec = function () { - return utils.clone(this._fields); - }; + /*! + * ignore + */ - /** - * Return an update document with corrected $set operations. - * - * @api private - */ + notify(event) { + const _this = this; + return function notify(val, _arr) { + _arr = _arr || _this; + let i = _arr.length; + while (i--) { + if (_arr[i] == null) { + continue; + } + switch (event) { + // only swap for save event for now, we may change this to all event types later + case 'save': + val = _this[i]; + break; + default: + // NO-OP + break; + } - Query.prototype._updateForExec = function () { - var update = utils.clone(this._update), - ops = utils.keys(update), - i = ops.length, - ret = {}; + if (_arr[i].isMongooseArray) { + notify(val, _arr[i]); + } else if (_arr[i]) { + _arr[i].emit(event, val); + } + } + }; + }, - while (i--) { - var op = ops[i]; + _markModified(elem, embeddedPath) { + const parent = this[arrayParentSymbol]; + let dirtyPath; - if (this.options.overwrite) { - ret[op] = update[op]; - continue; - } + if (parent) { + dirtyPath = this[arrayPathSymbol]; - if ("$" !== op[0]) { - // fix up $set sugar - if (!ret.$set) { - if (update.$set) { - ret.$set = update.$set; - } else { - ret.$set = {}; - } - } - ret.$set[op] = update[op]; - ops.splice(i, 1); - if (!~ops.indexOf("$set")) ops.push("$set"); - } else if ("$set" === op) { - if (!ret.$set) { - ret[op] = update[op]; - } - } else { - ret[op] = update[op]; - } + if (arguments.length) { + if (embeddedPath != null) { + // an embedded doc bubbled up the change + const index = elem.__index; + dirtyPath = dirtyPath + '.' + index + '.' + embeddedPath; + } else { + // directly set an index + dirtyPath = dirtyPath + '.' + elem; } + } + + if (dirtyPath != null && dirtyPath.endsWith('.$')) { + return this; + } - this._compiledUpdate = ret; - return ret; - }; + parent.markModified(dirtyPath, arguments.length > 0 ? elem : parent); + } - /** - * Make sure _path is set. - * - * @parmam {String} method - */ + return this; + } +}; - Query.prototype._ensurePath = function (method) { - if (!this._path) { - var msg = - method + - "() must be used after where() " + - "when called with these arguments"; - throw new Error(msg); - } - }; +module.exports = methods; - /*! - * Permissions - */ +/*! + * If this is a document array, each element may contain single + * populated paths, so we need to modify the top-level document's + * populated cache. See gh-8247, gh-8265. + */ - Query.permissions = __nccwpck_require__(6615); +function _updateParentPopulated(arr) { + const parent = arr[arrayParentSymbol]; + if (!parent || parent.$__.populated == null) return; - Query._isPermitted = function (a, b) { - var denied = Query.permissions[b]; - if (!denied) return true; - return true !== denied[a]; - }; + const populatedPaths = Object.keys(parent.$__.populated). + filter(p => p.startsWith(arr[arrayPathSymbol] + '.')); - Query.prototype._validate = function (action) { - var fail; - var validator; + for (const path of populatedPaths) { + const remnant = path.slice((arr[arrayPathSymbol] + '.').length); + if (!Array.isArray(parent.$__.populated[path].value)) { + continue; + } - if (undefined === action) { - validator = Query.permissions[this.op]; - if ("function" != typeof validator) return true; + parent.$__.populated[path].value = arr.map(val => val.$populated(remnant)); + } +} - fail = validator(this); - } else if (!Query._isPermitted(action, this.op)) { - fail = action; - } +/***/ }), - if (fail) { - throw new Error(fail + " cannot be used with " + this.op); - } - }; +/***/ 1089: +/***/ ((module, exports, __nccwpck_require__) => { - /** - * Determines if `conds` can be merged using `mquery().merge()` - * - * @param {Object} conds - * @return {Boolean} - */ +"use strict"; +/*! + * Module dependencies. + */ - Query.canMerge = function (conds) { - return conds instanceof Query || utils.isObject(conds); - }; - /** - * Set a trace function that will get called whenever a - * query is executed. - * - * See `setTraceFunction()` for details. - * - * @param {Object} conds - * @return {Boolean} - */ - Query.setGlobalTraceFunction = function (traceFunction) { - Query.traceFunction = traceFunction; - }; - /*! - * Exports. - */ +const Document = __nccwpck_require__(6717); +const mongooseArrayMethods = __nccwpck_require__(3919); - Query.utils = utils; - Query.env = __nccwpck_require__(5928); - Query.Collection = __nccwpck_require__(5680); - Query.BaseCollection = __nccwpck_require__(5257); - Query.Promise = __nccwpck_require__(5404); - module.exports = exports = Query; +const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; +const arrayAtomicsBackupSymbol = __nccwpck_require__(3240).arrayAtomicsBackupSymbol; +const arrayParentSymbol = __nccwpck_require__(3240).arrayParentSymbol; +const arrayPathSymbol = __nccwpck_require__(3240).arrayPathSymbol; +const arraySchemaSymbol = __nccwpck_require__(3240).arraySchemaSymbol; - // TODO - // test utils +/** + * Mongoose Array constructor. + * + * ####NOTE: + * + * _Values always have to be passed to the constructor to initialize, otherwise `MongooseArray#push` will mark the array as modified._ + * + * @param {Array} values + * @param {String} path + * @param {Document} doc parent document + * @api private + * @inherits Array + * @see http://bit.ly/f6CnZU + */ - /***/ - }, +function MongooseArray(values, path, doc, schematype) { + let arr; + if (Array.isArray(values)) { + const len = values.length; + + // Perf optimizations for small arrays: much faster to use `...` than `for` + `push`, + // but large arrays may cause stack overflows. And for arrays of length 0/1, just + // modifying the array is faster. Seems small, but adds up when you have a document + // with thousands of nested arrays. + if (len === 0) { + arr = new Array(); + } else if (len === 1) { + arr = new Array(1); + arr[0] = values[0]; + } else if (len < 10000) { + arr = new Array(); + arr.push.apply(arr, values); + } else { + arr = new Array(); + for (let i = 0; i < len; ++i) { + arr.push(values[i]); + } + } + } else { + arr = []; + } - /***/ 6615: /***/ (__unused_webpack_module, exports) => { - "use strict"; + const internals = { + [arrayAtomicsSymbol]: {}, + [arrayAtomicsBackupSymbol]: void 0, + [arrayPathSymbol]: path, + [arraySchemaSymbol]: schematype, + [arrayParentSymbol]: void 0, + isMongooseArray: true, + isMongooseArrayProxy: true, + __array: arr + }; - var denied = exports; + if (values[arrayAtomicsSymbol] != null) { + internals[arrayAtomicsSymbol] = values[arrayAtomicsSymbol]; + } - denied.distinct = function (self) { - if (self._fields && Object.keys(self._fields).length > 0) { - return "field selection and slice"; - } + // Because doc comes from the context of another function, doc === global + // can happen if there was a null somewhere up the chain (see #3020) + // RB Jun 17, 2015 updated to check for presence of expected paths instead + // to make more proof against unusual node environments + if (doc != null && doc instanceof Document) { + internals[arrayParentSymbol] = doc; + internals[arraySchemaSymbol] = schematype || doc.schema.path(path); + } - var keys = Object.keys(denied.distinct); - var err; + const proxy = new Proxy(arr, { + get: function(target, prop) { + if (internals.hasOwnProperty(prop)) { + return internals[prop]; + } + if (mongooseArrayMethods.hasOwnProperty(prop)) { + return mongooseArrayMethods[prop]; + } - keys.every(function (option) { - if (self.options[option]) { - err = option; - return false; - } - return true; - }); + return arr[prop]; + }, + set: function(target, prop, val) { + if (typeof prop === 'string' && /^\d+$/.test(prop)) { + const value = mongooseArrayMethods._cast.call(proxy, val, prop); + arr[prop] = value; + mongooseArrayMethods._markModified.call(proxy, prop); + } else if (internals.hasOwnProperty(prop)) { + internals[prop] = val; + } else { + arr[prop] = val; + } - return err; - }; - denied.distinct.select = - denied.distinct.slice = - denied.distinct.sort = - denied.distinct.limit = - denied.distinct.skip = - denied.distinct.batchSize = - denied.distinct.comment = - denied.distinct.maxScan = - denied.distinct.snapshot = - denied.distinct.hint = - denied.distinct.tailable = - true; - - // aggregation integration - - denied.findOneAndUpdate = denied.findOneAndRemove = function (self) { - var keys = Object.keys(denied.findOneAndUpdate); - var err; - - keys.every(function (option) { - if (self.options[option]) { - err = option; - return false; - } - return true; - }); + return true; + } + }); - return err; - }; - denied.findOneAndUpdate.limit = - denied.findOneAndUpdate.skip = - denied.findOneAndUpdate.batchSize = - denied.findOneAndUpdate.maxScan = - denied.findOneAndUpdate.snapshot = - denied.findOneAndUpdate.hint = - denied.findOneAndUpdate.tailable = - denied.findOneAndUpdate.comment = - true; - - denied.count = function (self) { - if (self._fields && Object.keys(self._fields).length > 0) { - return "field selection and slice"; - } - - var keys = Object.keys(denied.count); - var err; - - keys.every(function (option) { - if (self.options[option]) { - err = option; - return false; - } - return true; - }); + return proxy; +} - return err; - }; +/*! + * Module exports. + */ - denied.count.slice = - denied.count.batchSize = - denied.count.comment = - denied.count.maxScan = - denied.count.snapshot = - denied.count.tailable = - true; +module.exports = exports = MongooseArray; - /***/ - }, - /***/ 7483: /***/ ( - __unused_webpack_module, - exports, - __nccwpck_require__ - ) => { - "use strict"; - - /*! - * Module dependencies. - */ - - var Buffer = __nccwpck_require__(1865).Buffer; - var RegExpClone = __nccwpck_require__(8292); - - var specialProperties = ["__proto__", "constructor", "prototype"]; - - /** - * Clones objects - * - * @param {Object} obj the object to clone - * @param {Object} options - * @return {Object} the cloned object - * @api private - */ - - var clone = (exports.clone = function clone(obj, options) { - if (obj === undefined || obj === null) return obj; - - if (Array.isArray(obj)) return exports.cloneArray(obj, options); - - if (obj.constructor) { - if (/ObjectI[dD]$/.test(obj.constructor.name)) { - return "function" == typeof obj.clone - ? obj.clone() - : new obj.constructor(obj.id); - } +/***/ }), - if (obj.constructor.name === "ReadPreference") { - return new obj.constructor(obj.mode, clone(obj.tags, options)); - } +/***/ 3919: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ("Binary" == obj._bsontype && obj.buffer && obj.value) { - return "function" == typeof obj.clone - ? obj.clone() - : new obj.constructor(obj.value(true), obj.sub_type); - } +"use strict"; - if ( - "Date" === obj.constructor.name || - "Function" === obj.constructor.name - ) - return new obj.constructor(+obj); - if ("RegExp" === obj.constructor.name) return RegExpClone(obj); +const Document = __nccwpck_require__(6717); +const ArraySubdocument = __nccwpck_require__(9999); +const MongooseError = __nccwpck_require__(5953); +const ObjectId = __nccwpck_require__(2706); +const cleanModifiedSubpaths = __nccwpck_require__(7958); +const get = __nccwpck_require__(8730); +const internalToObjectOptions = __nccwpck_require__(5684)/* .internalToObjectOptions */ .h; +const utils = __nccwpck_require__(9232); - if ("Buffer" === obj.constructor.name) - return exports.cloneBuffer(obj); - } +const arrayAtomicsSymbol = __nccwpck_require__(3240).arrayAtomicsSymbol; +const arrayParentSymbol = __nccwpck_require__(3240).arrayParentSymbol; +const arrayPathSymbol = __nccwpck_require__(3240).arrayPathSymbol; +const arraySchemaSymbol = __nccwpck_require__(3240).arraySchemaSymbol; +const populateModelSymbol = __nccwpck_require__(3240).populateModelSymbol; +const slicedSymbol = Symbol('mongoose#Array#sliced'); - if (isObject(obj)) return exports.cloneObject(obj, options); +const _basePush = Array.prototype.push; - if (obj.valueOf) return obj.valueOf(); - }); +/*! + * ignore + */ - /*! - * ignore - */ +const methods = { + /** + * Depopulates stored atomic operation values as necessary for direct insertion to MongoDB. + * + * If no atomics exist, we return all array values after conversion. + * + * @return {Array} + * @method $__getAtomics + * @memberOf MongooseArray + * @instance + * @api private + */ + + $__getAtomics() { + const ret = []; + const keys = Object.keys(this[arrayAtomicsSymbol] || {}); + let i = keys.length; + + const opts = Object.assign({}, internalToObjectOptions, { _isNested: true }); + + if (i === 0) { + ret[0] = ['$set', this.toObject(opts)]; + return ret; + } - exports.cloneObject = function cloneObject(obj, options) { - var minimize = options && options.minimize; - var ret = {}; - var hasKeys; - var val; + while (i--) { + const op = keys[i]; + let val = this[arrayAtomicsSymbol][op]; - for (const k of Object.keys(obj)) { - // Not technically prototype pollution because this wouldn't merge properties - // onto `Object.prototype`, but avoid properties like __proto__ as a precaution. - if (specialProperties.indexOf(k) !== -1) { - continue; - } + // the atomic values which are arrays are not MongooseArrays. we + // need to convert their elements as if they were MongooseArrays + // to handle populated arrays versus DocumentArrays properly. + if (utils.isMongooseObject(val)) { + val = val.toObject(opts); + } else if (Array.isArray(val)) { + val = this.toObject.call(val, opts); + } else if (val != null && Array.isArray(val.$each)) { + val.$each = this.toObject.call(val.$each, opts); + } else if (val != null && typeof val.valueOf === 'function') { + val = val.valueOf(); + } - val = clone(obj[k], options); + if (op === '$addToSet') { + val = { $each: val }; + } - if (!minimize || "undefined" !== typeof val) { - hasKeys || (hasKeys = true); - ret[k] = val; - } - } + ret.push([op, val]); + } - return minimize ? hasKeys && ret : ret; - }; + return ret; + }, + + /*! + * ignore + */ + + $atomics() { + return this[arrayAtomicsSymbol]; + }, + + /*! + * ignore + */ + + $parent() { + return this[arrayParentSymbol]; + }, + + /*! + * ignore + */ + + $path() { + return this[arrayPathSymbol]; + }, + + /** + * Atomically shifts the array at most one time per document `save()`. + * + * ####NOTE: + * + * _Calling this multiple times on an array before saving sends the same command as calling it once._ + * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ + * + * doc.array = [1,2,3]; + * + * const shifted = doc.array.$shift(); + * console.log(shifted); // 1 + * console.log(doc.array); // [2,3] + * + * // no affect + * shifted = doc.array.$shift(); + * console.log(doc.array); // [2,3] + * + * doc.save(function (err) { + * if (err) return handleError(err); + * + * // we saved, now $shift works again + * shifted = doc.array.$shift(); + * console.log(shifted ); // 2 + * console.log(doc.array); // [3] + * }) + * + * @api public + * @memberOf MongooseArray + * @instance + * @method $shift + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop + */ + + $shift() { + this._registerAtomic('$pop', -1); + this._markModified(); + + // only allow shifting once + if (this._shifted) { + return; + } + this._shifted = true; + + return [].shift.call(this); + }, + + /** + * Pops the array atomically at most one time per document `save()`. + * + * #### NOTE: + * + * _Calling this mulitple times on an array before saving sends the same command as calling it once._ + * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ + * + * doc.array = [1,2,3]; + * + * const popped = doc.array.$pop(); + * console.log(popped); // 3 + * console.log(doc.array); // [1,2] + * + * // no affect + * popped = doc.array.$pop(); + * console.log(doc.array); // [1,2] + * + * doc.save(function (err) { + * if (err) return handleError(err); + * + * // we saved, now $pop works again + * popped = doc.array.$pop(); + * console.log(popped); // 2 + * console.log(doc.array); // [1] + * }) + * + * @api public + * @method $pop + * @memberOf MongooseArray + * @instance + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop + * @method $pop + * @memberOf MongooseArray + */ + + $pop() { + this._registerAtomic('$pop', 1); + this._markModified(); + + // only allow popping once + if (this._popped) { + return; + } + this._popped = true; + + return [].pop.call(this); + }, + + /*! + * ignore + */ + + $schema() { + return this[arraySchemaSymbol]; + }, + + /** + * Casts a member based on this arrays schema. + * + * @param {any} value + * @return value the casted value + * @method _cast + * @api private + * @memberOf MongooseArray + */ + + _cast(value) { + let populated = false; + let Model; + + const parent = this[arrayParentSymbol]; + if (parent) { + populated = parent.$populated(this[arrayPathSymbol], true); + } - exports.cloneArray = function cloneArray(arr, options) { - var ret = []; - for (var i = 0, l = arr.length; i < l; i++) - ret.push(clone(arr[i], options)); - return ret; - }; + if (populated && value !== null && value !== undefined) { + // cast to the populated Models schema + Model = populated.options[populateModelSymbol]; - /** - * process.nextTick helper. - * - * Wraps the given `callback` in a try/catch. If an error is - * caught it will be thrown on nextTick. - * - * node-mongodb-native had a habit of state corruption when - * an error was immediately thrown from within a collection - * method (find, update, etc) callback. - * - * @param {Function} [callback] - * @api private - */ - - exports.tick = function tick(callback) { - if ("function" !== typeof callback) return; - return function () { - // callbacks should always be fired on the next - // turn of the event loop. A side benefit is - // errors thrown from executing the callback - // will not cause drivers state to be corrupted - // which has historically been a problem. - var args = arguments; - soon(function () { - callback.apply(this, args); - }); - }; - }; + // only objects are permitted so we can safely assume that + // non-objects are to be interpreted as _id + if (Buffer.isBuffer(value) || + value instanceof ObjectId || !utils.isObject(value)) { + value = { _id: value }; + } - /** - * Merges `from` into `to` without overwriting existing properties. - * - * @param {Object} to - * @param {Object} from - * @api private - */ - - exports.merge = function merge(to, from) { - var keys = Object.keys(from), - i = keys.length, - key; - - while (i--) { - key = keys[i]; - if (specialProperties.indexOf(key) !== -1) { - continue; - } - if ("undefined" === typeof to[key]) { - to[key] = from[key]; - } else { - if (exports.isObject(from[key])) { - merge(to[key], from[key]); - } else { - to[key] = from[key]; - } - } - } - }; + // gh-2399 + // we should cast model only when it's not a discriminator + const isDisc = value.schema && value.schema.discriminatorMapping && + value.schema.discriminatorMapping.key !== undefined; + if (!isDisc) { + value = new Model(value); + } + return this[arraySchemaSymbol].caster.applySetters(value, parent, true); + } - /** - * Same as merge but clones the assigned values. - * - * @param {Object} to - * @param {Object} from - * @api private - */ - - exports.mergeClone = function mergeClone(to, from) { - var keys = Object.keys(from), - i = keys.length, - key; - - while (i--) { - key = keys[i]; - if (specialProperties.indexOf(key) !== -1) { - continue; - } - if ("undefined" === typeof to[key]) { - to[key] = clone(from[key]); - } else { - if (exports.isObject(from[key])) { - mergeClone(to[key], from[key]); - } else { - to[key] = clone(from[key]); - } - } - } - }; + return this[arraySchemaSymbol].caster.applySetters(value, parent, false); + }, + + /** + * Internal helper for .map() + * + * @api private + * @return {Number} + * @method _mapCast + * @memberOf MongooseArray + */ + + _mapCast(val, index) { + return this._cast(val, this.length + index); + }, + + /** + * Marks this array as modified. + * + * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments) + * + * @param {ArraySubdocument} subdoc the embedded doc that invoked this method on the Array + * @param {String} embeddedPath the path which changed in the subdoc + * @method _markModified + * @api private + * @memberOf MongooseArray + */ + + _markModified(elem) { + const parent = this[arrayParentSymbol]; + let dirtyPath; + + if (parent) { + dirtyPath = this[arrayPathSymbol]; + + if (arguments.length) { + dirtyPath = dirtyPath + '.' + elem; + } + + if (dirtyPath != null && dirtyPath.endsWith('.$')) { + return this; + } - /** - * Read pref helper (mongo 2.2 drivers support this) - * - * Allows using aliases instead of full preference names: - * - * p primary - * pp primaryPreferred - * s secondary - * sp secondaryPreferred - * n nearest - * - * @param {String} pref - */ - - exports.readPref = function readPref(pref) { - switch (pref) { - case "p": - pref = "primary"; - break; - case "pp": - pref = "primaryPreferred"; - break; - case "s": - pref = "secondary"; - break; - case "sp": - pref = "secondaryPreferred"; - break; - case "n": - pref = "nearest"; - break; - } + parent.markModified(dirtyPath, arguments.length > 0 ? elem : parent); + } - return pref; - }; + return this; + }, + + /** + * Register an atomic operation with the parent. + * + * @param {Array} op operation + * @param {any} val + * @method _registerAtomic + * @api private + * @memberOf MongooseArray + */ + + _registerAtomic(op, val) { + if (this[slicedSymbol]) { + return; + } + if (op === '$set') { + // $set takes precedence over all other ops. + // mark entire array modified. + this[arrayAtomicsSymbol] = { $set: val }; + cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]); + this._markModified(); + return this; + } - /** - * Read Concern helper (mongo 3.2 drivers support this) - * - * Allows using string to specify read concern level: - * - * local 3.2+ - * available 3.6+ - * majority 3.2+ - * linearizable 3.4+ - * snapshot 4.0+ - * - * @param {String|Object} concern - */ - - exports.readConcern = function readConcern(concern) { - if ("string" === typeof concern) { - switch (concern) { - case "l": - concern = "local"; - break; - case "a": - concern = "available"; - break; - case "m": - concern = "majority"; - break; - case "lz": - concern = "linearizable"; - break; - case "s": - concern = "snapshot"; - break; - } - concern = { level: concern }; - } - return concern; - }; + const atomics = this[arrayAtomicsSymbol]; - /** - * Object.prototype.toString.call helper - */ + // reset pop/shift after save + if (op === '$pop' && !('$pop' in atomics)) { + const _this = this; + this[arrayParentSymbol].once('save', function() { + _this._popped = _this._shifted = null; + }); + } - var _toString = Object.prototype.toString; - exports.toString = function (arg) { - return _toString.call(arg); - }; + // check for impossible $atomic combos (Mongo denies more than one + // $atomic op on a single path + if (atomics.$set || Object.keys(atomics).length && !(op in atomics)) { + // a different op was previously registered. + // save the entire thing. + this[arrayAtomicsSymbol] = { $set: this }; + return this; + } + + let selector; + + if (op === '$pullAll' || op === '$addToSet') { + atomics[op] || (atomics[op] = []); + atomics[op] = atomics[op].concat(val); + } else if (op === '$pullDocs') { + const pullOp = atomics['$pull'] || (atomics['$pull'] = {}); + if (val[0] instanceof ArraySubdocument) { + selector = pullOp['$or'] || (pullOp['$or'] = []); + Array.prototype.push.apply(selector, val.map(function(v) { + return v.toObject({ transform: false, virtuals: false }); + })); + } else { + selector = pullOp['_id'] || (pullOp['_id'] = { $in: [] }); + selector['$in'] = selector['$in'].concat(val); + } + } else if (op === '$push') { + atomics.$push = atomics.$push || { $each: [] }; + if (val != null && utils.hasUserDefinedProperty(val, '$each')) { + atomics.$push = val; + } else { + atomics.$push.$each = atomics.$push.$each.concat(val); + } + } else { + atomics[op] = val; + } - /** - * Determines if `arg` is an object. - * - * @param {Object|Array|String|Function|RegExp|any} arg - * @return {Boolean} - */ + return this; + }, + + /** + * Adds values to the array if not already present. + * + * ####Example: + * + * console.log(doc.array) // [2,3,4] + * const added = doc.array.addToSet(4,5); + * console.log(doc.array) // [2,3,4,5] + * console.log(added) // [5] + * + * @param {any} [args...] + * @return {Array} the values that were added + * @memberOf MongooseArray + * @api public + * @method addToSet + */ + + addToSet() { + _checkManualPopulation(this, arguments); + + let values = [].map.call(arguments, this._mapCast, this); + values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]); + const added = []; + let type = ''; + if (values[0] instanceof ArraySubdocument) { + type = 'doc'; + } else if (values[0] instanceof Date) { + type = 'date'; + } - var isObject = (exports.isObject = function (arg) { - return "[object Object]" == exports.toString(arg); - }); + const rawValues = values.isMongooseArrayProxy ? values.__array : this; + const rawArray = this.isMongooseArrayProxy ? this.__array : this; - /** - * Determines if `arg` is an array. - * - * @param {Object} - * @return {Boolean} - * @see nodejs utils - */ - - exports.isArray = function (arg) { - return ( - Array.isArray(arg) || - ("object" == typeof arg && "[object Array]" == exports.toString(arg)) - ); - }; + rawValues.forEach(function(v) { + let found; + const val = +v; + switch (type) { + case 'doc': + found = this.some(function(doc) { + return doc.equals(v); + }); + break; + case 'date': + found = this.some(function(d) { + return +d === val; + }); + break; + default: + found = ~this.indexOf(v); + } - /** - * Object.keys helper - */ + if (!found) { + rawArray.push(v); + this._registerAtomic('$addToSet', v); + this._markModified(); + [].push.call(added, v); + } + }, this); - exports.keys = Object.keys; + return added; + }, - /** - * Basic Object.create polyfill. - * Only one argument is supported. - * - * Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create - */ + /** + * Returns the number of pending atomic operations to send to the db for this array. + * + * @api private + * @return {Number} + * @method hasAtomics + * @memberOf MongooseArray + */ - exports.create = - "function" == typeof Object.create ? Object.create : create; + hasAtomics() { + if (!utils.isPOJO(this[arrayAtomicsSymbol])) { + return 0; + } - function create(proto) { - if (arguments.length > 1) { - throw new Error("Adding properties is not supported"); - } + return Object.keys(this[arrayAtomicsSymbol]).length; + }, + + /** + * Return whether or not the `obj` is included in the array. + * + * @param {Object} obj the item to check + * @return {Boolean} + * @api public + * @method includes + * @memberOf MongooseArray + */ + + includes(obj, fromIndex) { + const ret = this.indexOf(obj, fromIndex); + return ret !== -1; + }, + + /** + * Return the index of `obj` or `-1` if not found. + * + * @param {Object} obj the item to look for + * @return {Number} + * @api public + * @method indexOf + * @memberOf MongooseArray + */ + + indexOf(obj, fromIndex) { + if (obj instanceof ObjectId) { + obj = obj.toString(); + } - function F() {} - F.prototype = proto; - return new F(); + fromIndex = fromIndex == null ? 0 : fromIndex; + const len = this.length; + for (let i = fromIndex; i < len; ++i) { + if (obj == this[i]) { + return i; } + } + return -1; + }, + + /** + * Helper for console.log + * + * @api public + * @method inspect + * @memberOf MongooseArray + */ + + inspect() { + return JSON.stringify(this); + }, + + /** + * Pushes items to the array non-atomically. + * + * ####NOTE: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @param {any} [args...] + * @api public + * @method nonAtomicPush + * @memberOf MongooseArray + */ + + nonAtomicPush() { + const values = [].map.call(arguments, this._mapCast, this); + const ret = [].push.apply(this, values); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + }, + + /** + * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking. + * + * ####Note: + * + * _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @see MongooseArray#$pop #types_array_MongooseArray-%24pop + * @api public + * @method pop + * @memberOf MongooseArray + */ + + pop() { + const ret = [].pop.call(this); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + }, + + /** + * Pulls items from the array atomically. Equality is determined by casting + * the provided value to an embedded document and comparing using + * [the `Document.equals()` function.](./api.html#document_Document-equals) + * + * ####Examples: + * + * doc.array.pull(ObjectId) + * doc.array.pull({ _id: 'someId' }) + * doc.array.pull(36) + * doc.array.pull('tag 1', 'tag 2') + * + * To remove a document from a subdocument array we may pass an object with a matching `_id`. + * + * doc.subdocs.push({ _id: 4815162342 }) + * doc.subdocs.pull({ _id: 4815162342 }) // removed + * + * Or we may passing the _id directly and let mongoose take care of it. + * + * doc.subdocs.push({ _id: 4815162342 }) + * doc.subdocs.pull(4815162342); // works + * + * The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime. + * + * @param {any} [args...] + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull + * @api public + * @method pull + * @memberOf MongooseArray + */ + + pull() { + const values = [].map.call(arguments, this._cast, this); + const cur = this[arrayParentSymbol].get(this[arrayPathSymbol]); + let i = cur.length; + let mem; + + while (i--) { + mem = cur[i]; + if (mem instanceof Document) { + const some = values.some(function(v) { + return mem.equals(v); + }); + if (some) { + [].splice.call(cur, i, 1); + } + } else if (~cur.indexOf.call(values, mem)) { + [].splice.call(cur, i, 1); + } + } - /** - * inheritance - */ + if (values[0] instanceof ArraySubdocument) { + this._registerAtomic('$pullDocs', values.map(function(v) { + return v.$__getValue('_id') || v; + })); + } else { + this._registerAtomic('$pullAll', values); + } - exports.inherits = function (ctor, superCtor) { - ctor.prototype = exports.create(superCtor.prototype); - ctor.prototype.constructor = ctor; - }; + this._markModified(); - /** - * nextTick helper - * compat with node 0.10 which behaves differently than previous versions - */ - - var soon = (exports.soon = - "function" == typeof setImmediate ? setImmediate : process.nextTick); - - /** - * Clones the contents of a buffer. - * - * @param {Buffer} buff - * @return {Buffer} - */ - - exports.cloneBuffer = function (buff) { - var dupe = Buffer.alloc(buff.length); - buff.copy(dupe, 0, 0, buff.length); - return dupe; - }; + // Might have modified child paths and then pulled, like + // `doc.children[1].name = 'test';` followed by + // `doc.children.remove(doc.children[0]);`. In this case we fall back + // to a `$set` on the whole array. See #3511 + if (cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]) > 0) { + this._registerAtomic('$set', this); + } - /** - * Check if this object is an arguments object - * - * @param {Any} v - * @return {Boolean} - */ + return this; + }, + + /** + * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. + * + * ####Example: + * + * const schema = Schema({ nums: [Number] }); + * const Model = mongoose.model('Test', schema); + * + * const doc = await Model.create({ nums: [3, 4] }); + * doc.nums.push(5); // Add 5 to the end of the array + * await doc.save(); + * + * // You can also pass an object with `$each` as the + * // first parameter to use MongoDB's `$position` + * doc.nums.push({ + * $each: [1, 2], + * $position: 0 + * }); + * doc.nums; // [1, 2, 3, 4, 5] + * + * @param {Object} [args...] + * @api public + * @method push + * @memberOf MongooseArray + */ + + push() { + let values = arguments; + let atomic = values; + const isOverwrite = values[0] != null && + utils.hasUserDefinedProperty(values[0], '$each'); + const arr = this.isMongooseArrayProxy ? this.__array : this; + if (isOverwrite) { + atomic = values[0]; + values = values[0].$each; + } - exports.isArgumentsObject = function (v) { - return Object.prototype.toString.call(v) === "[object Arguments]"; - }; + if (this[arraySchemaSymbol] == null) { + return _basePush.apply(this, values); + } - /***/ - }, + _checkManualPopulation(this, values); - /***/ 8819: /***/ (module) => { - "use strict"; + const parent = this[arrayParentSymbol]; + values = [].map.call(values, this._mapCast, this); + values = this[arraySchemaSymbol].applySetters(values, parent, undefined, + undefined, { skipDocumentArrayCast: true }); + let ret; + const atomics = this[arrayAtomicsSymbol]; - module.exports = function (Promise) { - var SomePromiseArray = Promise._SomePromiseArray; - function any(promises) { - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - ret.setHowMany(1); - ret.setUnwrap(); - ret.init(); - return promise; - } + if (isOverwrite) { + atomic.$each = values; - Promise.any = function (promises) { - return any(promises); - }; + if (get(atomics, '$push.$each.length', 0) > 0 && + atomics.$push.$position != atomic.$position) { + throw new MongooseError('Cannot call `Array#push()` multiple times ' + + 'with different `$position`'); + } - Promise.prototype.any = function () { - return any(this); - }; - }; + if (atomic.$position != null) { + [].splice.apply(arr, [atomic.$position, 0].concat(values)); + ret = this.length; + } else { + ret = [].push.apply(arr, values); + } + } else { + if (get(atomics, '$push.$each.length', 0) > 0 && + atomics.$push.$position != null) { + throw new MongooseError('Cannot call `Array#push()` multiple times ' + + 'with different `$position`'); + } + atomic = values; + ret = [].push.apply(arr, values); + } - /***/ - }, + this._registerAtomic('$push', atomic); + this._markModified(); + return ret; + }, + + /** + * Alias of [pull](#mongoosearray_MongooseArray-pull) + * + * @see MongooseArray#pull #types_array_MongooseArray-pull + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull + * @api public + * @memberOf MongooseArray + * @instance + * @method remove + */ + + remove() { + return this.pull.apply(this, arguments); + }, + + /** + * Sets the casted `val` at index `i` and marks the array modified. + * + * ####Example: + * + * // given documents based on the following + * const Doc = mongoose.model('Doc', new Schema({ array: [Number] })); + * + * const doc = new Doc({ array: [2,3,4] }) + * + * console.log(doc.array) // [2,3,4] + * + * doc.array.set(1,"5"); + * console.log(doc.array); // [2,5,4] // properly cast to number + * doc.save() // the change is saved + * + * // VS not using array#set + * doc.array[1] = "5"; + * console.log(doc.array); // [2,"5",4] // no casting + * doc.save() // change is not saved + * + * @return {Array} this + * @api public + * @method set + * @memberOf MongooseArray + */ + + set(i, val, skipModified) { + const arr = this.__array; + if (skipModified) { + arr[i] = val; + return this; + } + const value = methods._cast.call(this, val, i); + arr[i] = value; + methods._markModified.call(this, i); + return this; + }, + + /** + * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. + * + * ####Example: + * + * doc.array = [2,3]; + * const res = doc.array.shift(); + * console.log(res) // 2 + * console.log(doc.array) // [3] + * + * ####Note: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method shift + * @memberOf MongooseArray + */ + + shift() { + const arr = this.isMongooseArrayProxy ? this.__array : this; + const ret = [].shift.call(arr); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + }, + + /** + * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking. + * + * ####NOTE: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method sort + * @memberOf MongooseArray + * @see https://masteringjs.io/tutorials/fundamentals/array-sort + */ + + sort() { + const arr = this.isMongooseArrayProxy ? this.__array : this; + const ret = [].sort.apply(arr, arguments); + this._registerAtomic('$set', this); + return ret; + }, + + /** + * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. + * + * ####Note: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method splice + * @memberOf MongooseArray + * @see https://masteringjs.io/tutorials/fundamentals/array-splice + */ + + splice() { + let ret; + const arr = this.isMongooseArrayProxy ? this.__array : this; + + _checkManualPopulation(this, Array.prototype.slice.call(arguments, 2)); + + if (arguments.length) { + let vals; + if (this[arraySchemaSymbol] == null) { + vals = arguments; + } else { + vals = []; + for (let i = 0; i < arguments.length; ++i) { + vals[i] = i < 2 ? + arguments[i] : + this._cast(arguments[i], arguments[0] + (i - 2)); + } + } - /***/ 5118: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + ret = [].splice.apply(arr, vals); + this._registerAtomic('$set', this); + } - var firstLineError; - try { - throw new Error(); - } catch (e) { - firstLineError = e; - } - var schedule = __nccwpck_require__(5989); - var Queue = __nccwpck_require__(632); - var util = __nccwpck_require__(2122); - - function Async() { - this._customScheduler = false; - this._isTickUsed = false; - this._lateQueue = new Queue(16); - this._normalQueue = new Queue(16); - this._haveDrainedQueues = false; - this._trampolineEnabled = true; - var self = this; - this.drainQueues = function () { - self._drainQueues(); - }; - this._schedule = schedule; - } + return ret; + }, + + /*! + * ignore + */ + + toBSON() { + return this.toObject(internalToObjectOptions); + }, + + /** + * Returns a native js Array. + * + * @param {Object} options + * @return {Array} + * @api public + * @method toObject + * @memberOf MongooseArray + */ + + toObject(options) { + const arr = this.isMongooseArrayProxy ? this.__array : this; + if (options && options.depopulate) { + options = utils.clone(options); + options._isNested = true; + // Ensure return value is a vanilla array, because in Node.js 6+ `map()` + // is smart enough to use the inherited array's constructor. + return [].concat(arr).map(function(doc) { + return doc instanceof Document + ? doc.toObject(options) + : doc; + }); + } - Async.prototype.setScheduler = function (fn) { - var prev = this._schedule; - this._schedule = fn; - this._customScheduler = true; - return prev; - }; + return [].concat(arr); + }, + + $toObject() { + return this.constructor.prototype.toObject.apply(this, arguments); + }, + /** + * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. + * + * ####Note: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwriting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method unshift + * @memberOf MongooseArray + */ + + unshift() { + _checkManualPopulation(this, arguments); + + let values; + if (this[arraySchemaSymbol] == null) { + values = arguments; + } else { + values = [].map.call(arguments, this._cast, this); + values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]); + } - Async.prototype.hasCustomScheduler = function () { - return this._customScheduler; - }; + const arr = this.isMongooseArrayProxy ? this.__array : this; + [].unshift.apply(arr, values); + this._registerAtomic('$set', this); + this._markModified(); + return this.length; + } +}; - Async.prototype.enableTrampoline = function () { - this._trampolineEnabled = true; - }; +/*! + * ignore + */ - Async.prototype.disableTrampolineIfNecessary = function () { - if (util.hasDevTools) { - this._trampolineEnabled = false; - } - }; +function _isAllSubdocs(docs, ref) { + if (!ref) { + return false; + } - Async.prototype.haveItemsQueued = function () { - return this._isTickUsed || this._haveDrainedQueues; - }; + for (const arg of docs) { + if (arg == null) { + return false; + } + const model = arg.constructor; + if (!(arg instanceof Document) || + (model.modelName !== ref && model.baseModelName !== ref)) { + return false; + } + } - Async.prototype.fatalError = function (e, isNode) { - if (isNode) { - process.stderr.write( - "Fatal " + (e instanceof Error ? e.stack : e) + "\n" - ); - process.exit(2); - } else { - this.throwLater(e); - } - }; + return true; +} - Async.prototype.throwLater = function (fn, arg) { - if (arguments.length === 1) { - arg = fn; - fn = function () { - throw arg; - }; - } - if (typeof setTimeout !== "undefined") { - setTimeout(function () { - fn(arg); - }, 0); - } else - try { - this._schedule(function () { - fn(arg); - }); - } catch (e) { - throw new Error( - "No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a" - ); - } - }; +/*! + * ignore + */ - function AsyncInvokeLater(fn, receiver, arg) { - this._lateQueue.push(fn, receiver, arg); - this._queueTick(); - } +function _checkManualPopulation(arr, docs) { + const ref = arr == null ? + null : + get(arr[arraySchemaSymbol], 'caster.options.ref', null); + if (arr.length === 0 && + docs.length > 0) { + if (_isAllSubdocs(docs, ref)) { + arr[arrayParentSymbol].$populated(arr[arrayPathSymbol], [], { + [populateModelSymbol]: docs[0].constructor + }); + } + } +} + +const returnVanillaArrayMethods = [ + 'filter', + 'flat', + 'flatMap', + 'map', + 'slice' +]; +for (const method of returnVanillaArrayMethods) { + if (Array.prototype[method] == null) { + continue; + } - function AsyncInvoke(fn, receiver, arg) { - this._normalQueue.push(fn, receiver, arg); - this._queueTick(); - } + methods[method] = function() { + const _arr = this.isMongooseArrayProxy ? this.__array : this; + const arr = [].concat(_arr); - function AsyncSettlePromises(promise) { - this._normalQueue._pushOne(promise); - this._queueTick(); - } + return arr[method].apply(arr, arguments); + }; +} - if (!util.hasDevTools) { - Async.prototype.invokeLater = AsyncInvokeLater; - Async.prototype.invoke = AsyncInvoke; - Async.prototype.settlePromises = AsyncSettlePromises; - } else { - Async.prototype.invokeLater = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvokeLater.call(this, fn, receiver, arg); - } else { - this._schedule(function () { - setTimeout(function () { - fn.call(receiver, arg); - }, 100); - }); - } - }; +module.exports = methods; - Async.prototype.invoke = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvoke.call(this, fn, receiver, arg); - } else { - this._schedule(function () { - fn.call(receiver, arg); - }); - } - }; - Async.prototype.settlePromises = function (promise) { - if (this._trampolineEnabled) { - AsyncSettlePromises.call(this, promise); - } else { - this._schedule(function () { - promise._settlePromises(); - }); - } - }; - } +/***/ }), - Async.prototype._drainQueue = function (queue) { - while (queue.length() > 0) { - var fn = queue.shift(); - if (typeof fn !== "function") { - fn._settlePromises(); - continue; - } - var receiver = queue.shift(); - var arg = queue.shift(); - fn.call(receiver, arg); - } - }; +/***/ 5505: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Async.prototype._drainQueues = function () { - this._drainQueue(this._normalQueue); - this._reset(); - this._haveDrainedQueues = true; - this._drainQueue(this._lateQueue); - }; +"use strict"; +/*! + * Module dependencies. + */ - Async.prototype._queueTick = function () { - if (!this._isTickUsed) { - this._isTickUsed = true; - this._schedule(this.drainQueues); - } - }; - Async.prototype._reset = function () { - this._isTickUsed = false; - }; - module.exports = Async; - module.exports.firstLineError = firstLineError; +const Binary = __nccwpck_require__(2324).get().Binary; +const utils = __nccwpck_require__(9232); - /***/ - }, +/** + * Mongoose Buffer constructor. + * + * Values always have to be passed to the constructor to initialize. + * + * @param {Buffer} value + * @param {String} encode + * @param {Number} offset + * @api private + * @inherits Buffer + * @see http://bit.ly/f6CnZU + */ - /***/ 764: /***/ (module) => { - "use strict"; - - module.exports = function ( - Promise, - INTERNAL, - tryConvertToPromise, - debug - ) { - var calledBind = false; - var rejectThis = function (_, e) { - this._reject(e); - }; +function MongooseBuffer(value, encode, offset) { + let val = value; + if (value == null) { + val = 0; + } - var targetRejected = function (e, context) { - context.promiseRejectionQueued = true; - context.bindingPromise._then(rejectThis, rejectThis, null, this, e); - }; + let encoding; + let path; + let doc; - var bindingResolved = function (thisArg, context) { - if ((this._bitField & 50397184) === 0) { - this._resolveCallback(context.target); - } - }; + if (Array.isArray(encode)) { + // internal casting + path = encode[0]; + doc = encode[1]; + } else { + encoding = encode; + } - var bindingRejected = function (e, context) { - if (!context.promiseRejectionQueued) this._reject(e); - }; + let buf; + if (typeof val === 'number' || val instanceof Number) { + buf = Buffer.alloc(val); + } else { // string, array or object { type: 'Buffer', data: [...] } + buf = Buffer.from(val, encoding, offset); + } + utils.decorate(buf, MongooseBuffer.mixin); + buf.isMongooseBuffer = true; - Promise.prototype.bind = function (thisArg) { - if (!calledBind) { - calledBind = true; - Promise.prototype._propagateFrom = debug.propagateFromFunction(); - Promise.prototype._boundValue = debug.boundValueFunction(); - } - var maybePromise = tryConvertToPromise(thisArg); - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 1); - var target = this._target(); - ret._setBoundTo(maybePromise); - if (maybePromise instanceof Promise) { - var context = { - promiseRejectionQueued: false, - promise: ret, - target: target, - bindingPromise: maybePromise, - }; - target._then(INTERNAL, targetRejected, undefined, ret, context); - maybePromise._then( - bindingResolved, - bindingRejected, - undefined, - ret, - context - ); - ret._setOnCancel(maybePromise); - } else { - ret._resolveCallback(target); - } - return ret; - }; + // make sure these internal props don't show up in Object.keys() + buf[MongooseBuffer.pathSymbol] = path; + buf[parentSymbol] = doc; - Promise.prototype._setBoundTo = function (obj) { - if (obj !== undefined) { - this._bitField = this._bitField | 2097152; - this._boundTo = obj; - } else { - this._bitField = this._bitField & ~2097152; - } - }; + buf._subtype = 0; + return buf; +} - Promise.prototype._isBound = function () { - return (this._bitField & 2097152) === 2097152; - }; +const pathSymbol = Symbol.for('mongoose#Buffer#_path'); +const parentSymbol = Symbol.for('mongoose#Buffer#_parent'); +MongooseBuffer.pathSymbol = pathSymbol; - Promise.bind = function (thisArg, value) { - return Promise.resolve(value).bind(thisArg); - }; - }; +/*! + * Inherit from Buffer. + */ - /***/ - }, +MongooseBuffer.mixin = { + + /** + * Default subtype for the Binary representing this Buffer + * + * @api private + * @property _subtype + * @receiver MongooseBuffer + */ + + _subtype: undefined, - /***/ 5404: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + /** + * Marks this buffer as modified. + * + * @api private + * @method _markModified + * @receiver MongooseBuffer + */ - var old; - if (typeof Promise !== "undefined") old = Promise; - function noConflict() { - try { - if (Promise === bluebird) Promise = old; - } catch (e) {} - return bluebird; - } - var bluebird = __nccwpck_require__(317)(); - bluebird.noConflict = noConflict; - module.exports = bluebird; + _markModified: function() { + const parent = this[parentSymbol]; - /***/ - }, + if (parent) { + parent.markModified(this[MongooseBuffer.pathSymbol]); + } + return this; + }, + + /** + * Writes the buffer. + * + * @api public + * @method write + * @receiver MongooseBuffer + */ + + write: function() { + const written = Buffer.prototype.write.apply(this, arguments); + + if (written > 0) { + this._markModified(); + } - /***/ 2414: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - var cr = Object.create; - if (cr) { - var callerCache = cr(null); - var getterCache = cr(null); - callerCache[" size"] = getterCache[" size"] = 0; - } - - module.exports = function (Promise) { - var util = __nccwpck_require__(2122); - var canEvaluate = util.canEvaluate; - var isIdentifier = util.isIdentifier; - - var getMethodCaller; - var getGetter; - if (true) { - var makeMethodCaller = function (methodName) { - return new Function( - "ensureMethod", - " \n\ - return function(obj) { \n\ - 'use strict' \n\ - var len = this.length; \n\ - ensureMethod(obj, 'methodName'); \n\ - switch(len) { \n\ - case 1: return obj.methodName(this[0]); \n\ - case 2: return obj.methodName(this[0], this[1]); \n\ - case 3: return obj.methodName(this[0], this[1], this[2]); \n\ - case 0: return obj.methodName(); \n\ - default: \n\ - return obj.methodName.apply(obj, this); \n\ - } \n\ - }; \n\ - ".replace( - /methodName/g, - methodName - ) - )(ensureMethod); - }; + return written; + }, + + /** + * Copies the buffer. + * + * ####Note: + * + * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this. + * + * @return {Number} The number of bytes copied. + * @param {Buffer} target + * @method copy + * @receiver MongooseBuffer + */ + + copy: function(target) { + const ret = Buffer.prototype.copy.apply(this, arguments); + + if (target && target.isMongooseBuffer) { + target._markModified(); + } - var makeGetter = function (propertyName) { - return new Function( - "obj", - " \n\ - 'use strict'; \n\ - return obj.propertyName; \n\ - ".replace( - "propertyName", - propertyName - ) - ); - }; + return ret; + } +}; - var getCompiled = function (name, compiler, cache) { - var ret = cache[name]; - if (typeof ret !== "function") { - if (!isIdentifier(name)) { - return null; - } - ret = compiler(name); - cache[name] = ret; - cache[" size"]++; - if (cache[" size"] > 512) { - var keys = Object.keys(cache); - for (var i = 0; i < 256; ++i) delete cache[keys[i]]; - cache[" size"] = keys.length - 256; - } - } - return ret; - }; +/*! + * Compile other Buffer methods marking this buffer as modified. + */ - getMethodCaller = function (name) { - return getCompiled(name, makeMethodCaller, callerCache); - }; +( +// node < 0.5 + ('writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' + + 'writeFloat writeDouble fill ' + + 'utf8Write binaryWrite asciiWrite set ' + + + // node >= 0.5 + 'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' + + 'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' + 'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE') +).split(' ').forEach(function(method) { + if (!Buffer.prototype[method]) { + return; + } + MongooseBuffer.mixin[method] = function() { + const ret = Buffer.prototype[method].apply(this, arguments); + this._markModified(); + return ret; + }; +}); - getGetter = function (name) { - return getCompiled(name, makeGetter, getterCache); - }; - } +/** + * Converts this buffer to its Binary type representation. + * + * ####SubTypes: + * + * const bson = require('bson') + * bson.BSON_BINARY_SUBTYPE_DEFAULT + * bson.BSON_BINARY_SUBTYPE_FUNCTION + * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY + * bson.BSON_BINARY_SUBTYPE_UUID + * bson.BSON_BINARY_SUBTYPE_MD5 + * bson.BSON_BINARY_SUBTYPE_USER_DEFINED + * + * doc.buffer.toObject(bson.BSON_BINARY_SUBTYPE_USER_DEFINED); + * + * @see http://bsonspec.org/#/specification + * @param {Hex} [subtype] + * @return {Binary} + * @api public + * @method toObject + * @receiver MongooseBuffer + */ - function ensureMethod(obj, methodName) { - var fn; - if (obj != null) fn = obj[methodName]; - if (typeof fn !== "function") { - var message = - "Object " + - util.classString(obj) + - " has no method '" + - util.toString(methodName) + - "'"; - throw new Promise.TypeError(message); - } - return fn; - } +MongooseBuffer.mixin.toObject = function(options) { + const subtype = typeof options === 'number' + ? options + : (this._subtype || 0); + return new Binary(Buffer.from(this), subtype); +}; - function caller(obj) { - var methodName = this.pop(); - var fn = ensureMethod(obj, methodName); - return fn.apply(obj, this); - } - Promise.prototype.call = function (methodName) { - var $_len = arguments.length; - var args = new Array(Math.max($_len - 1, 0)); - for (var $_i = 1; $_i < $_len; ++$_i) { - args[$_i - 1] = arguments[$_i]; - } - if (true) { - if (canEvaluate) { - var maybeCaller = getMethodCaller(methodName); - if (maybeCaller !== null) { - return this._then( - maybeCaller, - undefined, - undefined, - args, - undefined - ); - } - } - } - args.push(methodName); - return this._then(caller, undefined, undefined, args, undefined); - }; +MongooseBuffer.mixin.$toObject = MongooseBuffer.mixin.toObject; - function namedGetter(obj) { - return obj[this]; - } - function indexedGetter(obj) { - var index = +this; - if (index < 0) index = Math.max(0, index + obj.length); - return obj[index]; - } - Promise.prototype.get = function (propertyName) { - var isIndex = typeof propertyName === "number"; - var getter; - if (!isIndex) { - if (canEvaluate) { - var maybeGetter = getGetter(propertyName); - getter = maybeGetter !== null ? maybeGetter : namedGetter; - } else { - getter = namedGetter; - } - } else { - getter = indexedGetter; - } - return this._then( - getter, - undefined, - undefined, - propertyName, - undefined - ); - }; - }; +/** + * Converts this buffer for storage in MongoDB, including subtype + * + * @return {Binary} + * @api public + * @method toBSON + * @receiver MongooseBuffer + */ - /***/ - }, +MongooseBuffer.mixin.toBSON = function() { + return new Binary(this, this._subtype || 0); +}; - /***/ 3789: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function (Promise, PromiseArray, apiRejection, debug) { - var util = __nccwpck_require__(2122); - var tryCatch = util.tryCatch; - var errorObj = util.errorObj; - var async = Promise._async; - - Promise.prototype["break"] = Promise.prototype.cancel = function () { - if (!debug.cancellation()) - return this._warn("cancellation is disabled"); - - var promise = this; - var child = promise; - while (promise._isCancellable()) { - if (!promise._cancelBy(child)) { - if (child._isFollowing()) { - child._followee().cancel(); - } else { - child._cancelBranched(); - } - break; - } +/** + * Determines if this buffer is equals to `other` buffer + * + * @param {Buffer} other + * @return {Boolean} + * @method equals + * @receiver MongooseBuffer + */ - var parent = promise._cancellationParent; - if (parent == null || !parent._isCancellable()) { - if (promise._isFollowing()) { - promise._followee().cancel(); - } else { - promise._cancelBranched(); - } - break; - } else { - if (promise._isFollowing()) promise._followee().cancel(); - promise._setWillBeCancelled(); - child = promise; - promise = parent; - } - } - }; +MongooseBuffer.mixin.equals = function(other) { + if (!Buffer.isBuffer(other)) { + return false; + } - Promise.prototype._branchHasCancelled = function () { - this._branchesRemainingToCancel--; - }; + if (this.length !== other.length) { + return false; + } - Promise.prototype._enoughBranchesHaveCancelled = function () { - return ( - this._branchesRemainingToCancel === undefined || - this._branchesRemainingToCancel <= 0 - ); - }; + for (let i = 0; i < this.length; ++i) { + if (this[i] !== other[i]) { + return false; + } + } - Promise.prototype._cancelBy = function (canceller) { - if (canceller === this) { - this._branchesRemainingToCancel = 0; - this._invokeOnCancel(); - return true; - } else { - this._branchHasCancelled(); - if (this._enoughBranchesHaveCancelled()) { - this._invokeOnCancel(); - return true; - } - } - return false; - }; + return true; +}; - Promise.prototype._cancelBranched = function () { - if (this._enoughBranchesHaveCancelled()) { - this._cancel(); - } - }; +/** + * Sets the subtype option and marks the buffer modified. + * + * ####SubTypes: + * + * const bson = require('bson') + * bson.BSON_BINARY_SUBTYPE_DEFAULT + * bson.BSON_BINARY_SUBTYPE_FUNCTION + * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY + * bson.BSON_BINARY_SUBTYPE_UUID + * bson.BSON_BINARY_SUBTYPE_MD5 + * bson.BSON_BINARY_SUBTYPE_USER_DEFINED + * + * doc.buffer.subtype(bson.BSON_BINARY_SUBTYPE_UUID); + * + * @see http://bsonspec.org/#/specification + * @param {Hex} subtype + * @api public + * @method subtype + * @receiver MongooseBuffer + */ - Promise.prototype._cancel = function () { - if (!this._isCancellable()) return; - this._setCancelled(); - async.invoke(this._cancelPromises, this, undefined); - }; +MongooseBuffer.mixin.subtype = function(subtype) { + if (typeof subtype !== 'number') { + throw new TypeError('Invalid subtype. Expected a number'); + } - Promise.prototype._cancelPromises = function () { - if (this._length() > 0) this._settlePromises(); - }; + if (this._subtype !== subtype) { + this._markModified(); + } - Promise.prototype._unsetOnCancel = function () { - this._onCancelField = undefined; - }; + this._subtype = subtype; +}; - Promise.prototype._isCancellable = function () { - return this.isPending() && !this._isCancelled(); - }; +/*! + * Module exports. + */ - Promise.prototype.isCancellable = function () { - return this.isPending() && !this.isCancelled(); - }; +MongooseBuffer.Binary = Binary; - Promise.prototype._doInvokeOnCancel = function ( - onCancelCallback, - internalOnly - ) { - if (util.isArray(onCancelCallback)) { - for (var i = 0; i < onCancelCallback.length; ++i) { - this._doInvokeOnCancel(onCancelCallback[i], internalOnly); - } - } else if (onCancelCallback !== undefined) { - if (typeof onCancelCallback === "function") { - if (!internalOnly) { - var e = tryCatch(onCancelCallback).call(this._boundValue()); - if (e === errorObj) { - this._attachExtraTrace(e.e); - async.throwLater(e.e); - } - } - } else { - onCancelCallback._resultCancelled(this); - } - } - }; +module.exports = MongooseBuffer; - Promise.prototype._invokeOnCancel = function () { - var onCancelCallback = this._onCancel(); - this._unsetOnCancel(); - async.invoke(this._doInvokeOnCancel, this, onCancelCallback); - }; - Promise.prototype._invokeInternalOnCancel = function () { - if (this._isCancellable()) { - this._doInvokeOnCancel(this._onCancel(), true); - this._unsetOnCancel(); - } - }; +/***/ }), - Promise.prototype._resultCancelled = function () { - this.cancel(); - }; - }; +/***/ 8319: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /***/ - }, +"use strict"; +/** + * ObjectId type constructor + * + * ####Example + * + * const id = new mongoose.Types.ObjectId; + * + * @constructor ObjectId + */ - /***/ 8447: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function (NEXT_FILTER) { - var util = __nccwpck_require__(2122); - var getKeys = __nccwpck_require__(9432).keys; - var tryCatch = util.tryCatch; - var errorObj = util.errorObj; - - function catchFilter(instances, cb, promise) { - return function (e) { - var boundTo = promise._boundValue(); - predicateLoop: for (var i = 0; i < instances.length; ++i) { - var item = instances[i]; - - if ( - item === Error || - (item != null && item.prototype instanceof Error) - ) { - if (e instanceof item) { - return tryCatch(cb).call(boundTo, e); - } - } else if (typeof item === "function") { - var matchesPredicate = tryCatch(item).call(boundTo, e); - if (matchesPredicate === errorObj) { - return matchesPredicate; - } else if (matchesPredicate) { - return tryCatch(cb).call(boundTo, e); - } - } else if (util.isObject(e)) { - var keys = getKeys(item); - for (var j = 0; j < keys.length; ++j) { - var key = keys[j]; - if (item[key] != e[key]) { - continue predicateLoop; - } - } - return tryCatch(cb).call(boundTo, e); - } - } - return NEXT_FILTER; - }; - } - return catchFilter; - }; - /***/ - }, +module.exports = __nccwpck_require__(2324).get().Decimal128; - /***/ 647: /***/ (module) => { - "use strict"; - module.exports = function (Promise) { - var longStackTraces = false; - var contextStack = []; +/***/ }), - Promise.prototype._promiseCreated = function () {}; - Promise.prototype._pushContext = function () {}; - Promise.prototype._popContext = function () { - return null; - }; - Promise._peekContext = Promise.prototype._peekContext = function () {}; +/***/ 3000: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - function Context() { - this._trace = new Context.CapturedTrace(peekContext()); - } - Context.prototype._pushContext = function () { - if (this._trace !== undefined) { - this._trace._promiseCreated = null; - contextStack.push(this._trace); - } - }; +"use strict"; - Context.prototype._popContext = function () { - if (this._trace !== undefined) { - var trace = contextStack.pop(); - var ret = trace._promiseCreated; - trace._promiseCreated = null; - return ret; - } - return null; - }; +/*! + * Module exports. + */ - function createContext() { - if (longStackTraces) return new Context(); - } - function peekContext() { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; - } - return undefined; - } - Context.CapturedTrace = null; - Context.create = createContext; - Context.deactivateLongStackTraces = function () {}; - Context.activateLongStackTraces = function () { - var Promise_pushContext = Promise.prototype._pushContext; - var Promise_popContext = Promise.prototype._popContext; - var Promise_PeekContext = Promise._peekContext; - var Promise_peekContext = Promise.prototype._peekContext; - var Promise_promiseCreated = Promise.prototype._promiseCreated; - Context.deactivateLongStackTraces = function () { - Promise.prototype._pushContext = Promise_pushContext; - Promise.prototype._popContext = Promise_popContext; - Promise._peekContext = Promise_PeekContext; - Promise.prototype._peekContext = Promise_peekContext; - Promise.prototype._promiseCreated = Promise_promiseCreated; - longStackTraces = false; - }; - longStackTraces = true; - Promise.prototype._pushContext = Context.prototype._pushContext; - Promise.prototype._popContext = Context.prototype._popContext; - Promise._peekContext = Promise.prototype._peekContext = peekContext; - Promise.prototype._promiseCreated = function () { - var ctx = this._peekContext(); - if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; - }; - }; - return Context; - }; - /***/ - }, +exports.Array = __nccwpck_require__(1089); +exports.Buffer = __nccwpck_require__(5505); - /***/ 1234: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function (Promise, Context) { - var getDomain = Promise._getDomain; - var async = Promise._async; - var Warning = __nccwpck_require__(1522).Warning; - var util = __nccwpck_require__(2122); - var canAttachTrace = util.canAttachTrace; - var unhandledRejectionHandled; - var possiblyUnhandledRejection; - var bluebirdFramePattern = - /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; - var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; - var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; - var stackFramePattern = null; - var formatStack = null; - var indentStackFrames = false; - var printWarning; - var debugging = !!( - util.env("BLUEBIRD_DEBUG") != 0 && - (false || - util.env("BLUEBIRD_DEBUG") || - util.env("NODE_ENV") === "development") - ); +exports.Document = // @deprecate +exports.Embedded = __nccwpck_require__(9999); - var warnings = !!( - util.env("BLUEBIRD_WARNINGS") != 0 && - (debugging || util.env("BLUEBIRD_WARNINGS")) - ); +exports.DocumentArray = __nccwpck_require__(3369); +exports.Decimal128 = __nccwpck_require__(8319); +exports.ObjectId = __nccwpck_require__(2706); - var longStackTraces = !!( - util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && - (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")) - ); +exports.Map = __nccwpck_require__(9390); - var wForgottenReturn = - util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && - (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); +exports.Subdocument = __nccwpck_require__(7302); - Promise.prototype.suppressUnhandledRejections = function () { - var target = this._target(); - target._bitField = (target._bitField & ~1048576) | 524288; - }; - Promise.prototype._ensurePossibleRejectionHandled = function () { - if ((this._bitField & 524288) !== 0) return; - this._setRejectionIsUnhandled(); - var self = this; - setTimeout(function () { - self._notifyUnhandledRejection(); - }, 1); - }; +/***/ }), - Promise.prototype._notifyUnhandledRejectionIsHandled = function () { - fireRejectionEvent( - "rejectionHandled", - unhandledRejectionHandled, - undefined, - this - ); - }; +/***/ 9390: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Promise.prototype._setReturnedNonUndefined = function () { - this._bitField = this._bitField | 268435456; - }; +"use strict"; - Promise.prototype._returnedNonUndefined = function () { - return (this._bitField & 268435456) !== 0; - }; - Promise.prototype._notifyUnhandledRejection = function () { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue(); - this._setUnhandledRejectionIsNotified(); - fireRejectionEvent( - "unhandledRejection", - possiblyUnhandledRejection, - reason, - this - ); - } - }; +const Mixed = __nccwpck_require__(7495); +const ObjectId = __nccwpck_require__(2706); +const clone = __nccwpck_require__(5092); +const deepEqual = __nccwpck_require__(9232).deepEqual; +const get = __nccwpck_require__(8730); +const getConstructorName = __nccwpck_require__(7323); +const handleSpreadDoc = __nccwpck_require__(5232); +const util = __nccwpck_require__(1669); +const specialProperties = __nccwpck_require__(6786); - Promise.prototype._setUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField | 262144; - }; +const populateModelSymbol = __nccwpck_require__(3240).populateModelSymbol; - Promise.prototype._unsetUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField & ~262144; - }; +/*! + * ignore + */ - Promise.prototype._isUnhandledRejectionNotified = function () { - return (this._bitField & 262144) > 0; - }; +class MongooseMap extends Map { + constructor(v, path, doc, schemaType) { + if (getConstructorName(v) === 'Object') { + v = Object.keys(v).reduce((arr, key) => arr.concat([[key, v[key]]]), []); + } + super(v); + this.$__parent = doc != null && doc.$__ != null ? doc : null; + this.$__path = path; + this.$__schemaType = schemaType == null ? new Mixed(path) : schemaType; - Promise.prototype._setRejectionIsUnhandled = function () { - this._bitField = this._bitField | 1048576; - }; + this.$__runDeferred(); + } - Promise.prototype._unsetRejectionIsUnhandled = function () { - this._bitField = this._bitField & ~1048576; - if (this._isUnhandledRejectionNotified()) { - this._unsetUnhandledRejectionIsNotified(); - this._notifyUnhandledRejectionIsHandled(); - } - }; + $init(key, value) { + checkValidKey(key); - Promise.prototype._isRejectionUnhandled = function () { - return (this._bitField & 1048576) > 0; - }; + super.set(key, value); - Promise.prototype._warn = function ( - message, - shouldUseOwnTrace, - promise - ) { - return warn(message, shouldUseOwnTrace, promise || this); - }; + if (value != null && value.$isSingleNested) { + value.$basePath = this.$__path + '.' + key; + } + } - Promise.onPossiblyUnhandledRejection = function (fn) { - var domain = getDomain(); - possiblyUnhandledRejection = - typeof fn === "function" - ? domain === null - ? fn - : util.domainBind(domain, fn) - : undefined; - }; + $__set(key, value) { + super.set(key, value); + } - Promise.onUnhandledRejectionHandled = function (fn) { - var domain = getDomain(); - unhandledRejectionHandled = - typeof fn === "function" - ? domain === null - ? fn - : util.domainBind(domain, fn) - : undefined; - }; + get(key, options) { + if (key instanceof ObjectId) { + key = key.toString(); + } - var disableLongStackTraces = function () {}; - Promise.longStackTraces = function () { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error( - "cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a" - ); - } - if (!config.longStackTraces && longStackTracesIsSupported()) { - var Promise_captureStackTrace = - Promise.prototype._captureStackTrace; - var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; - config.longStackTraces = true; - disableLongStackTraces = function () { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error( - "cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a" - ); - } - Promise.prototype._captureStackTrace = Promise_captureStackTrace; - Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; - Context.deactivateLongStackTraces(); - async.enableTrampoline(); - config.longStackTraces = false; - }; - Promise.prototype._captureStackTrace = - longStackTracesCaptureStackTrace; - Promise.prototype._attachExtraTrace = - longStackTracesAttachExtraTrace; - Context.activateLongStackTraces(); - async.disableTrampolineIfNecessary(); - } - }; + options = options || {}; + if (options.getters === false) { + return super.get(key); + } + return this.$__schemaType.applyGetters(super.get(key), this.$__parent); + } - Promise.hasLongStackTraces = function () { - return config.longStackTraces && longStackTracesIsSupported(); - }; + set(key, value) { + if (key instanceof ObjectId) { + key = key.toString(); + } - var fireDomEvent = (function () { - try { - if (typeof CustomEvent === "function") { - var event = new CustomEvent("CustomEvent"); - util.global.dispatchEvent(event); - return function (name, event) { - var domEvent = new CustomEvent(name.toLowerCase(), { - detail: event, - cancelable: true, - }); - return !util.global.dispatchEvent(domEvent); - }; - } else if (typeof Event === "function") { - var event = new Event("CustomEvent"); - util.global.dispatchEvent(event); - return function (name, event) { - var domEvent = new Event(name.toLowerCase(), { - cancelable: true, - }); - domEvent.detail = event; - return !util.global.dispatchEvent(domEvent); - }; - } else { - var event = document.createEvent("CustomEvent"); - event.initCustomEvent("testingtheevent", false, true, {}); - util.global.dispatchEvent(event); - return function (name, event) { - var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent( - name.toLowerCase(), - false, - true, - event - ); - return !util.global.dispatchEvent(domEvent); - }; - } - } catch (e) {} - return function () { - return false; - }; - })(); + checkValidKey(key); + value = handleSpreadDoc(value); - var fireGlobalEvent = (function () { - if (util.isNode) { - return function () { - return process.emit.apply(process, arguments); - }; - } else { - if (!util.global) { - return function () { - return false; - }; - } - return function (name) { - var methodName = "on" + name.toLowerCase(); - var method = util.global[methodName]; - if (!method) return false; - method.apply(util.global, [].slice.call(arguments, 1)); - return true; - }; - } - })(); + // Weird, but because you can't assign to `this` before calling `super()` + // you can't get access to `$__schemaType` to cast in the initial call to + // `set()` from the `super()` constructor. - function generatePromiseLifecycleEventObject(name, promise) { - return { promise: promise }; - } + if (this.$__schemaType == null) { + this.$__deferred = this.$__deferred || []; + this.$__deferred.push({ key: key, value: value }); + return; + } - var eventToObjectGenerator = { - promiseCreated: generatePromiseLifecycleEventObject, - promiseFulfilled: generatePromiseLifecycleEventObject, - promiseRejected: generatePromiseLifecycleEventObject, - promiseResolved: generatePromiseLifecycleEventObject, - promiseCancelled: generatePromiseLifecycleEventObject, - promiseChained: function (name, promise, child) { - return { promise: promise, child: child }; - }, - warning: function (name, warning) { - return { warning: warning }; - }, - unhandledRejection: function (name, reason, promise) { - return { reason: reason, promise: promise }; - }, - rejectionHandled: generatePromiseLifecycleEventObject, - }; + const fullPath = this.$__path + '.' + key; + const populated = this.$__parent != null && this.$__parent.$__ ? + this.$__parent.$populated(fullPath) || this.$__parent.$populated(this.$__path) : + null; + const priorVal = this.get(key); - var activeFireEvent = function (name) { - var globalEventFired = false; - try { - globalEventFired = fireGlobalEvent.apply(null, arguments); - } catch (e) { - async.throwLater(e); - globalEventFired = true; - } + if (populated != null) { + if (value.$__ == null) { + value = new populated.options[populateModelSymbol](value); + } + value.$__.wasPopulated = true; + } else { + try { + value = this.$__schemaType. + applySetters(value, this.$__parent, false, this.get(key), { path: fullPath }); + } catch (error) { + if (this.$__parent != null && this.$__parent.$__ != null) { + this.$__parent.invalidate(fullPath, error); + return; + } + throw error; + } + } - var domEventFired = false; - try { - domEventFired = fireDomEvent( - name, - eventToObjectGenerator[name].apply(null, arguments) - ); - } catch (e) { - async.throwLater(e); - domEventFired = true; - } + super.set(key, value); - return domEventFired || globalEventFired; - }; + if (value != null && value.$isSingleNested) { + value.$basePath = this.$__path + '.' + key; + } - Promise.config = function (opts) { - opts = Object(opts); - if ("longStackTraces" in opts) { - if (opts.longStackTraces) { - Promise.longStackTraces(); - } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { - disableLongStackTraces(); - } - } - if ("warnings" in opts) { - var warningsOption = opts.warnings; - config.warnings = !!warningsOption; - wForgottenReturn = config.warnings; - - if (util.isObject(warningsOption)) { - if ("wForgottenReturn" in warningsOption) { - wForgottenReturn = !!warningsOption.wForgottenReturn; - } - } - } - if ( - "cancellation" in opts && - opts.cancellation && - !config.cancellation - ) { - if (async.haveItemsQueued()) { - throw new Error( - "cannot enable cancellation after promises are in use" - ); - } - Promise.prototype._clearCancellationData = - cancellationClearCancellationData; - Promise.prototype._propagateFrom = cancellationPropagateFrom; - Promise.prototype._onCancel = cancellationOnCancel; - Promise.prototype._setOnCancel = cancellationSetOnCancel; - Promise.prototype._attachCancellationCallback = - cancellationAttachCancellationCallback; - Promise.prototype._execute = cancellationExecute; - propagateFromFunction = cancellationPropagateFrom; - config.cancellation = true; - } - if ("monitoring" in opts) { - if (opts.monitoring && !config.monitoring) { - config.monitoring = true; - Promise.prototype._fireEvent = activeFireEvent; - } else if (!opts.monitoring && config.monitoring) { - config.monitoring = false; - Promise.prototype._fireEvent = defaultFireEvent; - } - } - return Promise; - }; + const parent = this.$__parent; + if (parent != null && parent.$__ != null && !deepEqual(value, priorVal)) { + parent.markModified(this.$__path + '.' + key); + } + } - function defaultFireEvent() { - return false; - } + clear() { + super.clear(); + const parent = this.$__parent; + if (parent != null) { + parent.markModified(this.$__path); + } + } - Promise.prototype._fireEvent = defaultFireEvent; - Promise.prototype._execute = function (executor, resolve, reject) { - try { - executor(resolve, reject); - } catch (e) { - return e; - } - }; - Promise.prototype._onCancel = function () {}; - Promise.prototype._setOnCancel = function (handler) {}; - Promise.prototype._attachCancellationCallback = function (onCancel) {}; - Promise.prototype._captureStackTrace = function () {}; - Promise.prototype._attachExtraTrace = function () {}; - Promise.prototype._clearCancellationData = function () {}; - Promise.prototype._propagateFrom = function (parent, flags) {}; - - function cancellationExecute(executor, resolve, reject) { - var promise = this; - try { - executor(resolve, reject, function (onCancel) { - if (typeof onCancel !== "function") { - throw new TypeError( - "onCancel must be a function, got: " + util.toString(onCancel) - ); - } - promise._attachCancellationCallback(onCancel); - }); - } catch (e) { - return e; - } - } + delete(key) { + if (key instanceof ObjectId) { + key = key.toString(); + } - function cancellationAttachCancellationCallback(onCancel) { - if (!this._isCancellable()) return this; + this.set(key, undefined); + super.delete(key); + } - var previousOnCancel = this._onCancel(); - if (previousOnCancel !== undefined) { - if (util.isArray(previousOnCancel)) { - previousOnCancel.push(onCancel); - } else { - this._setOnCancel([previousOnCancel, onCancel]); - } - } else { - this._setOnCancel(onCancel); - } - } + toBSON() { + return new Map(this); + } - function cancellationOnCancel() { - return this._onCancelField; - } + toObject(options) { + if (get(options, 'flattenMaps')) { + const ret = {}; + const keys = this.keys(); + for (const key of keys) { + ret[key] = clone(this.get(key), options); + } + return ret; + } - function cancellationSetOnCancel(onCancel) { - this._onCancelField = onCancel; - } + return new Map(this); + } - function cancellationClearCancellationData() { - this._cancellationParent = undefined; - this._onCancelField = undefined; - } + $toObject() { + return this.constructor.prototype.toObject.apply(this, arguments); + } - function cancellationPropagateFrom(parent, flags) { - if ((flags & 1) !== 0) { - this._cancellationParent = parent; - var branchesRemainingToCancel = parent._branchesRemainingToCancel; - if (branchesRemainingToCancel === undefined) { - branchesRemainingToCancel = 0; - } - parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; - } - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } - } + toJSON(options) { + if (get(options, 'flattenMaps', true)) { + const ret = {}; + const keys = this.keys(); + for (const key of keys) { + ret[key] = clone(this.get(key), options); + } + return ret; + } - function bindingPropagateFrom(parent, flags) { - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } - } - var propagateFromFunction = bindingPropagateFrom; + return new Map(this); + } - function boundValueFunction() { - var ret = this._boundTo; - if (ret !== undefined) { - if (ret instanceof Promise) { - if (ret.isFulfilled()) { - return ret.value(); - } else { - return undefined; - } - } - } - return ret; - } + inspect() { + return new Map(this); + } - function longStackTracesCaptureStackTrace() { - this._trace = new CapturedTrace(this._peekContext()); - } + $__runDeferred() { + if (!this.$__deferred) { + return; + } - function longStackTracesAttachExtraTrace(error, ignoreSelf) { - if (canAttachTrace(error)) { - var trace = this._trace; - if (trace !== undefined) { - if (ignoreSelf) trace = trace._parent; - } - if (trace !== undefined) { - trace.attachExtraTrace(error); - } else if (!error.__stackCleaned__) { - var parsed = parseStackAndMessage(error); - util.notEnumerableProp( - error, - "stack", - parsed.message + "\n" + parsed.stack.join("\n") - ); - util.notEnumerableProp(error, "__stackCleaned__", true); - } - } - } + for (const keyValueObject of this.$__deferred) { + this.set(keyValueObject.key, keyValueObject.value); + } - function checkForgottenReturns( - returnValue, - promiseCreated, - name, - promise, - parent - ) { - if ( - returnValue === undefined && - promiseCreated !== null && - wForgottenReturn - ) { - if (parent !== undefined && parent._returnedNonUndefined()) return; - if ((promise._bitField & 65535) === 0) return; - - if (name) name = name + " "; - var handlerLine = ""; - var creatorLine = ""; - if (promiseCreated._trace) { - var traceLines = promiseCreated._trace.stack.split("\n"); - var stack = cleanStack(traceLines); - for (var i = stack.length - 1; i >= 0; --i) { - var line = stack[i]; - if (!nodeFramePattern.test(line)) { - var lineMatches = line.match(parseLinePattern); - if (lineMatches) { - handlerLine = - "at " + - lineMatches[1] + - ":" + - lineMatches[2] + - ":" + - lineMatches[3] + - " "; - } - break; - } - } + this.$__deferred = null; + } +} + +if (util.inspect.custom) { + Object.defineProperty(MongooseMap.prototype, util.inspect.custom, { + enumerable: false, + writable: false, + configurable: false, + value: MongooseMap.prototype.inspect + }); +} + +Object.defineProperty(MongooseMap.prototype, '$__set', { + enumerable: false, + writable: true, + configurable: false +}); + +Object.defineProperty(MongooseMap.prototype, '$__parent', { + enumerable: false, + writable: true, + configurable: false +}); + +Object.defineProperty(MongooseMap.prototype, '$__path', { + enumerable: false, + writable: true, + configurable: false +}); + +Object.defineProperty(MongooseMap.prototype, '$__schemaType', { + enumerable: false, + writable: true, + configurable: false +}); + +Object.defineProperty(MongooseMap.prototype, '$isMongooseMap', { + enumerable: false, + writable: false, + configurable: false, + value: true +}); + +Object.defineProperty(MongooseMap.prototype, '$__deferredCalls', { + enumerable: false, + writable: false, + configurable: false, + value: true +}); + +/*! + * Since maps are stored as objects under the hood, keys must be strings + * and can't contain any invalid characters + */ - if (stack.length > 0) { - var firstUserLine = stack[0]; - for (var i = 0; i < traceLines.length; ++i) { - if (traceLines[i] === firstUserLine) { - if (i > 0) { - creatorLine = "\n" + traceLines[i - 1]; - } - break; - } - } - } - } - var msg = - "a promise was created in a " + - name + - "handler " + - handlerLine + - "but was not returned from it, " + - "see http://goo.gl/rRqMUw" + - creatorLine; - promise._warn(msg, true, promiseCreated); - } - } +function checkValidKey(key) { + const keyType = typeof key; + if (keyType !== 'string') { + throw new TypeError(`Mongoose maps only support string keys, got ${keyType}`); + } + if (key.startsWith('$')) { + throw new Error(`Mongoose maps do not support keys that start with "$", got "${key}"`); + } + if (key.includes('.')) { + throw new Error(`Mongoose maps do not support keys that contain ".", got "${key}"`); + } + if (specialProperties.has(key)) { + throw new Error(`Mongoose maps do not support reserved key name "${key}"`); + } +} - function deprecated(name, replacement) { - var message = - name + " is deprecated and will be removed in a future version."; - if (replacement) message += " Use " + replacement + " instead."; - return warn(message); - } +module.exports = MongooseMap; - function warn(message, shouldUseOwnTrace, promise) { - if (!config.warnings) return; - var warning = new Warning(message); - var ctx; - if (shouldUseOwnTrace) { - promise._attachExtraTrace(warning); - } else if (config.longStackTraces && (ctx = Promise._peekContext())) { - ctx.attachExtraTrace(warning); - } else { - var parsed = parseStackAndMessage(warning); - warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); - } - if (!activeFireEvent("warning", warning)) { - formatAndLogError(warning, "", true); - } - } +/***/ }), - function reconstructStack(message, stacks) { - for (var i = 0; i < stacks.length - 1; ++i) { - stacks[i].push("From previous event:"); - stacks[i] = stacks[i].join("\n"); - } - if (i < stacks.length) { - stacks[i] = stacks[i].join("\n"); - } - return message + "\n" + stacks.join("\n"); - } +/***/ 2706: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function removeDuplicateOrEmptyJumps(stacks) { - for (var i = 0; i < stacks.length; ++i) { - if ( - stacks[i].length === 0 || - (i + 1 < stacks.length && stacks[i][0] === stacks[i + 1][0]) - ) { - stacks.splice(i, 1); - i--; - } - } - } +"use strict"; +/** + * ObjectId type constructor + * + * ####Example + * + * const id = new mongoose.Types.ObjectId; + * + * @constructor ObjectId + */ - function removeCommonRoots(stacks) { - var current = stacks[0]; - for (var i = 1; i < stacks.length; ++i) { - var prev = stacks[i]; - var currentLastIndex = current.length - 1; - var currentLastLine = current[currentLastIndex]; - var commonRootMeetPoint = -1; - for (var j = prev.length - 1; j >= 0; --j) { - if (prev[j] === currentLastLine) { - commonRootMeetPoint = j; - break; - } - } - for (var j = commonRootMeetPoint; j >= 0; --j) { - var line = prev[j]; - if (current[currentLastIndex] === line) { - current.pop(); - currentLastIndex--; - } else { - break; - } - } - current = prev; - } - } +const ObjectId = __nccwpck_require__(2324).get().ObjectId; +const objectIdSymbol = __nccwpck_require__(3240).objectIdSymbol; - function cleanStack(stack) { - var ret = []; - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - var isTraceLine = - " (No stack trace)" === line || stackFramePattern.test(line); - var isInternalFrame = isTraceLine && shouldIgnore(line); - if (isTraceLine && !isInternalFrame) { - if (indentStackFrames && line.charAt(0) !== " ") { - line = " " + line; - } - ret.push(line); - } - } - return ret; - } +/*! + * Getter for convenience with populate, see gh-6115 + */ - function stackFramesAsArray(error) { - var stack = error.stack.replace(/\s+$/g, "").split("\n"); - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - if ( - " (No stack trace)" === line || - stackFramePattern.test(line) - ) { - break; - } - } - if (i > 0 && error.name != "SyntaxError") { - stack = stack.slice(i); - } - return stack; - } +Object.defineProperty(ObjectId.prototype, '_id', { + enumerable: false, + configurable: true, + get: function() { + return this; + } +}); - function parseStackAndMessage(error) { - var stack = error.stack; - var message = error.toString(); - stack = - typeof stack === "string" && stack.length > 0 - ? stackFramesAsArray(error) - : [" (No stack trace)"]; - return { - message: message, - stack: error.name == "SyntaxError" ? stack : cleanStack(stack), - }; - } +/*! + * Convenience `valueOf()` to allow comparing ObjectIds using double equals re: gh-7299 + */ - function formatAndLogError(error, title, isSoft) { - if (typeof console !== "undefined") { - var message; - if (util.isObject(error)) { - var stack = error.stack; - message = title + formatStack(stack, error); - } else { - message = title + String(error); - } - if (typeof printWarning === "function") { - printWarning(message, isSoft); - } else if ( - typeof console.log === "function" || - typeof console.log === "object" - ) { - console.log(message); - } - } - } - function fireRejectionEvent(name, localHandler, reason, promise) { - var localEventFired = false; - try { - if (typeof localHandler === "function") { - localEventFired = true; - if (name === "rejectionHandled") { - localHandler(promise); - } else { - localHandler(reason, promise); - } - } - } catch (e) { - async.throwLater(e); - } +if (!ObjectId.prototype.hasOwnProperty('valueOf')) { + ObjectId.prototype.valueOf = function objectIdValueOf() { + return this.toString(); + }; +} - if (name === "unhandledRejection") { - if (!activeFireEvent(name, reason, promise) && !localEventFired) { - formatAndLogError(reason, "Unhandled rejection "); - } - } else { - activeFireEvent(name, promise); - } - } +ObjectId.prototype[objectIdSymbol] = true; - function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + (obj.name || "anonymous") + "]"; - } else { - str = - obj && typeof obj.toString === "function" - ? obj.toString() - : util.toString(obj); - var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; - if (ruselessToString.test(str)) { - try { - var newStr = JSON.stringify(obj); - str = newStr; - } catch (e) {} - } - if (str.length === 0) { - str = "(empty array)"; - } - } - return "(<" + snip(str) + ">, no stack trace)"; - } +module.exports = ObjectId; - function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; - } - return str.substr(0, maxChars - 3) + "..."; - } - function longStackTracesIsSupported() { - return typeof captureStackTrace === "function"; - } +/***/ }), - var shouldIgnore = function () { - return false; - }; - var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; - function parseLineInfo(line) { - var matches = line.match(parseLineInfoRegex); - if (matches) { - return { - fileName: matches[1], - line: parseInt(matches[2], 10), - }; - } - } +/***/ 7302: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function setBounds(firstLineError, lastLineError) { - if (!longStackTracesIsSupported()) return; - var firstStackLines = firstLineError.stack.split("\n"); - var lastStackLines = lastLineError.stack.split("\n"); - var firstIndex = -1; - var lastIndex = -1; - var firstFileName; - var lastFileName; - for (var i = 0; i < firstStackLines.length; ++i) { - var result = parseLineInfo(firstStackLines[i]); - if (result) { - firstFileName = result.fileName; - firstIndex = result.line; - break; - } - } - for (var i = 0; i < lastStackLines.length; ++i) { - var result = parseLineInfo(lastStackLines[i]); - if (result) { - lastFileName = result.fileName; - lastIndex = result.line; - break; - } - } - if ( - firstIndex < 0 || - lastIndex < 0 || - !firstFileName || - !lastFileName || - firstFileName !== lastFileName || - firstIndex >= lastIndex - ) { - return; - } +"use strict"; - shouldIgnore = function (line) { - if (bluebirdFramePattern.test(line)) return true; - var info = parseLineInfo(line); - if (info) { - if ( - info.fileName === firstFileName && - firstIndex <= info.line && - info.line <= lastIndex - ) { - return true; - } - } - return false; - }; - } - function CapturedTrace(parent) { - this._parent = parent; - this._promisesCreated = 0; - var length = (this._length = - 1 + (parent === undefined ? 0 : parent._length)); - captureStackTrace(this, CapturedTrace); - if (length > 32) this.uncycle(); - } - util.inherits(CapturedTrace, Error); - Context.CapturedTrace = CapturedTrace; +const Document = __nccwpck_require__(6717); +const immediate = __nccwpck_require__(4830); +const internalToObjectOptions = __nccwpck_require__(5684)/* .internalToObjectOptions */ .h; +const promiseOrCallback = __nccwpck_require__(4046); +const util = __nccwpck_require__(1669); +const utils = __nccwpck_require__(9232); - CapturedTrace.prototype.uncycle = function () { - var length = this._length; - if (length < 2) return; - var nodes = []; - var stackToIndex = {}; +module.exports = Subdocument; - for (var i = 0, node = this; node !== undefined; ++i) { - nodes.push(node); - node = node._parent; - } - length = this._length = i; - for (var i = length - 1; i >= 0; --i) { - var stack = nodes[i].stack; - if (stackToIndex[stack] === undefined) { - stackToIndex[stack] = i; - } - } - for (var i = 0; i < length; ++i) { - var currentStack = nodes[i].stack; - var index = stackToIndex[currentStack]; - if (index !== undefined && index !== i) { - if (index > 0) { - nodes[index - 1]._parent = undefined; - nodes[index - 1]._length = 1; - } - nodes[i]._parent = undefined; - nodes[i]._length = 1; - var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; - - if (index < length - 1) { - cycleEdgeNode._parent = nodes[index + 1]; - cycleEdgeNode._parent.uncycle(); - cycleEdgeNode._length = cycleEdgeNode._parent._length + 1; - } else { - cycleEdgeNode._parent = undefined; - cycleEdgeNode._length = 1; - } - var currentChildLength = cycleEdgeNode._length + 1; - for (var j = i - 2; j >= 0; --j) { - nodes[j]._length = currentChildLength; - currentChildLength++; - } - return; - } - } - }; +/** + * Subdocument constructor. + * + * @inherits Document + * @api private + */ - CapturedTrace.prototype.attachExtraTrace = function (error) { - if (error.__stackCleaned__) return; - this.uncycle(); - var parsed = parseStackAndMessage(error); - var message = parsed.message; - var stacks = [parsed.stack]; - - var trace = this; - while (trace !== undefined) { - stacks.push(cleanStack(trace.stack.split("\n"))); - trace = trace._parent; - } - removeCommonRoots(stacks); - removeDuplicateOrEmptyJumps(stacks); - util.notEnumerableProp( - error, - "stack", - reconstructStack(message, stacks) - ); - util.notEnumerableProp(error, "__stackCleaned__", true); - }; +function Subdocument(value, fields, parent, skipId, options) { + if (parent != null) { + // If setting a nested path, should copy isNew from parent re: gh-7048 + const parentOptions = { isNew: parent.isNew }; + if ('defaults' in parent.$__) { + parentOptions.defaults = parent.$__.defaults; + } + options = Object.assign({}, parentOptions, options); + } + if (options != null && options.path != null) { + this.$basePath = options.path; + } + Document.call(this, value, fields, skipId, options); - var captureStackTrace = (function stackDetection() { - var v8stackFramePattern = /^\s*at\s*/; - var v8stackFormatter = function (stack, error) { - if (typeof stack === "string") return stack; + delete this.$__.priorDoc; +} - if (error.name !== undefined && error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; +Subdocument.prototype = Object.create(Document.prototype); - if ( - typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function" - ) { - Error.stackTraceLimit += 6; - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - var captureStackTrace = Error.captureStackTrace; - - shouldIgnore = function (line) { - return bluebirdFramePattern.test(line); - }; - return function (receiver, ignoreUntil) { - Error.stackTraceLimit += 6; - captureStackTrace(receiver, ignoreUntil); - Error.stackTraceLimit -= 6; - }; - } - var err = new Error(); - - if ( - typeof err.stack === "string" && - err.stack.split("\n")[0].indexOf("stackDetection@") >= 0 - ) { - stackFramePattern = /@/; - formatStack = v8stackFormatter; - indentStackFrames = true; - return function captureStackTrace(o) { - o.stack = new Error().stack; - }; - } +Object.defineProperty(Subdocument.prototype, '$isSubdocument', { + configurable: false, + writable: false, + value: true +}); - var hasStackAfterThrow; - try { - throw new Error(); - } catch (e) { - hasStackAfterThrow = "stack" in e; - } - if ( - !("stack" in err) && - hasStackAfterThrow && - typeof Error.stackTraceLimit === "number" - ) { - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - return function captureStackTrace(o) { - Error.stackTraceLimit += 6; - try { - throw new Error(); - } catch (e) { - o.stack = e.stack; - } - Error.stackTraceLimit -= 6; - }; - } +Object.defineProperty(Subdocument.prototype, '$isSingleNested', { + configurable: false, + writable: false, + value: true +}); - formatStack = function (stack, error) { - if (typeof stack === "string") return stack; +/*! + * ignore + */ - if ( - (typeof error === "object" || typeof error === "function") && - error.name !== undefined && - error.message !== undefined - ) { - return error.toString(); - } - return formatNonError(error); - }; +Subdocument.prototype.toBSON = function() { + return this.toObject(internalToObjectOptions); +}; - return null; - })([]); +/** + * Used as a stub for middleware + * + * ####NOTE: + * + * _This is a no-op. Does not actually save the doc to the db._ + * + * @param {Function} [fn] + * @return {Promise} resolved Promise + * @api private + */ - if ( - typeof console !== "undefined" && - typeof console.warn !== "undefined" - ) { - printWarning = function (message) { - console.warn(message); - }; - if (util.isNode && process.stderr.isTTY) { - printWarning = function (message, isSoft) { - var color = isSoft ? "\u001b[33m" : "\u001b[31m"; - console.warn(color + message + "\u001b[0m\n"); - }; - } else if (!util.isNode && typeof new Error().stack === "string") { - printWarning = function (message, isSoft) { - console.warn( - "%c" + message, - isSoft ? "color: darkorange" : "color: red" - ); - }; - } - } +Subdocument.prototype.save = function(options, fn) { + if (typeof options === 'function') { + fn = options; + options = {}; + } + options = options || {}; - var config = { - warnings: warnings, - longStackTraces: false, - cancellation: false, - monitoring: false, - }; + if (!options.suppressWarning) { + utils.warn('mongoose: calling `save()` on a subdoc does **not** save ' + + 'the document to MongoDB, it only runs save middleware. ' + + 'Use `subdoc.save({ suppressWarning: true })` to hide this warning ' + + 'if you\'re sure this behavior is right for your app.'); + } - if (longStackTraces) Promise.longStackTraces(); + return promiseOrCallback(fn, cb => { + this.$__save(cb); + }); +}; - return { - longStackTraces: function () { - return config.longStackTraces; - }, - warnings: function () { - return config.warnings; - }, - cancellation: function () { - return config.cancellation; - }, - monitoring: function () { - return config.monitoring; - }, - propagateFromFunction: function () { - return propagateFromFunction; - }, - boundValueFunction: function () { - return boundValueFunction; - }, - checkForgottenReturns: checkForgottenReturns, - setBounds: setBounds, - warn: warn, - deprecated: deprecated, - CapturedTrace: CapturedTrace, - fireDomEvent: fireDomEvent, - fireGlobalEvent: fireGlobalEvent, - }; - }; +/*! + * Given a path relative to this document, return the path relative + * to the top-level document. + */ - /***/ - }, +Subdocument.prototype.$__fullPath = function(path) { + if (!this.$__.fullPath) { + this.ownerDocument(); + } - /***/ 9923: /***/ (module) => { - "use strict"; + return path ? + this.$__.fullPath + '.' + path : + this.$__.fullPath; +}; - module.exports = function (Promise) { - function returner() { - return this.value; - } - function thrower() { - throw this.reason; - } +/*! + * Given a path relative to this document, return the path relative + * to the top-level document. + */ - Promise.prototype["return"] = Promise.prototype.thenReturn = function ( - value - ) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - returner, - undefined, - undefined, - { value: value }, - undefined - ); - }; +Subdocument.prototype.$__pathRelativeToParent = function(p) { + if (p == null) { + return this.$basePath; + } + return [this.$basePath, p].join('.'); +}; - Promise.prototype["throw"] = Promise.prototype.thenThrow = function ( - reason - ) { - return this._then( - thrower, - undefined, - undefined, - { reason: reason }, - undefined - ); - }; +/** + * Used as a stub for middleware + * + * ####NOTE: + * + * _This is a no-op. Does not actually save the doc to the db._ + * + * @param {Function} [fn] + * @method $__save + * @api private + */ - Promise.prototype.catchThrow = function (reason) { - if (arguments.length <= 1) { - return this._then( - undefined, - thrower, - undefined, - { reason: reason }, - undefined - ); - } else { - var _reason = arguments[1]; - var handler = function () { - throw _reason; - }; - return this.caught(reason, handler); - } - }; +Subdocument.prototype.$__save = function(fn) { + return immediate(() => fn(null, this)); +}; - Promise.prototype.catchReturn = function (value) { - if (arguments.length <= 1) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - undefined, - returner, - undefined, - { value: value }, - undefined - ); - } else { - var _value = arguments[1]; - if (_value instanceof Promise) _value.suppressUnhandledRejections(); - var handler = function () { - return _value; - }; - return this.caught(value, handler); - } - }; - }; +/*! + * ignore + */ - /***/ - }, +Subdocument.prototype.$isValid = function(path) { + const parent = this.$parent(); + const fullPath = this.$__pathRelativeToParent(path); + if (parent != null && fullPath != null) { + return parent.$isValid(fullPath); + } + return Document.prototype.$isValid.call(this, path); +}; - /***/ 301: /***/ (module) => { - "use strict"; +/*! + * ignore + */ - module.exports = function (Promise, INTERNAL) { - var PromiseReduce = Promise.reduce; - var PromiseAll = Promise.all; +Subdocument.prototype.markModified = function(path) { + Document.prototype.markModified.call(this, path); + const parent = this.$parent(); + const fullPath = this.$__pathRelativeToParent(path); - function promiseAllThis() { - return PromiseAll(this); - } + if (parent == null || fullPath == null) { + return; + } - function PromiseMapSeries(promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, INTERNAL); - } + const myPath = this.$__pathRelativeToParent().replace(/\.$/, ''); + if (parent.isDirectModified(myPath) || this.isNew) { + return; + } + this.$__parent.markModified(fullPath, this); +}; - Promise.prototype.each = function (fn) { - return PromiseReduce(this, fn, INTERNAL, 0)._then( - promiseAllThis, - undefined, - undefined, - this, - undefined - ); - }; +/*! + * ignore + */ - Promise.prototype.mapSeries = function (fn) { - return PromiseReduce(this, fn, INTERNAL, INTERNAL); - }; +Subdocument.prototype.isModified = function(paths, modifiedPaths) { + const parent = this.$parent(); + if (parent != null) { + if (Array.isArray(paths) || typeof paths === 'string') { + paths = (Array.isArray(paths) ? paths : paths.split(' ')); + paths = paths.map(p => this.$__pathRelativeToParent(p)).filter(p => p != null); + } else if (!paths) { + paths = this.$__pathRelativeToParent(); + } - Promise.each = function (promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, 0)._then( - promiseAllThis, - undefined, - undefined, - promises, - undefined - ); - }; + return parent.$isModified(paths, modifiedPaths); + } - Promise.mapSeries = PromiseMapSeries; - }; + return Document.prototype.isModified.call(this, paths, modifiedPaths); +}; - /***/ - }, +/** + * Marks a path as valid, removing existing validation errors. + * + * @param {String} path the field to mark as valid + * @api private + * @method $markValid + * @receiver Subdocument + */ - /***/ 1522: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - var es5 = __nccwpck_require__(9432); - var Objectfreeze = es5.freeze; - var util = __nccwpck_require__(2122); - var inherits = util.inherits; - var notEnumerableProp = util.notEnumerableProp; - - function subError(nameProperty, defaultMessage) { - function SubError(message) { - if (!(this instanceof SubError)) return new SubError(message); - notEnumerableProp( - this, - "message", - typeof message === "string" ? message : defaultMessage - ); - notEnumerableProp(this, "name", nameProperty); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - Error.call(this); - } - } - inherits(SubError, Error); - return SubError; - } +Subdocument.prototype.$markValid = function(path) { + Document.prototype.$markValid.call(this, path); + const parent = this.$parent(); + const fullPath = this.$__pathRelativeToParent(path); + if (parent != null && fullPath != null) { + parent.$markValid(fullPath); + } +}; - var _TypeError, _RangeError; - var Warning = subError("Warning", "warning"); - var CancellationError = subError( - "CancellationError", - "cancellation error" - ); - var TimeoutError = subError("TimeoutError", "timeout error"); - var AggregateError = subError("AggregateError", "aggregate error"); - try { - _TypeError = TypeError; - _RangeError = RangeError; - } catch (e) { - _TypeError = subError("TypeError", "type error"); - _RangeError = subError("RangeError", "range error"); - } +/*! + * ignore + */ - var methods = ( - "join pop push shift unshift slice filter forEach some " + - "every map indexOf lastIndexOf reduce reduceRight sort reverse" - ).split(" "); +Subdocument.prototype.invalidate = function(path, err, val) { + Document.prototype.invalidate.call(this, path, err, val); - for (var i = 0; i < methods.length; ++i) { - if (typeof Array.prototype[methods[i]] === "function") { - AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; - } - } + const parent = this.$parent(); + const fullPath = this.$__pathRelativeToParent(path); + if (parent != null && fullPath != null) { + parent.invalidate(fullPath, err, val); + } else if (err.kind === 'cast' || err.name === 'CastError' || fullPath == null) { + throw err; + } - es5.defineProperty(AggregateError.prototype, "length", { - value: 0, - configurable: false, - writable: true, - enumerable: true, - }); - AggregateError.prototype["isOperational"] = true; - var level = 0; - AggregateError.prototype.toString = function () { - var indent = Array(level * 4 + 1).join(" "); - var ret = "\n" + indent + "AggregateError of:" + "\n"; - level++; - indent = Array(level * 4 + 1).join(" "); - for (var i = 0; i < this.length; ++i) { - var str = - this[i] === this ? "[Circular AggregateError]" : this[i] + ""; - var lines = str.split("\n"); - for (var j = 0; j < lines.length; ++j) { - lines[j] = indent + lines[j]; - } - str = lines.join("\n"); - ret += str + "\n"; - } - level--; - return ret; - }; + return this.ownerDocument().$__.validationError; +}; - function OperationalError(message) { - if (!(this instanceof OperationalError)) - return new OperationalError(message); - notEnumerableProp(this, "name", "OperationalError"); - notEnumerableProp(this, "message", message); - this.cause = message; - this["isOperational"] = true; +/*! + * ignore + */ - if (message instanceof Error) { - notEnumerableProp(this, "message", message.message); - notEnumerableProp(this, "stack", message.stack); - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - } - inherits(OperationalError, Error); - - var errorTypes = Error["__BluebirdErrorTypes__"]; - if (!errorTypes) { - errorTypes = Objectfreeze({ - CancellationError: CancellationError, - TimeoutError: TimeoutError, - OperationalError: OperationalError, - RejectionError: OperationalError, - AggregateError: AggregateError, - }); - es5.defineProperty(Error, "__BluebirdErrorTypes__", { - value: errorTypes, - writable: false, - enumerable: false, - configurable: false, - }); - } +Subdocument.prototype.$ignore = function(path) { + Document.prototype.$ignore.call(this, path); + const parent = this.$parent(); + const fullPath = this.$__pathRelativeToParent(path); + if (parent != null && fullPath != null) { + parent.$ignore(fullPath); + } +}; + +/** + * Returns the top level document of this sub-document. + * + * @return {Document} + */ + +Subdocument.prototype.ownerDocument = function() { + if (this.$__.ownerDocument) { + return this.$__.ownerDocument; + } - module.exports = { - Error: Error, - TypeError: _TypeError, - RangeError: _RangeError, - CancellationError: errorTypes.CancellationError, - OperationalError: errorTypes.OperationalError, - TimeoutError: errorTypes.TimeoutError, - AggregateError: errorTypes.AggregateError, - Warning: Warning, - }; + let parent = this; // eslint-disable-line consistent-this + const paths = []; + const seenDocs = new Set([parent]); - /***/ - }, + while (true) { + if (typeof parent.$__pathRelativeToParent !== 'function') { + break; + } + paths.unshift(parent.$__pathRelativeToParent(void 0, true)); + const _parent = parent.$parent(); + if (_parent == null) { + break; + } + parent = _parent; + if (seenDocs.has(parent)) { + throw new Error('Infinite subdocument loop: subdoc with _id ' + parent._id + ' is a parent of itself'); + } - /***/ 9432: /***/ (module) => { - var isES5 = (function () { - "use strict"; - return this === undefined; - })(); - - if (isES5) { - module.exports = { - freeze: Object.freeze, - defineProperty: Object.defineProperty, - getDescriptor: Object.getOwnPropertyDescriptor, - keys: Object.keys, - names: Object.getOwnPropertyNames, - getPrototypeOf: Object.getPrototypeOf, - isArray: Array.isArray, - isES5: isES5, - propertyIsWritable: function (obj, prop) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop); - return !!(!descriptor || descriptor.writable || descriptor.set); - }, - }; - } else { - var has = {}.hasOwnProperty; - var str = {}.toString; - var proto = {}.constructor.prototype; + seenDocs.add(parent); + } - var ObjectKeys = function (o) { - var ret = []; - for (var key in o) { - if (has.call(o, key)) { - ret.push(key); - } - } - return ret; - }; + this.$__.fullPath = paths.join('.'); - var ObjectGetDescriptor = function (o, key) { - return { value: o[key] }; - }; + this.$__.ownerDocument = parent; + return this.$__.ownerDocument; +}; - var ObjectDefineProperty = function (o, key, desc) { - o[key] = desc.value; - return o; - }; +/** + * Returns this sub-documents parent document. + * + * @api public + */ - var ObjectFreeze = function (obj) { - return obj; - }; +Subdocument.prototype.parent = function() { + return this.$__parent; +}; - var ObjectGetPrototypeOf = function (obj) { - try { - return Object(obj).constructor.prototype; - } catch (e) { - return proto; - } - }; +/** + * Returns this sub-documents parent document. + * + * @api public + */ - var ArrayIsArray = function (obj) { - try { - return str.call(obj) === "[object Array]"; - } catch (e) { - return false; - } - }; +Subdocument.prototype.$parent = Subdocument.prototype.parent; - module.exports = { - isArray: ArrayIsArray, - keys: ObjectKeys, - names: ObjectKeys, - defineProperty: ObjectDefineProperty, - getDescriptor: ObjectGetDescriptor, - freeze: ObjectFreeze, - getPrototypeOf: ObjectGetPrototypeOf, - isES5: isES5, - propertyIsWritable: function () { - return true; - }, - }; - } +/*! + * no-op for hooks + */ - /***/ - }, +Subdocument.prototype.$__remove = function(cb) { + if (cb == null) { + return; + } + return cb(null, this); +}; - /***/ 9180: /***/ (module) => { - "use strict"; +Subdocument.prototype.$__removeFromParent = function() { + this.$__parent.set(this.$basePath, null); +}; - module.exports = function (Promise, INTERNAL) { - var PromiseMap = Promise.map; +/** + * Null-out this subdoc + * + * @param {Object} [options] + * @param {Function} [callback] optional callback for compatibility with Document.prototype.remove + */ - Promise.prototype.filter = function (fn, options) { - return PromiseMap(this, fn, options, INTERNAL); - }; +Subdocument.prototype.remove = function(options, callback) { + if (typeof options === 'function') { + callback = options; + options = null; + } + registerRemoveListener(this); - Promise.filter = function (promises, fn, options) { - return PromiseMap(promises, fn, options, INTERNAL); - }; - }; + // If removing entire doc, no need to remove subdoc + if (!options || !options.noop) { + this.$__removeFromParent(); + } - /***/ - }, + return this.$__remove(callback); +}; - /***/ 3701: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function (Promise, tryConvertToPromise, NEXT_FILTER) { - var util = __nccwpck_require__(2122); - var CancellationError = Promise.CancellationError; - var errorObj = util.errorObj; - var catchFilter = __nccwpck_require__(8447)(NEXT_FILTER); - - function PassThroughHandlerContext(promise, type, handler) { - this.promise = promise; - this.type = type; - this.handler = handler; - this.called = false; - this.cancelPromise = null; - } - - PassThroughHandlerContext.prototype.isFinallyHandler = function () { - return this.type === 0; - }; +/*! + * ignore + */ - function FinallyHandlerCancelReaction(finallyHandler) { - this.finallyHandler = finallyHandler; - } +Subdocument.prototype.populate = function() { + throw new Error('Mongoose does not support calling populate() on nested ' + + 'docs. Instead of `doc.nested.populate("path")`, use ' + + '`doc.populate("nested.path")`'); +}; - FinallyHandlerCancelReaction.prototype._resultCancelled = function () { - checkCancel(this.finallyHandler); - }; +/** + * Helper for console.log + * + * @api public + */ - function checkCancel(ctx, reason) { - if (ctx.cancelPromise != null) { - if (arguments.length > 1) { - ctx.cancelPromise._reject(reason); - } else { - ctx.cancelPromise._cancel(); - } - ctx.cancelPromise = null; - return true; - } - return false; - } +Subdocument.prototype.inspect = function() { + return this.toObject({ + transform: false, + virtuals: false, + flattenDecimals: false + }); +}; + +if (util.inspect.custom) { + /*! + * Avoid Node deprecation warning DEP0079 + */ + + Subdocument.prototype[util.inspect.custom] = Subdocument.prototype.inspect; +} + +/*! + * Registers remove event listeners for triggering + * on subdocuments. + * + * @param {Subdocument} sub + * @api private + */ - function succeed() { - return finallyHandler.call( - this, - this.promise._target()._settledValue() - ); - } - function fail(reason) { - if (checkCancel(this, reason)) return; - errorObj.e = reason; - return errorObj; - } - function finallyHandler(reasonOrValue) { - var promise = this.promise; - var handler = this.handler; - - if (!this.called) { - this.called = true; - var ret = this.isFinallyHandler() - ? handler.call(promise._boundValue()) - : handler.call(promise._boundValue(), reasonOrValue); - if (ret === NEXT_FILTER) { - return ret; - } else if (ret !== undefined) { - promise._setReturnedNonUndefined(); - var maybePromise = tryConvertToPromise(ret, promise); - if (maybePromise instanceof Promise) { - if (this.cancelPromise != null) { - if (maybePromise._isCancelled()) { - var reason = new CancellationError( - "late cancellation observer" - ); - promise._attachExtraTrace(reason); - errorObj.e = reason; - return errorObj; - } else if (maybePromise.isPending()) { - maybePromise._attachCancellationCallback( - new FinallyHandlerCancelReaction(this) - ); - } - } - return maybePromise._then( - succeed, - fail, - undefined, - this, - undefined - ); - } - } - } +function registerRemoveListener(sub) { + let owner = sub.ownerDocument(); - if (promise.isRejected()) { - checkCancel(this); - errorObj.e = reasonOrValue; - return errorObj; - } else { - checkCancel(this); - return reasonOrValue; - } - } + function emitRemove() { + owner.$removeListener('save', emitRemove); + owner.$removeListener('remove', emitRemove); + sub.emit('remove', sub); + sub.constructor.emit('remove', sub); + owner = sub = null; + } - Promise.prototype._passThrough = function ( - handler, - type, - success, - fail - ) { - if (typeof handler !== "function") return this.then(); - return this._then( - success, - fail, - undefined, - new PassThroughHandlerContext(this, type, handler), - undefined - ); - }; + owner.$on('save', emitRemove); + owner.$on('remove', emitRemove); +} - Promise.prototype.lastly = Promise.prototype["finally"] = function ( - handler - ) { - return this._passThrough(handler, 0, finallyHandler, finallyHandler); - }; - Promise.prototype.tap = function (handler) { - return this._passThrough(handler, 1, finallyHandler); - }; +/***/ }), - Promise.prototype.tapCatch = function (handlerOrPredicate) { - var len = arguments.length; - if (len === 1) { - return this._passThrough( - handlerOrPredicate, - 1, - undefined, - finallyHandler - ); - } else { - var catchInstances = new Array(len - 1), - j = 0, - i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return Promise.reject( - new TypeError( - "tapCatch statement predicate: " + - "expecting an object but got " + - util.classString(item) - ) - ); - } - } - catchInstances.length = j; - var handler = arguments[i]; - return this._passThrough( - catchFilter(catchInstances, handler, this), - 1, - undefined, - finallyHandler - ); - } - }; +/***/ 9232: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return PassThroughHandlerContext; - }; +"use strict"; - /***/ - }, - /***/ 8498: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function ( - Promise, - apiRejection, - INTERNAL, - tryConvertToPromise, - Proxyable, - debug - ) { - var errors = __nccwpck_require__(1522); - var TypeError = errors.TypeError; - var util = __nccwpck_require__(2122); - var errorObj = util.errorObj; - var tryCatch = util.tryCatch; - var yieldHandlers = []; - - function promiseFromYieldHandler(value, yieldHandlers, traceParent) { - for (var i = 0; i < yieldHandlers.length; ++i) { - traceParent._pushContext(); - var result = tryCatch(yieldHandlers[i])(value); - traceParent._popContext(); - if (result === errorObj) { - traceParent._pushContext(); - var ret = Promise.reject(errorObj.e); - traceParent._popContext(); - return ret; - } - var maybePromise = tryConvertToPromise(result, traceParent); - if (maybePromise instanceof Promise) return maybePromise; - } - return null; - } +/*! + * Module dependencies. + */ - function PromiseSpawn( - generatorFunction, - receiver, - yieldHandler, - stack - ) { - if (debug.cancellation()) { - var internal = new Promise(INTERNAL); - var _finallyPromise = (this._finallyPromise = new Promise( - INTERNAL - )); - this._promise = internal.lastly(function () { - return _finallyPromise; - }); - internal._captureStackTrace(); - internal._setOnCancel(this); - } else { - var promise = (this._promise = new Promise(INTERNAL)); - promise._captureStackTrace(); - } - this._stack = stack; - this._generatorFunction = generatorFunction; - this._receiver = receiver; - this._generator = undefined; - this._yieldHandlers = - typeof yieldHandler === "function" - ? [yieldHandler].concat(yieldHandlers) - : yieldHandlers; - this._yieldedPromise = null; - this._cancellationPhase = false; - } - util.inherits(PromiseSpawn, Proxyable); - - PromiseSpawn.prototype._isResolved = function () { - return this._promise === null; - }; +const ms = __nccwpck_require__(900); +const mpath = __nccwpck_require__(8586); +const sliced = __nccwpck_require__(9889); +const Decimal = __nccwpck_require__(8319); +const ObjectId = __nccwpck_require__(2706); +const PopulateOptions = __nccwpck_require__(7038); +const clone = __nccwpck_require__(5092); +const immediate = __nccwpck_require__(4830); +const isObject = __nccwpck_require__(273); +const isBsonType = __nccwpck_require__(8275); +const getFunctionName = __nccwpck_require__(6621); +const isMongooseObject = __nccwpck_require__(7104); +const promiseOrCallback = __nccwpck_require__(4046); +const schemaMerge = __nccwpck_require__(2830); +const specialProperties = __nccwpck_require__(6786); +const { trustedSymbol } = __nccwpck_require__(7776); + +let Document; + +exports.specialProperties = specialProperties; + +/*! + * Produces a collection name from model `name`. By default, just returns + * the model name + * + * @param {String} name a model name + * @param {Function} pluralize function that pluralizes the collection name + * @return {String} a collection name + * @api private + */ - PromiseSpawn.prototype._cleanup = function () { - this._promise = this._generator = null; - if (debug.cancellation() && this._finallyPromise !== null) { - this._finallyPromise._fulfill(); - this._finallyPromise = null; - } - }; +exports.toCollectionName = function(name, pluralize) { + if (name === 'system.profile') { + return name; + } + if (name === 'system.indexes') { + return name; + } + if (typeof pluralize === 'function') { + return pluralize(name); + } + return name; +}; - PromiseSpawn.prototype._promiseCancelled = function () { - if (this._isResolved()) return; - var implementsReturn = - typeof this._generator["return"] !== "undefined"; +/*! + * Determines if `a` and `b` are deep equal. + * + * Modified from node/lib/assert.js + * + * @param {any} a a value to compare to `b` + * @param {any} b a value to compare to `a` + * @return {Boolean} + * @api private + */ - var result; - if (!implementsReturn) { - var reason = new Promise.CancellationError( - "generator .return() sentinel" - ); - Promise.coroutine.returnSentinel = reason; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - result = tryCatch(this._generator["throw"]).call( - this._generator, - reason - ); - this._promise._popContext(); - } else { - this._promise._pushContext(); - result = tryCatch(this._generator["return"]).call( - this._generator, - undefined - ); - this._promise._popContext(); - } - this._cancellationPhase = true; - this._yieldedPromise = null; - this._continue(result); - }; +exports.deepEqual = function deepEqual(a, b) { + if (a === b) { + return true; + } - PromiseSpawn.prototype._promiseFulfilled = function (value) { - this._yieldedPromise = null; - this._promise._pushContext(); - var result = tryCatch(this._generator.next).call( - this._generator, - value - ); - this._promise._popContext(); - this._continue(result); - }; + if (typeof a !== 'object' && typeof b !== 'object') { + return a === b; + } - PromiseSpawn.prototype._promiseRejected = function (reason) { - this._yieldedPromise = null; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - var result = tryCatch(this._generator["throw"]).call( - this._generator, - reason - ); - this._promise._popContext(); - this._continue(result); - }; + if (a instanceof Date && b instanceof Date) { + return a.getTime() === b.getTime(); + } - PromiseSpawn.prototype._resultCancelled = function () { - if (this._yieldedPromise instanceof Promise) { - var promise = this._yieldedPromise; - this._yieldedPromise = null; - promise.cancel(); - } - }; + if ((isBsonType(a, 'ObjectID') && isBsonType(b, 'ObjectID')) || + (isBsonType(a, 'Decimal128') && isBsonType(b, 'Decimal128'))) { + return a.toString() === b.toString(); + } - PromiseSpawn.prototype.promise = function () { - return this._promise; - }; + if (a instanceof RegExp && b instanceof RegExp) { + return a.source === b.source && + a.ignoreCase === b.ignoreCase && + a.multiline === b.multiline && + a.global === b.global; + } - PromiseSpawn.prototype._run = function () { - this._generator = this._generatorFunction.call(this._receiver); - this._receiver = this._generatorFunction = undefined; - this._promiseFulfilled(undefined); - }; + if (a == null || b == null) { + return false; + } - PromiseSpawn.prototype._continue = function (result) { - var promise = this._promise; - if (result === errorObj) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._rejectCallback(result.e, false); - } - } + if (a.prototype !== b.prototype) { + return false; + } - var value = result.value; - if (result.done === true) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._resolveCallback(value); - } - } else { - var maybePromise = tryConvertToPromise(value, this._promise); - if (!(maybePromise instanceof Promise)) { - maybePromise = promiseFromYieldHandler( - maybePromise, - this._yieldHandlers, - this._promise - ); - if (maybePromise === null) { - this._promiseRejected( - new TypeError( - "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace( - "%s", - String(value) - ) + - "From coroutine:\u000a" + - this._stack.split("\n").slice(1, -7).join("\n") - ) - ); - return; - } - } - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - if ((bitField & 50397184) === 0) { - this._yieldedPromise = maybePromise; - maybePromise._proxy(this, null); - } else if ((bitField & 33554432) !== 0) { - Promise._async.invoke( - this._promiseFulfilled, - this, - maybePromise._value() - ); - } else if ((bitField & 16777216) !== 0) { - Promise._async.invoke( - this._promiseRejected, - this, - maybePromise._reason() - ); - } else { - this._promiseCancelled(); - } - } - }; + if (a instanceof Map && b instanceof Map) { + return deepEqual(Array.from(a.keys()), Array.from(b.keys())) && + deepEqual(Array.from(a.values()), Array.from(b.values())); + } - Promise.coroutine = function (generatorFunction, options) { - if (typeof generatorFunction !== "function") { - throw new TypeError( - "generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a" - ); - } - var yieldHandler = Object(options).yieldHandler; - var PromiseSpawn$ = PromiseSpawn; - var stack = new Error().stack; - return function () { - var generator = generatorFunction.apply(this, arguments); - var spawn = new PromiseSpawn$( - undefined, - undefined, - yieldHandler, - stack - ); - var ret = spawn.promise(); - spawn._generator = generator; - spawn._promiseFulfilled(undefined); - return ret; - }; - }; + // Handle MongooseNumbers + if (a instanceof Number && b instanceof Number) { + return a.valueOf() === b.valueOf(); + } - Promise.coroutine.addYieldHandler = function (fn) { - if (typeof fn !== "function") { - throw new TypeError( - "expecting a function but got " + util.classString(fn) - ); - } - yieldHandlers.push(fn); - }; + if (Buffer.isBuffer(a)) { + return exports.buffer.areEqual(a, b); + } - Promise.spawn = function (generatorFunction) { - debug.deprecated("Promise.spawn()", "Promise.coroutine()"); - if (typeof generatorFunction !== "function") { - return apiRejection( - "generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a" - ); - } - var spawn = new PromiseSpawn(generatorFunction, this); - var ret = spawn.promise(); - spawn._run(Promise.spawn); - return ret; - }; - }; + if (Array.isArray(a) && Array.isArray(b)) { + const len = a.length; + if (len !== b.length) { + return false; + } + for (let i = 0; i < len; ++i) { + if (!deepEqual(a[i], b[i])) { + return false; + } + } + return true; + } - /***/ - }, + if (a.$__ != null) { + a = a._doc; + } else if (isMongooseObject(a)) { + a = a.toObject(); + } - /***/ 689: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function ( - Promise, - PromiseArray, - tryConvertToPromise, - INTERNAL, - async, - getDomain - ) { - var util = __nccwpck_require__(2122); - var canEvaluate = util.canEvaluate; - var tryCatch = util.tryCatch; - var errorObj = util.errorObj; - var reject; - - if (true) { - if (canEvaluate) { - var thenCallback = function (i) { - return new Function( - "value", - "holder", - " \n\ - 'use strict'; \n\ - holder.pIndex = value; \n\ - holder.checkFulfillment(this); \n\ - ".replace( - /Index/g, - i - ) - ); - }; + if (b.$__ != null) { + b = b._doc; + } else if (isMongooseObject(b)) { + b = b.toObject(); + } - var promiseSetter = function (i) { - return new Function( - "promise", - "holder", - " \n\ - 'use strict'; \n\ - holder.pIndex = promise; \n\ - ".replace( - /Index/g, - i - ) - ); - }; + const ka = Object.keys(a); + const kb = Object.keys(b); + const kaLength = ka.length; - var generateHolderClass = function (total) { - var props = new Array(total); - for (var i = 0; i < props.length; ++i) { - props[i] = "this.p" + (i + 1); - } - var assignment = props.join(" = ") + " = null;"; - var cancellationCode = - "var promise;\n" + - props - .map(function (prop) { - return ( - " \n\ - promise = " + - prop + - "; \n\ - if (promise instanceof Promise) { \n\ - promise.cancel(); \n\ - } \n\ - " - ); - }) - .join("\n"); - var passedArguments = props.join(", "); - var name = "Holder$" + total; - - var code = - "return function(tryCatch, errorObj, Promise, async) { \n\ - 'use strict'; \n\ - function [TheName](fn) { \n\ - [TheProperties] \n\ - this.fn = fn; \n\ - this.asyncNeeded = true; \n\ - this.now = 0; \n\ - } \n\ - \n\ - [TheName].prototype._callFunction = function(promise) { \n\ - promise._pushContext(); \n\ - var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ - promise._popContext(); \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(ret.e, false); \n\ - } else { \n\ - promise._resolveCallback(ret); \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype.checkFulfillment = function(promise) { \n\ - var now = ++this.now; \n\ - if (now === [TheTotal]) { \n\ - if (this.asyncNeeded) { \n\ - async.invoke(this._callFunction, this, promise); \n\ - } else { \n\ - this._callFunction(promise); \n\ - } \n\ - \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype._resultCancelled = function() { \n\ - [CancellationCode] \n\ - }; \n\ - \n\ - return [TheName]; \n\ - }(tryCatch, errorObj, Promise, async); \n\ - "; - - code = code - .replace(/\[TheName\]/g, name) - .replace(/\[TheTotal\]/g, total) - .replace(/\[ThePassedArguments\]/g, passedArguments) - .replace(/\[TheProperties\]/g, assignment) - .replace(/\[CancellationCode\]/g, cancellationCode); - - return new Function( - "tryCatch", - "errorObj", - "Promise", - "async", - code - )(tryCatch, errorObj, Promise, async); - }; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (kaLength !== kb.length) { + return false; + } - var holderClasses = []; - var thenCallbacks = []; - var promiseSetters = []; + // ~~~cheap key test + for (let i = kaLength - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) { + return false; + } + } - for (var i = 0; i < 8; ++i) { - holderClasses.push(generateHolderClass(i + 1)); - thenCallbacks.push(thenCallback(i + 1)); - promiseSetters.push(promiseSetter(i + 1)); - } + // equivalent values for every corresponding key, and + // ~~~possibly expensive deep test + for (const key of ka) { + if (!deepEqual(a[key], b[key])) { + return false; + } + } - reject = function (reason) { - this._reject(reason); - }; - } - } + return true; +}; - Promise.join = function () { - var last = arguments.length - 1; - var fn; - if (last > 0 && typeof arguments[last] === "function") { - fn = arguments[last]; - if (true) { - if (last <= 8 && canEvaluate) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var HolderClass = holderClasses[last - 1]; - var holder = new HolderClass(fn); - var callbacks = thenCallbacks; - - for (var i = 0; i < last; ++i) { - var maybePromise = tryConvertToPromise(arguments[i], ret); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - if ((bitField & 50397184) === 0) { - maybePromise._then( - callbacks[i], - reject, - undefined, - ret, - holder - ); - promiseSetters[i](maybePromise, holder); - holder.asyncNeeded = false; - } else if ((bitField & 33554432) !== 0) { - callbacks[i].call(ret, maybePromise._value(), holder); - } else if ((bitField & 16777216) !== 0) { - ret._reject(maybePromise._reason()); - } else { - ret._cancel(); - } - } else { - callbacks[i].call(ret, maybePromise, holder); - } - } +/*! + * Get the last element of an array + */ - if (!ret._isFateSealed()) { - if (holder.asyncNeeded) { - var domain = getDomain(); - if (domain !== null) { - holder.fn = util.domainBind(domain, holder.fn); - } - } - ret._setAsyncGuaranteed(); - ret._setOnCancel(holder); - } - return ret; - } - } - } - var $_len = arguments.length; - var args = new Array($_len); - for (var $_i = 0; $_i < $_len; ++$_i) { - args[$_i] = arguments[$_i]; - } - if (fn) args.pop(); - var ret = new PromiseArray(args).promise(); - return fn !== undefined ? ret.spread(fn) : ret; - }; - }; +exports.last = function(arr) { + if (arr.length > 0) { + return arr[arr.length - 1]; + } + return void 0; +}; - /***/ - }, +exports.clone = clone; - /***/ 377: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function ( - Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug - ) { - var getDomain = Promise._getDomain; - var util = __nccwpck_require__(2122); - var tryCatch = util.tryCatch; - var errorObj = util.errorObj; - var async = Promise._async; - - function MappingPromiseArray(promises, fn, limit, _filter) { - this.constructor$(promises); - this._promise._captureStackTrace(); - var domain = getDomain(); - this._callback = domain === null ? fn : util.domainBind(domain, fn); - this._preservedValues = - _filter === INTERNAL ? new Array(this.length()) : null; - this._limit = limit; - this._inFlight = 0; - this._queue = []; - async.invoke(this._asyncInit, this, undefined); - } - util.inherits(MappingPromiseArray, PromiseArray); - - MappingPromiseArray.prototype._asyncInit = function () { - this._init$(undefined, -2); - }; +/*! + * ignore + */ - MappingPromiseArray.prototype._init = function () {}; +exports.promiseOrCallback = promiseOrCallback; - MappingPromiseArray.prototype._promiseFulfilled = function ( - value, - index - ) { - var values = this._values; - var length = this.length(); - var preservedValues = this._preservedValues; - var limit = this._limit; - - if (index < 0) { - index = index * -1 - 1; - values[index] = value; - if (limit >= 1) { - this._inFlight--; - this._drainQueue(); - if (this._isResolved()) return true; - } - } else { - if (limit >= 1 && this._inFlight >= limit) { - values[index] = value; - this._queue.push(index); - return false; - } - if (preservedValues !== null) preservedValues[index] = value; - - var promise = this._promise; - var callback = this._callback; - var receiver = promise._boundValue(); - promise._pushContext(); - var ret = tryCatch(callback).call(receiver, value, index, length); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - preservedValues !== null ? "Promise.filter" : "Promise.map", - promise - ); - if (ret === errorObj) { - this._reject(ret.e); - return true; - } - - var maybePromise = tryConvertToPromise(ret, this._promise); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - if ((bitField & 50397184) === 0) { - if (limit >= 1) this._inFlight++; - values[index] = maybePromise; - maybePromise._proxy(this, (index + 1) * -1); - return false; - } else if ((bitField & 33554432) !== 0) { - ret = maybePromise._value(); - } else if ((bitField & 16777216) !== 0) { - this._reject(maybePromise._reason()); - return true; - } else { - this._cancel(); - return true; - } - } - values[index] = ret; - } - var totalResolved = ++this._totalResolved; - if (totalResolved >= length) { - if (preservedValues !== null) { - this._filter(values, preservedValues); - } else { - this._resolve(values); - } - return true; - } - return false; - }; +/*! + * ignore + */ - MappingPromiseArray.prototype._drainQueue = function () { - var queue = this._queue; - var limit = this._limit; - var values = this._values; - while (queue.length > 0 && this._inFlight < limit) { - if (this._isResolved()) return; - var index = queue.pop(); - this._promiseFulfilled(values[index], index); - } - }; +exports.cloneArrays = function cloneArrays(arr) { + if (!Array.isArray(arr)) { + return arr; + } - MappingPromiseArray.prototype._filter = function (booleans, values) { - var len = values.length; - var ret = new Array(len); - var j = 0; - for (var i = 0; i < len; ++i) { - if (booleans[i]) ret[j++] = values[i]; - } - ret.length = j; - this._resolve(ret); - }; + return arr.map(el => exports.cloneArrays(el)); +}; - MappingPromiseArray.prototype.preservedValues = function () { - return this._preservedValues; - }; +/*! + * ignore + */ - function map(promises, fn, options, _filter) { - if (typeof fn !== "function") { - return apiRejection( - "expecting a function but got " + util.classString(fn) - ); - } +exports.omit = function omit(obj, keys) { + if (keys == null) { + return Object.assign({}, obj); + } + if (!Array.isArray(keys)) { + keys = [keys]; + } - var limit = 0; - if (options !== undefined) { - if (typeof options === "object" && options !== null) { - if (typeof options.concurrency !== "number") { - return Promise.reject( - new TypeError( - "'concurrency' must be a number but it is " + - util.classString(options.concurrency) - ) - ); - } - limit = options.concurrency; - } else { - return Promise.reject( - new TypeError( - "options argument must be an object but it is " + - util.classString(options) - ) - ); - } - } - limit = - typeof limit === "number" && isFinite(limit) && limit >= 1 - ? limit - : 0; - return new MappingPromiseArray( - promises, - fn, - limit, - _filter - ).promise(); - } - - Promise.prototype.map = function (fn, options) { - return map(this, fn, options, null); - }; + const ret = Object.assign({}, obj); + for (const key of keys) { + delete ret[key]; + } + return ret; +}; - Promise.map = function (promises, fn, options, _filter) { - return map(promises, fn, options, _filter); - }; - }; - /***/ - }, +/*! + * Shallow copies defaults into options. + * + * @param {Object} defaults + * @param {Object} options + * @return {Object} the merged object + * @api private + */ + +exports.options = function(defaults, options) { + const keys = Object.keys(defaults); + let i = keys.length; + let k; + + options = options || {}; - /***/ 4802: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function ( - Promise, - INTERNAL, - tryConvertToPromise, - apiRejection, - debug - ) { - var util = __nccwpck_require__(2122); - var tryCatch = util.tryCatch; - - Promise.method = function (fn) { - if (typeof fn !== "function") { - throw new Promise.TypeError( - "expecting a function but got " + util.classString(fn) - ); - } - return function () { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value = tryCatch(fn).apply(this, arguments); - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, - promiseCreated, - "Promise.method", - ret - ); - ret._resolveFromSyncValue(value); - return ret; - }; - }; + while (i--) { + k = keys[i]; + if (!(k in options)) { + options[k] = defaults[k]; + } + } - Promise.attempt = Promise["try"] = function (fn) { - if (typeof fn !== "function") { - return apiRejection( - "expecting a function but got " + util.classString(fn) - ); - } - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value; - if (arguments.length > 1) { - debug.deprecated("calling Promise.try with more than 1 argument"); - var arg = arguments[1]; - var ctx = arguments[2]; - value = util.isArray(arg) - ? tryCatch(fn).apply(ctx, arg) - : tryCatch(fn).call(ctx, arg); - } else { - value = tryCatch(fn)(); - } - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, - promiseCreated, - "Promise.try", - ret - ); - ret._resolveFromSyncValue(value); - return ret; - }; + return options; +}; - Promise.prototype._resolveFromSyncValue = function (value) { - if (value === util.errorObj) { - this._rejectCallback(value.e, false); - } else { - this._resolveCallback(value, true); - } - }; - }; +/*! + * Generates a random string + * + * @api private + */ - /***/ - }, +exports.random = function() { + return Math.random().toString().substr(3); +}; - /***/ 11: /***/ (module, __unused_webpack_exports, __nccwpck_require__) => { - "use strict"; +/*! + * Merges `from` into `to` without overwriting existing properties. + * + * @param {Object} to + * @param {Object} from + * @api private + */ - var util = __nccwpck_require__(2122); - var maybeWrapAsError = util.maybeWrapAsError; - var errors = __nccwpck_require__(1522); - var OperationalError = errors.OperationalError; - var es5 = __nccwpck_require__(9432); +exports.merge = function merge(to, from, options, path) { + options = options || {}; - function isUntypedError(obj) { - return ( - obj instanceof Error && es5.getPrototypeOf(obj) === Error.prototype - ); - } + const keys = Object.keys(from); + let i = 0; + const len = keys.length; + let key; - var rErrorKey = /^(?:name|message|stack|cause)$/; - function wrapAsOperationalError(obj) { - var ret; - if (isUntypedError(obj)) { - ret = new OperationalError(obj); - ret.name = obj.name; - ret.message = obj.message; - ret.stack = obj.stack; - var keys = es5.keys(obj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (!rErrorKey.test(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - util.markAsOriginatingFromRejection(obj); - return obj; - } + if (from[trustedSymbol]) { + to[trustedSymbol] = from[trustedSymbol]; + } - function nodebackForPromise(promise, multiArgs) { - return function (err, value) { - if (promise === null) return; - if (err) { - var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } else if (!multiArgs) { - promise._fulfill(value); + path = path || ''; + const omitNested = options.omitNested || {}; + + while (i < len) { + key = keys[i++]; + if (options.omit && options.omit[key]) { + continue; + } + if (omitNested[path]) { + continue; + } + if (specialProperties.has(key)) { + continue; + } + if (to[key] == null) { + to[key] = from[key]; + } else if (exports.isObject(from[key])) { + if (!exports.isObject(to[key])) { + to[key] = {}; + } + if (from[key] != null) { + // Skip merging schemas if we're creating a discriminator schema and + // base schema has a given path as a single nested but discriminator schema + // has the path as a document array, or vice versa (gh-9534) + if (options.isDiscriminatorSchemaMerge && + (from[key].$isSingleNested && to[key].$isMongooseDocumentArray) || + (from[key].$isMongooseDocumentArray && to[key].$isSingleNested)) { + continue; + } else if (from[key].instanceOfSchema) { + if (to[key].instanceOfSchema) { + schemaMerge(to[key], from[key].clone(), options.isDiscriminatorSchemaMerge); } else { - var $_len = arguments.length; - var args = new Array(Math.max($_len - 1, 0)); - for (var $_i = 1; $_i < $_len; ++$_i) { - args[$_i - 1] = arguments[$_i]; - } - promise._fulfill(args); + to[key] = from[key].clone(); } - promise = null; - }; + continue; + } else if (from[key] instanceof ObjectId) { + to[key] = new ObjectId(from[key]); + continue; + } } + merge(to[key], from[key], options, path ? path + '.' + key : key); + } else if (options.overwrite) { + to[key] = from[key]; + } + } +}; - module.exports = nodebackForPromise; - - /***/ - }, +/*! + * Applies toObject recursively. + * + * @param {Document|Array|Object} obj + * @return {Object} + * @api private + */ - /***/ 8647: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function (Promise) { - var util = __nccwpck_require__(2122); - var async = Promise._async; - var tryCatch = util.tryCatch; - var errorObj = util.errorObj; - - function spreadAdapter(val, nodeback) { - var promise = this; - if (!util.isArray(val)) - return successAdapter.call(promise, val, nodeback); - var ret = tryCatch(nodeback).apply( - promise._boundValue(), - [null].concat(val) - ); - if (ret === errorObj) { - async.throwLater(ret.e); - } - } +exports.toObject = function toObject(obj) { + Document || (Document = __nccwpck_require__(6717)); + let ret; - function successAdapter(val, nodeback) { - var promise = this; - var receiver = promise._boundValue(); - var ret = - val === undefined - ? tryCatch(nodeback).call(receiver, null) - : tryCatch(nodeback).call(receiver, null, val); - if (ret === errorObj) { - async.throwLater(ret.e); - } - } - function errorAdapter(reason, nodeback) { - var promise = this; - if (!reason) { - var newReason = new Error(reason + ""); - newReason.cause = reason; - reason = newReason; - } - var ret = tryCatch(nodeback).call(promise._boundValue(), reason); - if (ret === errorObj) { - async.throwLater(ret.e); - } - } + if (obj == null) { + return obj; + } - Promise.prototype.asCallback = Promise.prototype.nodeify = function ( - nodeback, - options - ) { - if (typeof nodeback == "function") { - var adapter = successAdapter; - if (options !== undefined && Object(options).spread) { - adapter = spreadAdapter; - } - this._then(adapter, errorAdapter, undefined, this, nodeback); - } - return this; - }; - }; + if (obj instanceof Document) { + return obj.toObject(); + } - /***/ - }, + if (Array.isArray(obj)) { + ret = []; - /***/ 317: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function () { - var makeSelfResolutionError = function () { - return new TypeError( - "circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a" - ); - }; - var reflectHandler = function () { - return new Promise.PromiseInspection(this._target()); - }; - var apiRejection = function (msg) { - return Promise.reject(new TypeError(msg)); - }; - function Proxyable() {} - var UNDEFINED_BINDING = {}; - var util = __nccwpck_require__(2122); - - var getDomain; - if (util.isNode) { - getDomain = function () { - var ret = process.domain; - if (ret === undefined) ret = null; - return ret; - }; - } else { - getDomain = function () { - return null; - }; - } - util.notEnumerableProp(Promise, "_getDomain", getDomain); - - var es5 = __nccwpck_require__(9432); - var Async = __nccwpck_require__(5118); - var async = new Async(); - es5.defineProperty(Promise, "_async", { value: async }); - var errors = __nccwpck_require__(1522); - var TypeError = (Promise.TypeError = errors.TypeError); - Promise.RangeError = errors.RangeError; - var CancellationError = (Promise.CancellationError = - errors.CancellationError); - Promise.TimeoutError = errors.TimeoutError; - Promise.OperationalError = errors.OperationalError; - Promise.RejectionError = errors.OperationalError; - Promise.AggregateError = errors.AggregateError; - var INTERNAL = function () {}; - var APPLY = {}; - var NEXT_FILTER = {}; - var tryConvertToPromise = __nccwpck_require__(4997)(Promise, INTERNAL); - var PromiseArray = __nccwpck_require__(5168)( - Promise, - INTERNAL, - tryConvertToPromise, - apiRejection, - Proxyable - ); - var Context = __nccwpck_require__(647)(Promise); - /*jshint unused:false*/ - var createContext = Context.create; - var debug = __nccwpck_require__(1234)(Promise, Context); - var CapturedTrace = debug.CapturedTrace; - var PassThroughHandlerContext = __nccwpck_require__(3701)( - Promise, - tryConvertToPromise, - NEXT_FILTER - ); - var catchFilter = __nccwpck_require__(8447)(NEXT_FILTER); - var nodebackForPromise = __nccwpck_require__(11); - var errorObj = util.errorObj; - var tryCatch = util.tryCatch; - function check(self, executor) { - if (self == null || self.constructor !== Promise) { - throw new TypeError( - "the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a" - ); - } - if (typeof executor !== "function") { - throw new TypeError( - "expecting a function but got " + util.classString(executor) - ); - } - } + for (const doc of obj) { + ret.push(toObject(doc)); + } - function Promise(executor) { - if (executor !== INTERNAL) { - check(this, executor); - } - this._bitField = 0; - this._fulfillmentHandler0 = undefined; - this._rejectionHandler0 = undefined; - this._promise0 = undefined; - this._receiver0 = undefined; - this._resolveFromExecutor(executor); - this._promiseCreated(); - this._fireEvent("promiseCreated", this); - } - - Promise.prototype.toString = function () { - return "[object Promise]"; - }; + return ret; + } - Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { - var len = arguments.length; - if (len > 1) { - var catchInstances = new Array(len - 1), - j = 0, - i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return apiRejection( - "Catch statement predicate: " + - "expecting an object but got " + - util.classString(item) - ); - } - } - catchInstances.length = j; - fn = arguments[i]; - return this.then(undefined, catchFilter(catchInstances, fn, this)); - } - return this.then(undefined, fn); - }; + if (exports.isPOJO(obj)) { + ret = {}; - Promise.prototype.reflect = function () { - return this._then( - reflectHandler, - reflectHandler, - undefined, - this, - undefined - ); - }; + if (obj[trustedSymbol]) { + ret[trustedSymbol] = obj[trustedSymbol]; + } - Promise.prototype.then = function (didFulfill, didReject) { - if ( - debug.warnings() && - arguments.length > 0 && - typeof didFulfill !== "function" && - typeof didReject !== "function" - ) { - var msg = - ".then() only accepts functions but was passed: " + - util.classString(didFulfill); - if (arguments.length > 1) { - msg += ", " + util.classString(didReject); - } - this._warn(msg); - } - return this._then( - didFulfill, - didReject, - undefined, - undefined, - undefined - ); - }; + for (const k of Object.keys(obj)) { + if (specialProperties.has(k)) { + continue; + } + ret[k] = toObject(obj[k]); + } - Promise.prototype.done = function (didFulfill, didReject) { - var promise = this._then( - didFulfill, - didReject, - undefined, - undefined, - undefined - ); - promise._setIsFinal(); - }; + return ret; + } - Promise.prototype.spread = function (fn) { - if (typeof fn !== "function") { - return apiRejection( - "expecting a function but got " + util.classString(fn) - ); - } - return this.all()._then(fn, undefined, undefined, APPLY, undefined); - }; + return obj; +}; - Promise.prototype.toJSON = function () { - var ret = { - isFulfilled: false, - isRejected: false, - fulfillmentValue: undefined, - rejectionReason: undefined, - }; - if (this.isFulfilled()) { - ret.fulfillmentValue = this.value(); - ret.isFulfilled = true; - } else if (this.isRejected()) { - ret.rejectionReason = this.reason(); - ret.isRejected = true; - } - return ret; - }; +exports.isObject = isObject; - Promise.prototype.all = function () { - if (arguments.length > 0) { - this._warn(".all() was passed arguments but it does not take any"); - } - return new PromiseArray(this).promise(); - }; +/*! + * Determines if `arg` is a plain old JavaScript object (POJO). Specifically, + * `arg` must be an object but not an instance of any special class, like String, + * ObjectId, etc. + * + * `Object.getPrototypeOf()` is part of ES5: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf + * + * @param {Object|Array|String|Function|RegExp|any} arg + * @api private + * @return {Boolean} + */ - Promise.prototype.error = function (fn) { - return this.caught(util.originatesFromRejection, fn); - }; +exports.isPOJO = function isPOJO(arg) { + if (arg == null || typeof arg !== 'object') { + return false; + } + const proto = Object.getPrototypeOf(arg); + // Prototype may be null if you used `Object.create(null)` + // Checking `proto`'s constructor is safe because `getPrototypeOf()` + // explicitly crosses the boundary from object data to object metadata + return !proto || proto.constructor.name === 'Object'; +}; + +/*! + * Determines if `arg` is an object that isn't an instance of a built-in value + * class, like Array, Buffer, ObjectId, etc. + */ - Promise.getNewLibraryCopy = module.exports; +exports.isNonBuiltinObject = function isNonBuiltinObject(val) { + return typeof val === 'object' && + !exports.isNativeObject(val) && + !exports.isMongooseType(val) && + val != null; +}; - Promise.is = function (val) { - return val instanceof Promise; - }; +/*! + * Determines if `obj` is a built-in object like an array, date, boolean, + * etc. + */ - Promise.fromNode = Promise.fromCallback = function (fn) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var multiArgs = - arguments.length > 1 ? !!Object(arguments[1]).multiArgs : false; - var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); - if (result === errorObj) { - ret._rejectCallback(result.e, true); - } - if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); - return ret; - }; +exports.isNativeObject = function(arg) { + return Array.isArray(arg) || + arg instanceof Date || + arg instanceof Boolean || + arg instanceof Number || + arg instanceof String; +}; - Promise.all = function (promises) { - return new PromiseArray(promises).promise(); - }; +/*! + * Determines if `val` is an object that has no own keys + */ - Promise.cast = function (obj) { - var ret = tryConvertToPromise(obj); - if (!(ret instanceof Promise)) { - ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._setFulfilled(); - ret._rejectionHandler0 = obj; - } - return ret; - }; +exports.isEmptyObject = function(val) { + return val != null && + typeof val === 'object' && + Object.keys(val).length === 0; +}; - Promise.resolve = Promise.fulfilled = Promise.cast; +/*! + * Search if `obj` or any POJOs nested underneath `obj` has a property named + * `key` + */ - Promise.reject = Promise.rejected = function (reason) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._rejectCallback(reason, true); - return ret; - }; +exports.hasKey = function hasKey(obj, key) { + const props = Object.keys(obj); + for (const prop of props) { + if (prop === key) { + return true; + } + if (exports.isPOJO(obj[prop]) && exports.hasKey(obj[prop], key)) { + return true; + } + } + return false; +}; - Promise.setScheduler = function (fn) { - if (typeof fn !== "function") { - throw new TypeError( - "expecting a function but got " + util.classString(fn) - ); - } - return async.setScheduler(fn); - }; +/*! + * A faster Array.prototype.slice.call(arguments) alternative + * @api private + */ - Promise.prototype._then = function ( - didFulfill, - didReject, - _, - receiver, - internalData - ) { - var haveInternalData = internalData !== undefined; - var promise = haveInternalData ? internalData : new Promise(INTERNAL); - var target = this._target(); - var bitField = target._bitField; - - if (!haveInternalData) { - promise._propagateFrom(this, 3); - promise._captureStackTrace(); - if (receiver === undefined && (this._bitField & 2097152) !== 0) { - if (!((bitField & 50397184) === 0)) { - receiver = this._boundValue(); - } else { - receiver = target === this ? undefined : this._boundTo; - } - } - this._fireEvent("promiseChained", this, promise); - } +exports.args = sliced; - var domain = getDomain(); - if (!((bitField & 50397184) === 0)) { - var handler, - value, - settler = target._settlePromiseCtx; - if ((bitField & 33554432) !== 0) { - value = target._rejectionHandler0; - handler = didFulfill; - } else if ((bitField & 16777216) !== 0) { - value = target._fulfillmentHandler0; - handler = didReject; - target._unsetRejectionIsUnhandled(); - } else { - settler = target._settlePromiseLateCancellationObserver; - value = new CancellationError("late cancellation observer"); - target._attachExtraTrace(value); - handler = didReject; - } - - async.invoke(settler, target, { - handler: - domain === null - ? handler - : typeof handler === "function" && - util.domainBind(domain, handler), - promise: promise, - receiver: receiver, - value: value, - }); - } else { - target._addCallbacks( - didFulfill, - didReject, - promise, - receiver, - domain - ); - } +/*! + * process.nextTick helper. + * + * Wraps `callback` in a try/catch + nextTick. + * + * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback. + * + * @param {Function} callback + * @api private + */ - return promise; - }; +exports.tick = function tick(callback) { + if (typeof callback !== 'function') { + return; + } + return function() { + try { + callback.apply(this, arguments); + } catch (err) { + // only nextTick on err to get out of + // the event loop and avoid state corruption. + immediate(function() { + throw err; + }); + } + }; +}; - Promise.prototype._length = function () { - return this._bitField & 65535; - }; +/*! + * Returns true if `v` is an object that can be serialized as a primitive in + * MongoDB + */ - Promise.prototype._isFateSealed = function () { - return (this._bitField & 117506048) !== 0; - }; +exports.isMongooseType = function(v) { + return v instanceof ObjectId || v instanceof Decimal || v instanceof Buffer; +}; - Promise.prototype._isFollowing = function () { - return (this._bitField & 67108864) === 67108864; - }; +exports.isMongooseObject = isMongooseObject; - Promise.prototype._setLength = function (len) { - this._bitField = (this._bitField & -65536) | (len & 65535); - }; +/*! + * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB. + * + * @param {Object} object + * @api private + */ - Promise.prototype._setFulfilled = function () { - this._bitField = this._bitField | 33554432; - this._fireEvent("promiseFulfilled", this); - }; +exports.expires = function expires(object) { + if (!(object && object.constructor.name === 'Object')) { + return; + } + if (!('expires' in object)) { + return; + } - Promise.prototype._setRejected = function () { - this._bitField = this._bitField | 16777216; - this._fireEvent("promiseRejected", this); - }; + let when; + if (typeof object.expires !== 'string') { + when = object.expires; + } else { + when = Math.round(ms(object.expires) / 1000); + } + object.expireAfterSeconds = when; + delete object.expires; +}; - Promise.prototype._setFollowing = function () { - this._bitField = this._bitField | 67108864; - this._fireEvent("promiseResolved", this); - }; +/*! + * populate helper + */ - Promise.prototype._setIsFinal = function () { - this._bitField = this._bitField | 4194304; - }; +exports.populate = function populate(path, select, model, match, options, subPopulate, justOne, count) { + // might have passed an object specifying all arguments + let obj = null; + if (arguments.length === 1) { + if (path instanceof PopulateOptions) { + return [path]; + } - Promise.prototype._isFinal = function () { - return (this._bitField & 4194304) > 0; - }; + if (Array.isArray(path)) { + const singles = makeSingles(path); + return singles.map(o => exports.populate(o)[0]); + } - Promise.prototype._unsetCancelled = function () { - this._bitField = this._bitField & ~65536; - }; + if (exports.isObject(path)) { + obj = Object.assign({}, path); + } else { + obj = { path: path }; + } + } else if (typeof model === 'object') { + obj = { + path: path, + select: select, + match: model, + options: match + }; + } else { + obj = { + path: path, + select: select, + model: model, + match: match, + options: options, + populate: subPopulate, + justOne: justOne, + count: count + }; + } - Promise.prototype._setCancelled = function () { - this._bitField = this._bitField | 65536; - this._fireEvent("promiseCancelled", this); - }; + if (typeof obj.path !== 'string') { + throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`'); + } - Promise.prototype._setWillBeCancelled = function () { - this._bitField = this._bitField | 8388608; - }; + return _populateObj(obj); + + // The order of select/conditions args is opposite Model.find but + // necessary to keep backward compatibility (select could be + // an array, string, or object literal). + function makeSingles(arr) { + const ret = []; + arr.forEach(function(obj) { + if (/[\s]/.test(obj.path)) { + const paths = obj.path.split(' '); + paths.forEach(function(p) { + const copy = Object.assign({}, obj); + copy.path = p; + ret.push(copy); + }); + } else { + ret.push(obj); + } + }); - Promise.prototype._setAsyncGuaranteed = function () { - if (async.hasCustomScheduler()) return; - this._bitField = this._bitField | 134217728; - }; + return ret; + } +}; + +function _populateObj(obj) { + if (Array.isArray(obj.populate)) { + const ret = []; + obj.populate.forEach(function(obj) { + if (/[\s]/.test(obj.path)) { + const copy = Object.assign({}, obj); + const paths = copy.path.split(' '); + paths.forEach(function(p) { + copy.path = p; + ret.push(exports.populate(copy)[0]); + }); + } else { + ret.push(exports.populate(obj)[0]); + } + }); + obj.populate = exports.populate(ret); + } else if (obj.populate != null && typeof obj.populate === 'object') { + obj.populate = exports.populate(obj.populate); + } - Promise.prototype._receiverAt = function (index) { - var ret = index === 0 ? this._receiver0 : this[index * 4 - 4 + 3]; - if (ret === UNDEFINED_BINDING) { - return undefined; - } else if (ret === undefined && this._isBound()) { - return this._boundValue(); - } - return ret; - }; + const ret = []; + const paths = obj.path.split(' '); + if (obj.options != null) { + obj.options = exports.clone(obj.options); + } - Promise.prototype._promiseAt = function (index) { - return this[index * 4 - 4 + 2]; - }; + for (const path of paths) { + ret.push(new PopulateOptions(Object.assign({}, obj, { path: path }))); + } - Promise.prototype._fulfillmentHandlerAt = function (index) { - return this[index * 4 - 4 + 0]; - }; + return ret; +} - Promise.prototype._rejectionHandlerAt = function (index) { - return this[index * 4 - 4 + 1]; - }; +/*! + * Return the value of `obj` at the given `path`. + * + * @param {String} path + * @param {Object} obj + */ - Promise.prototype._boundValue = function () {}; +exports.getValue = function(path, obj, map) { + return mpath.get(path, obj, '_doc', map); +}; - Promise.prototype._migrateCallback0 = function (follower) { - var bitField = follower._bitField; - var fulfill = follower._fulfillmentHandler0; - var reject = follower._rejectionHandler0; - var promise = follower._promise0; - var receiver = follower._receiverAt(0); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); - }; +/*! + * Sets the value of `obj` at the given `path`. + * + * @param {String} path + * @param {Anything} val + * @param {Object} obj + */ - Promise.prototype._migrateCallbackAt = function (follower, index) { - var fulfill = follower._fulfillmentHandlerAt(index); - var reject = follower._rejectionHandlerAt(index); - var promise = follower._promiseAt(index); - var receiver = follower._receiverAt(index); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); - }; +exports.setValue = function(path, val, obj, map, _copying) { + mpath.set(path, val, obj, '_doc', map, _copying); +}; - Promise.prototype._addCallbacks = function ( - fulfill, - reject, - promise, - receiver, - domain - ) { - var index = this._length(); +/*! + * Returns an array of values from object `o`. + * + * @param {Object} o + * @return {Array} + * @private + */ - if (index >= 65535 - 4) { - index = 0; - this._setLength(0); - } +exports.object = {}; +exports.object.vals = function vals(o) { + const keys = Object.keys(o); + let i = keys.length; + const ret = []; - if (index === 0) { - this._promise0 = promise; - this._receiver0 = receiver; - if (typeof fulfill === "function") { - this._fulfillmentHandler0 = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this._rejectionHandler0 = - domain === null ? reject : util.domainBind(domain, reject); - } - } else { - var base = index * 4 - 4; - this[base + 2] = promise; - this[base + 3] = receiver; - if (typeof fulfill === "function") { - this[base + 0] = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this[base + 1] = - domain === null ? reject : util.domainBind(domain, reject); - } - } - this._setLength(index + 1); - return index; - }; + while (i--) { + ret.push(o[keys[i]]); + } - Promise.prototype._proxy = function (proxyable, arg) { - this._addCallbacks(undefined, undefined, arg, proxyable, null); - }; + return ret; +}; - Promise.prototype._resolveCallback = function (value, shouldBind) { - if ((this._bitField & 117506048) !== 0) return; - if (value === this) - return this._rejectCallback(makeSelfResolutionError(), false); - var maybePromise = tryConvertToPromise(value, this); - if (!(maybePromise instanceof Promise)) return this._fulfill(value); +/*! + * @see exports.options + */ - if (shouldBind) this._propagateFrom(maybePromise, 2); +exports.object.shallowCopy = exports.options; - var promise = maybePromise._target(); +/*! + * Safer helper for hasOwnProperty checks + * + * @param {Object} obj + * @param {String} prop + */ - if (promise === this) { - this._reject(makeSelfResolutionError()); - return; - } +const hop = Object.prototype.hasOwnProperty; +exports.object.hasOwnProperty = function(obj, prop) { + return hop.call(obj, prop); +}; - var bitField = promise._bitField; - if ((bitField & 50397184) === 0) { - var len = this._length(); - if (len > 0) promise._migrateCallback0(this); - for (var i = 1; i < len; ++i) { - promise._migrateCallbackAt(this, i); - } - this._setFollowing(); - this._setLength(0); - this._setFollowee(promise); - } else if ((bitField & 33554432) !== 0) { - this._fulfill(promise._value()); - } else if ((bitField & 16777216) !== 0) { - this._reject(promise._reason()); - } else { - var reason = new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - this._reject(reason); - } - }; +/*! + * Determine if `val` is null or undefined + * + * @return {Boolean} + */ - Promise.prototype._rejectCallback = function ( - reason, - synchronous, - ignoreNonErrorWarnings - ) { - var trace = util.ensureErrorObject(reason); - var hasStack = trace === reason; - if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { - var message = - "a promise was rejected with a non-error: " + - util.classString(reason); - this._warn(message, true); - } - this._attachExtraTrace(trace, synchronous ? hasStack : false); - this._reject(reason); - }; +exports.isNullOrUndefined = function(val) { + return val === null || val === undefined; +}; - Promise.prototype._resolveFromExecutor = function (executor) { - if (executor === INTERNAL) return; - var promise = this; - this._captureStackTrace(); - this._pushContext(); - var synchronous = true; - var r = this._execute( - executor, - function (value) { - promise._resolveCallback(value); - }, - function (reason) { - promise._rejectCallback(reason, synchronous); - } - ); - synchronous = false; - this._popContext(); +/*! + * ignore + */ - if (r !== undefined) { - promise._rejectCallback(r, true); - } - }; +exports.array = {}; - Promise.prototype._settlePromiseFromHandler = function ( - handler, - receiver, - value, - promise - ) { - var bitField = promise._bitField; - if ((bitField & 65536) !== 0) return; - promise._pushContext(); - var x; - if (receiver === APPLY) { - if (!value || typeof value.length !== "number") { - x = errorObj; - x.e = new TypeError( - "cannot .spread() a non-array: " + util.classString(value) - ); - } else { - x = tryCatch(handler).apply(this._boundValue(), value); - } - } else { - x = tryCatch(handler).call(receiver, value); - } - var promiseCreated = promise._popContext(); - bitField = promise._bitField; - if ((bitField & 65536) !== 0) return; - - if (x === NEXT_FILTER) { - promise._reject(value); - } else if (x === errorObj) { - promise._rejectCallback(x.e, false); - } else { - debug.checkForgottenReturns(x, promiseCreated, "", promise, this); - promise._resolveCallback(x); - } - }; +/*! + * Flattens an array. + * + * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4] + * + * @param {Array} arr + * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsy value, the item will not be included in the results. + * @return {Array} + * @private + */ - Promise.prototype._target = function () { - var ret = this; - while (ret._isFollowing()) ret = ret._followee(); - return ret; - }; +exports.array.flatten = function flatten(arr, filter, ret) { + ret || (ret = []); - Promise.prototype._followee = function () { - return this._rejectionHandler0; - }; + arr.forEach(function(item) { + if (Array.isArray(item)) { + flatten(item, filter, ret); + } else { + if (!filter || filter(item)) { + ret.push(item); + } + } + }); - Promise.prototype._setFollowee = function (promise) { - this._rejectionHandler0 = promise; - }; + return ret; +}; - Promise.prototype._settlePromise = function ( - promise, - handler, - receiver, - value - ) { - var isPromise = promise instanceof Promise; - var bitField = this._bitField; - var asyncGuaranteed = (bitField & 134217728) !== 0; - if ((bitField & 65536) !== 0) { - if (isPromise) promise._invokeInternalOnCancel(); - - if ( - receiver instanceof PassThroughHandlerContext && - receiver.isFinallyHandler() - ) { - receiver.cancelPromise = promise; - if (tryCatch(handler).call(receiver, value) === errorObj) { - promise._reject(errorObj.e); - } - } else if (handler === reflectHandler) { - promise._fulfill(reflectHandler.call(receiver)); - } else if (receiver instanceof Proxyable) { - receiver._promiseCancelled(promise); - } else if (isPromise || promise instanceof PromiseArray) { - promise._cancel(); - } else { - receiver.cancel(); - } - } else if (typeof handler === "function") { - if (!isPromise) { - handler.call(receiver, value, promise); - } else { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (receiver instanceof Proxyable) { - if (!receiver._isResolved()) { - if ((bitField & 33554432) !== 0) { - receiver._promiseFulfilled(value, promise); - } else { - receiver._promiseRejected(value, promise); - } - } - } else if (isPromise) { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - if ((bitField & 33554432) !== 0) { - promise._fulfill(value); - } else { - promise._reject(value); - } - } - }; +/*! + * ignore + */ - Promise.prototype._settlePromiseLateCancellationObserver = function ( - ctx - ) { - var handler = ctx.handler; - var promise = ctx.promise; - var receiver = ctx.receiver; - var value = ctx.value; - if (typeof handler === "function") { - if (!(promise instanceof Promise)) { - handler.call(receiver, value, promise); - } else { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (promise instanceof Promise) { - promise._reject(value); - } - }; +const _hasOwnProperty = Object.prototype.hasOwnProperty; - Promise.prototype._settlePromiseCtx = function (ctx) { - this._settlePromise( - ctx.promise, - ctx.handler, - ctx.receiver, - ctx.value - ); - }; +exports.hasUserDefinedProperty = function(obj, key) { + if (obj == null) { + return false; + } - Promise.prototype._settlePromise0 = function ( - handler, - value, - bitField - ) { - var promise = this._promise0; - var receiver = this._receiverAt(0); - this._promise0 = undefined; - this._receiver0 = undefined; - this._settlePromise(promise, handler, receiver, value); - }; + if (Array.isArray(key)) { + for (const k of key) { + if (exports.hasUserDefinedProperty(obj, k)) { + return true; + } + } + return false; + } - Promise.prototype._clearCallbackDataAtIndex = function (index) { - var base = index * 4 - 4; - this[base + 2] = - this[base + 3] = - this[base + 0] = - this[base + 1] = - undefined; - }; + if (_hasOwnProperty.call(obj, key)) { + return true; + } + if (typeof obj === 'object' && key in obj) { + const v = obj[key]; + return v !== Object.prototype[key] && v !== Array.prototype[key]; + } - Promise.prototype._fulfill = function (value) { - var bitField = this._bitField; - if ((bitField & 117506048) >>> 16) return; - if (value === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._reject(err); - } - this._setFulfilled(); - this._rejectionHandler0 = value; + return false; +}; - if ((bitField & 65535) > 0) { - if ((bitField & 134217728) !== 0) { - this._settlePromises(); - } else { - async.settlePromises(this); - } - } - }; +/*! + * ignore + */ - Promise.prototype._reject = function (reason) { - var bitField = this._bitField; - if ((bitField & 117506048) >>> 16) return; - this._setRejected(); - this._fulfillmentHandler0 = reason; +const MAX_ARRAY_INDEX = Math.pow(2, 32) - 1; - if (this._isFinal()) { - return async.fatalError(reason, util.isNode); - } +exports.isArrayIndex = function(val) { + if (typeof val === 'number') { + return val >= 0 && val <= MAX_ARRAY_INDEX; + } + if (typeof val === 'string') { + if (!/^\d+$/.test(val)) { + return false; + } + val = +val; + return val >= 0 && val <= MAX_ARRAY_INDEX; + } - if ((bitField & 65535) > 0) { - async.settlePromises(this); - } else { - this._ensurePossibleRejectionHandled(); - } - }; + return false; +}; - Promise.prototype._fulfillPromises = function (len, value) { - for (var i = 1; i < len; i++) { - var handler = this._fulfillmentHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, value); - } - }; +/*! + * Removes duplicate values from an array + * + * [1, 2, 3, 3, 5] => [1, 2, 3, 5] + * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ] + * => [ObjectId("550988ba0c19d57f697dc45e")] + * + * @param {Array} arr + * @return {Array} + * @private + */ - Promise.prototype._rejectPromises = function (len, reason) { - for (var i = 1; i < len; i++) { - var handler = this._rejectionHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, reason); - } - }; +exports.array.unique = function(arr) { + const primitives = new Set(); + const ids = new Set(); + const ret = []; + + for (const item of arr) { + if (typeof item === 'number' || typeof item === 'string' || item == null) { + if (primitives.has(item)) { + continue; + } + ret.push(item); + primitives.add(item); + } else if (item instanceof ObjectId) { + if (ids.has(item.toString())) { + continue; + } + ret.push(item); + ids.add(item.toString()); + } else { + ret.push(item); + } + } - Promise.prototype._settlePromises = function () { - var bitField = this._bitField; - var len = bitField & 65535; + return ret; +}; - if (len > 0) { - if ((bitField & 16842752) !== 0) { - var reason = this._fulfillmentHandler0; - this._settlePromise0(this._rejectionHandler0, reason, bitField); - this._rejectPromises(len, reason); - } else { - var value = this._rejectionHandler0; - this._settlePromise0(this._fulfillmentHandler0, value, bitField); - this._fulfillPromises(len, value); - } - this._setLength(0); - } - this._clearCancellationData(); - }; +/*! + * Determines if two buffers are equal. + * + * @param {Buffer} a + * @param {Object} b + */ - Promise.prototype._settledValue = function () { - var bitField = this._bitField; - if ((bitField & 33554432) !== 0) { - return this._rejectionHandler0; - } else if ((bitField & 16777216) !== 0) { - return this._fulfillmentHandler0; - } - }; +exports.buffer = {}; +exports.buffer.areEqual = function(a, b) { + if (!Buffer.isBuffer(a)) { + return false; + } + if (!Buffer.isBuffer(b)) { + return false; + } + if (a.length !== b.length) { + return false; + } + for (let i = 0, len = a.length; i < len; ++i) { + if (a[i] !== b[i]) { + return false; + } + } + return true; +}; + +exports.getFunctionName = getFunctionName; +/*! + * Decorate buffers + */ + +exports.decorate = function(destination, source) { + for (const key in source) { + if (specialProperties.has(key)) { + continue; + } + destination[key] = source[key]; + } +}; + +/** + * merges to with a copy of from + * + * @param {Object} to + * @param {Object} fromObj + * @api private + */ - function deferResolve(v) { - this.promise._resolveCallback(v); +exports.mergeClone = function(to, fromObj) { + if (isMongooseObject(fromObj)) { + fromObj = fromObj.toObject({ + transform: false, + virtuals: false, + depopulate: true, + getters: false, + flattenDecimals: false + }); + } + const keys = Object.keys(fromObj); + const len = keys.length; + let i = 0; + let key; + + while (i < len) { + key = keys[i++]; + if (specialProperties.has(key)) { + continue; + } + if (typeof to[key] === 'undefined') { + to[key] = exports.clone(fromObj[key], { + transform: false, + virtuals: false, + depopulate: true, + getters: false, + flattenDecimals: false + }); + } else { + let val = fromObj[key]; + if (val != null && val.valueOf && !(val instanceof Date)) { + val = val.valueOf(); + } + if (exports.isObject(val)) { + let obj = val; + if (isMongooseObject(val) && !val.isMongooseBuffer) { + obj = obj.toObject({ + transform: false, + virtuals: false, + depopulate: true, + getters: false, + flattenDecimals: false + }); } - function deferReject(v) { - this.promise._rejectCallback(v, false); + if (val.isMongooseBuffer) { + obj = Buffer.from(obj); } + exports.mergeClone(to[key], obj); + } else { + to[key] = exports.clone(val, { + flattenDecimals: false + }); + } + } + } +}; - Promise.defer = Promise.pending = function () { - debug.deprecated("Promise.defer", "new Promise"); - var promise = new Promise(INTERNAL); - return { - promise: promise, - resolve: deferResolve, - reject: deferReject, - }; - }; - - util.notEnumerableProp( - Promise, - "_makeSelfResolutionError", - makeSelfResolutionError - ); +/** + * Executes a function on each element of an array (like _.each) + * + * @param {Array} arr + * @param {Function} fn + * @api private + */ - __nccwpck_require__(4802)( - Promise, - INTERNAL, - tryConvertToPromise, - apiRejection, - debug - ); - __nccwpck_require__(764)(Promise, INTERNAL, tryConvertToPromise, debug); - __nccwpck_require__(3789)(Promise, PromiseArray, apiRejection, debug); - __nccwpck_require__(9923)(Promise); - __nccwpck_require__(4084)(Promise); - __nccwpck_require__(689)( - Promise, - PromiseArray, - tryConvertToPromise, - INTERNAL, - async, - getDomain - ); - Promise.Promise = Promise; - Promise.version = "3.5.1"; - __nccwpck_require__(377)( - Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug - ); - __nccwpck_require__(2414)(Promise); - __nccwpck_require__(9626)( - Promise, - apiRejection, - tryConvertToPromise, - createContext, - INTERNAL, - debug - ); - __nccwpck_require__(3482)(Promise, INTERNAL, debug); - __nccwpck_require__(8498)( - Promise, - apiRejection, - INTERNAL, - tryConvertToPromise, - Proxyable, - debug - ); - __nccwpck_require__(8647)(Promise); - __nccwpck_require__(2625)(Promise, INTERNAL); - __nccwpck_require__(8717)( - Promise, - PromiseArray, - tryConvertToPromise, - apiRejection - ); - __nccwpck_require__(4668)( - Promise, - INTERNAL, - tryConvertToPromise, - apiRejection - ); - __nccwpck_require__(986)( - Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug - ); - __nccwpck_require__(1506)(Promise, PromiseArray, debug); - __nccwpck_require__(2807)(Promise, PromiseArray, apiRejection); - __nccwpck_require__(9180)(Promise, INTERNAL); - __nccwpck_require__(301)(Promise, INTERNAL); - __nccwpck_require__(8819)(Promise); - - util.toFastProperties(Promise); - util.toFastProperties(Promise.prototype); - function fillTypes(value) { - var p = new Promise(INTERNAL); - p._fulfillmentHandler0 = value; - p._rejectionHandler0 = value; - p._promise0 = value; - p._receiver0 = value; - } - // Complete slack tracking, opt out of field-type tracking and - // stabilize map - fillTypes({ a: 1 }); - fillTypes({ b: 2 }); - fillTypes({ c: 3 }); - fillTypes(1); - fillTypes(function () {}); - fillTypes(undefined); - fillTypes(false); - fillTypes(new Promise(INTERNAL)); - debug.setBounds(Async.firstLineError, util.lastLineError); - return Promise; - }; +exports.each = function(arr, fn) { + for (const item of arr) { + fn(item); + } +}; - /***/ - }, +/*! + * ignore + */ - /***/ 5168: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function ( - Promise, - INTERNAL, - tryConvertToPromise, - apiRejection, - Proxyable - ) { - var util = __nccwpck_require__(2122); - var isArray = util.isArray; - - function toResolutionValue(val) { - switch (val) { - case -2: - return []; - case -3: - return {}; - case -6: - return new Map(); - } - } +exports.getOption = function(name) { + const sources = Array.prototype.slice.call(arguments, 1); - function PromiseArray(values) { - var promise = (this._promise = new Promise(INTERNAL)); - if (values instanceof Promise) { - promise._propagateFrom(values, 3); - } - promise._setOnCancel(this); - this._values = values; - this._length = 0; - this._totalResolved = 0; - this._init(undefined, -2); - } - util.inherits(PromiseArray, Proxyable); + for (const source of sources) { + if (source[name] != null) { + return source[name]; + } + } - PromiseArray.prototype.length = function () { - return this._length; - }; + return null; +}; - PromiseArray.prototype.promise = function () { - return this._promise; - }; +/*! + * ignore + */ - PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { - var values = tryConvertToPromise(this._values, this._promise); - if (values instanceof Promise) { - values = values._target(); - var bitField = values._bitField; - this._values = values; - - if ((bitField & 50397184) === 0) { - this._promise._setAsyncGuaranteed(); - return values._then( - init, - this._reject, - undefined, - this, - resolveValueIfEmpty - ); - } else if ((bitField & 33554432) !== 0) { - values = values._value(); - } else if ((bitField & 16777216) !== 0) { - return this._reject(values._reason()); - } else { - return this._cancel(); - } - } - values = util.asArray(values); - if (values === null) { - var err = apiRejection( - "expecting an array or an iterable object but got " + - util.classString(values) - ).reason(); - this._promise._rejectCallback(err, false); - return; - } +exports.noop = function() {}; - if (values.length === 0) { - if (resolveValueIfEmpty === -5) { - this._resolveEmptyArray(); - } else { - this._resolve(toResolutionValue(resolveValueIfEmpty)); - } - return; - } - this._iterate(values); - }; +exports.errorToPOJO = function errorToPOJO(error) { + const isError = error instanceof Error; + if (!isError) { + throw new Error('`error` must be `instanceof Error`.'); + } - PromiseArray.prototype._iterate = function (values) { - var len = this.getActualLength(values.length); - this._length = len; - this._values = this.shouldCopyValues() - ? new Array(len) - : this._values; - var result = this._promise; - var isResolved = false; - var bitField = null; - for (var i = 0; i < len; ++i) { - var maybePromise = tryConvertToPromise(values[i], result); - - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - bitField = maybePromise._bitField; - } else { - bitField = null; - } + const ret = {}; + for (const properyName of Object.getOwnPropertyNames(error)) { + ret[properyName] = error[properyName]; + } + return ret; +}; - if (isResolved) { - if (bitField !== null) { - maybePromise.suppressUnhandledRejections(); - } - } else if (bitField !== null) { - if ((bitField & 50397184) === 0) { - maybePromise._proxy(this, i); - this._values[i] = maybePromise; - } else if ((bitField & 33554432) !== 0) { - isResolved = this._promiseFulfilled(maybePromise._value(), i); - } else if ((bitField & 16777216) !== 0) { - isResolved = this._promiseRejected(maybePromise._reason(), i); - } else { - isResolved = this._promiseCancelled(i); - } - } else { - isResolved = this._promiseFulfilled(maybePromise, i); - } - } - if (!isResolved) result._setAsyncGuaranteed(); - }; +/*! + * ignore + */ - PromiseArray.prototype._isResolved = function () { - return this._values === null; - }; +exports.warn = function warn(message) { + return process.emitWarning(message, { code: 'MONGOOSE' }); +}; - PromiseArray.prototype._resolve = function (value) { - this._values = null; - this._promise._fulfill(value); - }; - PromiseArray.prototype._cancel = function () { - if (this._isResolved() || !this._promise._isCancellable()) return; - this._values = null; - this._promise._cancel(); - }; +/***/ }), - PromiseArray.prototype._reject = function (reason) { - this._values = null; - this._promise._rejectCallback(reason, false); - }; +/***/ 481: +/***/ ((module) => { - PromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; - }; +"use strict"; - PromiseArray.prototype._promiseCancelled = function () { - this._cancel(); - return true; - }; +/*! + * Valid mongoose options + */ - PromiseArray.prototype._promiseRejected = function (reason) { - this._totalResolved++; - this._reject(reason); - return true; - }; - PromiseArray.prototype._resultCancelled = function () { - if (this._isResolved()) return; - var values = this._values; - this._cancel(); - if (values instanceof Promise) { - values.cancel(); - } else { - for (var i = 0; i < values.length; ++i) { - if (values[i] instanceof Promise) { - values[i].cancel(); - } - } - } - }; - PromiseArray.prototype.shouldCopyValues = function () { - return true; - }; +const VALID_OPTIONS = Object.freeze([ + 'applyPluginsToChildSchemas', + 'applyPluginsToDiscriminators', + 'autoCreate', + 'autoIndex', + 'bufferCommands', + 'bufferTimeoutMS', + 'cloneSchemas', + 'debug', + 'maxTimeMS', + 'objectIdGetter', + 'overwriteModels', + 'returnOriginal', + 'runValidators', + 'sanitizeFilter', + 'sanitizeProjection', + 'selectPopulatedPaths', + 'setDefaultsOnInsert', + 'strict', + 'strictPopulate', + 'strictQuery', + 'toJSON', + 'toObject' +]); - PromiseArray.prototype.getActualLength = function (len) { - return len; - }; +module.exports = VALID_OPTIONS; - return PromiseArray; - }; - /***/ - }, +/***/ }), - /***/ 2625: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function (Promise, INTERNAL) { - var THIS = {}; - var util = __nccwpck_require__(2122); - var nodebackForPromise = __nccwpck_require__(11); - var withAppended = util.withAppended; - var maybeWrapAsError = util.maybeWrapAsError; - var canEvaluate = util.canEvaluate; - var TypeError = __nccwpck_require__(1522).TypeError; - var defaultSuffix = "Async"; - var defaultPromisified = { __isPromisified__: true }; - var noCopyProps = [ - "arity", - "length", - "name", - "arguments", - "caller", - "callee", - "prototype", - "__isPromisified__", - ]; - var noCopyPropsPattern = new RegExp( - "^(?:" + noCopyProps.join("|") + ")$" - ); +/***/ 1423: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var defaultFilter = function (name) { - return ( - util.isIdentifier(name) && - name.charAt(0) !== "_" && - name !== "constructor" - ); - }; +"use strict"; - function propsFilter(key) { - return !noCopyPropsPattern.test(key); - } - function isPromisified(fn) { - try { - return fn.__isPromisified__ === true; - } catch (e) { - return false; - } - } +const utils = __nccwpck_require__(9232); - function hasPromisified(obj, key, suffix) { - var val = util.getDataPropertyOrDefault( - obj, - key + suffix, - defaultPromisified - ); - return val ? isPromisified(val) : false; - } - function checkValid(ret, suffix, suffixRegexp) { - for (var i = 0; i < ret.length; i += 2) { - var key = ret[i]; - if (suffixRegexp.test(key)) { - var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); - for (var j = 0; j < ret.length; j += 2) { - if (ret[j] === keyWithoutAsyncSuffix) { - throw new TypeError( - "Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a".replace( - "%s", - suffix - ) - ); - } - } - } - } - } +/** + * VirtualType constructor + * + * This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`. + * + * ####Example: + * + * const fullname = schema.virtual('fullname'); + * fullname instanceof mongoose.VirtualType // true + * + * @param {Object} options + * @param {string|function} [options.ref] if `ref` is not nullish, this becomes a [populated virtual](/docs/populate.html#populate-virtuals) + * @param {string|function} [options.localField] the local field to populate on if this is a populated virtual. + * @param {string|function} [options.foreignField] the foreign field to populate on if this is a populated virtual. + * @param {boolean} [options.justOne=false] by default, a populated virtual is an array. If you set `justOne`, the populated virtual will be a single doc or `null`. + * @param {boolean} [options.getters=false] if you set this to `true`, Mongoose will call any custom getters you defined on this virtual + * @param {boolean} [options.count=false] if you set this to `true`, `populate()` will set this virtual to the number of populated documents, as opposed to the documents themselves, using [`Query#countDocuments()`](./api.html#query_Query-countDocuments) + * @param {Object|Function} [options.match=null] add an extra match condition to `populate()` + * @param {Number} [options.limit=null] add a default `limit` to the `populate()` query + * @param {Number} [options.skip=null] add a default `skip` to the `populate()` query + * @param {Number} [options.perDocumentLimit=null] For legacy reasons, `limit` with `populate()` may give incorrect results because it only executes a single query for every document being populated. If you set `perDocumentLimit`, Mongoose will ensure correct `limit` per document by executing a separate query for each document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })` will execute 2 additional queries if `.find()` returns 2 documents. + * @param {Object} [options.options=null] Additional options like `limit` and `lean`. + * @api public + */ - function promisifiableMethods(obj, suffix, suffixRegexp, filter) { - var keys = util.inheritedDataKeys(obj); - var ret = []; - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var value = obj[key]; - var passesDefaultFilter = - filter === defaultFilter ? true : defaultFilter(key, value, obj); - if ( - typeof value === "function" && - !isPromisified(value) && - !hasPromisified(obj, key, suffix) && - filter(key, value, obj, passesDefaultFilter) - ) { - ret.push(key, value); - } - } - checkValid(ret, suffix, suffixRegexp); - return ret; - } +function VirtualType(options, name) { + this.path = name; + this.getters = []; + this.setters = []; + this.options = Object.assign({}, options); +} - var escapeIdentRegex = function (str) { - return str.replace(/([$])/, "\\$"); - }; +/** + * If no getters/getters, add a default + * + * @param {Function} fn + * @return {VirtualType} this + * @api private + */ - var makeNodePromisifiedEval; - if (true) { - var switchCaseArgumentOrder = function (likelyArgumentCount) { - var ret = [likelyArgumentCount]; - var min = Math.max(0, likelyArgumentCount - 1 - 3); - for (var i = likelyArgumentCount - 1; i >= min; --i) { - ret.push(i); - } - for (var i = likelyArgumentCount + 1; i <= 3; ++i) { - ret.push(i); - } - return ret; - }; +VirtualType.prototype._applyDefaultGetters = function() { + if (this.getters.length > 0 || this.setters.length > 0) { + return; + } - var argumentSequence = function (argumentCount) { - return util.filledRange(argumentCount, "_arg", ""); - }; + const path = this.path; + const internalProperty = '$' + path; + this.getters.push(function() { + return this[internalProperty]; + }); + this.setters.push(function(v) { + this[internalProperty] = v; + }); +}; + +/*! + * ignore + */ - var parameterDeclaration = function (parameterCount) { - return util.filledRange(Math.max(parameterCount, 3), "_arg", ""); - }; +VirtualType.prototype.clone = function() { + const clone = new VirtualType(this.options, this.path); + clone.getters = [].concat(this.getters); + clone.setters = [].concat(this.setters); + return clone; +}; - var parameterCount = function (fn) { - if (typeof fn.length === "number") { - return Math.max(Math.min(fn.length, 1023 + 1), 0); - } - return 0; - }; +/** + * Adds a custom getter to this virtual. + * + * Mongoose calls the getter function with the below 3 parameters. + * + * - `value`: the value returned by the previous getter. If there is only one getter, `value` will be `undefined`. + * - `virtual`: the virtual object you called `.get()` on + * - `doc`: the document this virtual is attached to. Equivalent to `this`. + * + * ####Example: + * + * const virtual = schema.virtual('fullname'); + * virtual.get(function(value, virtual, doc) { + * return this.name.first + ' ' + this.name.last; + * }); + * + * @param {Function(Any, VirtualType, Document)} fn + * @return {VirtualType} this + * @api public + */ - makeNodePromisifiedEval = function ( - callback, - receiver, - originalName, - fn, - _, - multiArgs - ) { - var newParameterCount = Math.max(0, parameterCount(fn) - 1); - var argumentOrder = switchCaseArgumentOrder(newParameterCount); - var shouldProxyThis = - typeof callback === "string" || receiver === THIS; - - function generateCallForArgumentCount(count) { - var args = argumentSequence(count).join(", "); - var comma = count > 0 ? ", " : ""; - var ret; - if (shouldProxyThis) { - ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; - } else { - ret = - receiver === undefined - ? "ret = callback({{args}}, nodeback); break;\n" - : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; - } - return ret.replace("{{args}}", args).replace(", ", comma); - } +VirtualType.prototype.get = function(fn) { + this.getters.push(fn); + return this; +}; - function generateArgumentSwitchCase() { - var ret = ""; - for (var i = 0; i < argumentOrder.length; ++i) { - ret += - "case " + - argumentOrder[i] + - ":" + - generateCallForArgumentCount(argumentOrder[i]); - } +/** + * Adds a custom setter to this virtual. + * + * Mongoose calls the setter function with the below 3 parameters. + * + * - `value`: the value being set + * - `virtual`: the virtual object you're calling `.set()` on + * - `doc`: the document this virtual is attached to. Equivalent to `this`. + * + * ####Example: + * + * const virtual = schema.virtual('fullname'); + * virtual.set(function(value, virtual, doc) { + * const parts = value.split(' '); + * this.name.first = parts[0]; + * this.name.last = parts[1]; + * }); + * + * const Model = mongoose.model('Test', schema); + * const doc = new Model(); + * // Calls the setter with `value = 'Jean-Luc Picard'` + * doc.fullname = 'Jean-Luc Picard'; + * doc.name.first; // 'Jean-Luc' + * doc.name.last; // 'Picard' + * + * @param {Function(Any, VirtualType, Document)} fn + * @return {VirtualType} this + * @api public + */ - ret += - " \n\ - default: \n\ - var args = new Array(len + 1); \n\ - var i = 0; \n\ - for (var i = 0; i < len; ++i) { \n\ - args[i] = arguments[i]; \n\ - } \n\ - args[i] = nodeback; \n\ - [CodeForCall] \n\ - break; \n\ - ".replace( - "[CodeForCall]", - shouldProxyThis - ? "ret = callback.apply(this, args);\n" - : "ret = callback.apply(receiver, args);\n" - ); - return ret; - } +VirtualType.prototype.set = function(fn) { + this.setters.push(fn); + return this; +}; - var getFunctionCode = - typeof callback === "string" - ? "this != null ? this['" + callback + "'] : fn" - : "fn"; - var body = - "'use strict'; \n\ - var ret = function (Parameters) { \n\ - 'use strict'; \n\ - var len = arguments.length; \n\ - var promise = new Promise(INTERNAL); \n\ - promise._captureStackTrace(); \n\ - var nodeback = nodebackForPromise(promise, " + - multiArgs + - "); \n\ - var ret; \n\ - var callback = tryCatch([GetFunctionCode]); \n\ - switch(len) { \n\ - [CodeForSwitchCase] \n\ - } \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ - } \n\ - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ - return promise; \n\ - }; \n\ - notEnumerableProp(ret, '__isPromisified__', true); \n\ - return ret; \n\ - " - .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) - .replace("[GetFunctionCode]", getFunctionCode); - body = body.replace( - "Parameters", - parameterDeclaration(newParameterCount) - ); - return new Function( - "Promise", - "fn", - "receiver", - "withAppended", - "maybeWrapAsError", - "nodebackForPromise", - "tryCatch", - "errorObj", - "notEnumerableProp", - "INTERNAL", - body - )( - Promise, - fn, - receiver, - withAppended, - maybeWrapAsError, - nodebackForPromise, - util.tryCatch, - util.errorObj, - util.notEnumerableProp, - INTERNAL - ); - }; - } +/** + * Applies getters to `value`. + * + * @param {Object} value + * @param {Document} doc The document this virtual is attached to + * @return {any} the value after applying all getters + * @api public + */ - function makeNodePromisifiedClosure( - callback, - receiver, - _, - fn, - __, - multiArgs - ) { - var defaultThis = (function () { - return this; - })(); - var method = callback; - if (typeof method === "string") { - callback = fn; - } - function promisified() { - var _receiver = receiver; - if (receiver === THIS) _receiver = this; - var promise = new Promise(INTERNAL); - promise._captureStackTrace(); - var cb = - typeof method === "string" && this !== defaultThis - ? this[method] - : callback; - var fn = nodebackForPromise(promise, multiArgs); - try { - cb.apply(_receiver, withAppended(arguments, fn)); - } catch (e) { - promise._rejectCallback(maybeWrapAsError(e), true, true); - } - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); - return promise; - } - util.notEnumerableProp(promisified, "__isPromisified__", true); - return promisified; - } - - var makeNodePromisified = canEvaluate - ? makeNodePromisifiedEval - : makeNodePromisifiedClosure; - - function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { - var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); - var methods = promisifiableMethods(obj, suffix, suffixRegexp, filter); - - for (var i = 0, len = methods.length; i < len; i += 2) { - var key = methods[i]; - var fn = methods[i + 1]; - var promisifiedKey = key + suffix; - if (promisifier === makeNodePromisified) { - obj[promisifiedKey] = makeNodePromisified( - key, - THIS, - key, - fn, - suffix, - multiArgs - ); - } else { - var promisified = promisifier(fn, function () { - return makeNodePromisified( - key, - THIS, - key, - fn, - suffix, - multiArgs - ); - }); - util.notEnumerableProp(promisified, "__isPromisified__", true); - obj[promisifiedKey] = promisified; - } - } - util.toFastProperties(obj); - return obj; - } +VirtualType.prototype.applyGetters = function(value, doc) { + if (utils.hasUserDefinedProperty(this.options, ['ref', 'refPath']) && + doc.$$populatedVirtuals && + doc.$$populatedVirtuals.hasOwnProperty(this.path)) { + value = doc.$$populatedVirtuals[this.path]; + } - function promisify(callback, receiver, multiArgs) { - return makeNodePromisified( - callback, - receiver, - undefined, - callback, - null, - multiArgs - ); - } + let v = value; + for (const getter of this.getters) { + v = getter.call(doc, v, this, doc); + } + return v; +}; - Promise.promisify = function (fn, options) { - if (typeof fn !== "function") { - throw new TypeError( - "expecting a function but got " + util.classString(fn) - ); - } - if (isPromisified(fn)) { - return fn; - } - options = Object(options); - var receiver = options.context === undefined ? THIS : options.context; - var multiArgs = !!options.multiArgs; - var ret = promisify(fn, receiver, multiArgs); - util.copyDescriptors(fn, ret, propsFilter); - return ret; - }; +/** + * Applies setters to `value`. + * + * @param {Object} value + * @param {Document} doc + * @return {any} the value after applying all setters + * @api public + */ - Promise.promisifyAll = function (target, options) { - if (typeof target !== "function" && typeof target !== "object") { - throw new TypeError( - "the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a" - ); - } - options = Object(options); - var multiArgs = !!options.multiArgs; - var suffix = options.suffix; - if (typeof suffix !== "string") suffix = defaultSuffix; - var filter = options.filter; - if (typeof filter !== "function") filter = defaultFilter; - var promisifier = options.promisifier; - if (typeof promisifier !== "function") - promisifier = makeNodePromisified; - - if (!util.isIdentifier(suffix)) { - throw new RangeError( - "suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a" - ); - } +VirtualType.prototype.applySetters = function(value, doc) { + let v = value; + for (const setter of this.setters) { + v = setter.call(doc, v, this, doc); + } + return v; +}; - var keys = util.inheritedDataKeys(target); - for (var i = 0; i < keys.length; ++i) { - var value = target[keys[i]]; - if (keys[i] !== "constructor" && util.isClass(value)) { - promisifyAll( - value.prototype, - suffix, - filter, - promisifier, - multiArgs - ); - promisifyAll(value, suffix, filter, promisifier, multiArgs); - } - } +/*! + * exports + */ - return promisifyAll(target, suffix, filter, promisifier, multiArgs); - }; - }; +module.exports = VirtualType; - /***/ - }, - /***/ 8717: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function ( - Promise, - PromiseArray, - tryConvertToPromise, - apiRejection - ) { - var util = __nccwpck_require__(2122); - var isObject = util.isObject; - var es5 = __nccwpck_require__(9432); - var Es6Map; - if (typeof Map === "function") Es6Map = Map; - - var mapToEntries = (function () { - var index = 0; - var size = 0; - - function extractEntry(value, key) { - this[index] = value; - this[index + size] = key; - index++; - } +/***/ }), - return function mapToEntries(map) { - size = map.size; - index = 0; - var ret = new Array(map.size * 2); - map.forEach(extractEntry, ret); - return ret; - }; - })(); - - var entriesToMap = function (entries) { - var ret = new Es6Map(); - var length = (entries.length / 2) | 0; - for (var i = 0; i < length; ++i) { - var key = entries[length + i]; - var value = entries[i]; - ret.set(key, value); - } - return ret; - }; +/***/ 8586: +/***/ ((module, exports, __nccwpck_require__) => { - function PropertiesPromiseArray(obj) { - var isMap = false; - var entries; - if (Es6Map !== undefined && obj instanceof Es6Map) { - entries = mapToEntries(obj); - isMap = true; - } else { - var keys = es5.keys(obj); - var len = keys.length; - entries = new Array(len * 2); - for (var i = 0; i < len; ++i) { - var key = keys[i]; - entries[i] = obj[key]; - entries[i + len] = key; - } - } - this.constructor$(entries); - this._isMap = isMap; - this._init$(undefined, isMap ? -6 : -3); - } - util.inherits(PropertiesPromiseArray, PromiseArray); +"use strict"; - PropertiesPromiseArray.prototype._init = function () {}; - PropertiesPromiseArray.prototype._promiseFulfilled = function ( - value, - index - ) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - var val; - if (this._isMap) { - val = entriesToMap(this._values); - } else { - val = {}; - var keyOffset = this.length(); - for (var i = 0, len = this.length(); i < len; ++i) { - val[this._values[i + keyOffset]] = this._values[i]; - } - } - this._resolve(val); - return true; - } - return false; - }; +module.exports = exports = __nccwpck_require__(9741); - PropertiesPromiseArray.prototype.shouldCopyValues = function () { - return false; - }; - PropertiesPromiseArray.prototype.getActualLength = function (len) { - return len >> 1; - }; +/***/ }), - function props(promises) { - var ret; - var castValue = tryConvertToPromise(promises); +/***/ 9741: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!isObject(castValue)) { - return apiRejection( - "cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a" - ); - } else if (castValue instanceof Promise) { - ret = castValue._then( - Promise.props, - undefined, - undefined, - undefined, - undefined - ); - } else { - ret = new PropertiesPromiseArray(castValue).promise(); - } +/* eslint strict:off */ +/* eslint no-var: off */ +/* eslint no-redeclare: off */ - if (castValue instanceof Promise) { - ret._propagateFrom(castValue, 2); - } - return ret; - } +var stringToParts = __nccwpck_require__(9655); - Promise.prototype.props = function () { - return props(this); - }; +// These properties are special and can open client libraries to security +// issues +var ignoreProperties = ['__proto__', 'constructor', 'prototype']; - Promise.props = function (promises) { - return props(promises); - }; - }; +/** + * Returns the value of object `o` at the given `path`. + * + * ####Example: + * + * var obj = { + * comments: [ + * { title: 'exciting!', _doc: { title: 'great!' }} + * , { title: 'number dos' } + * ] + * } + * + * mpath.get('comments.0.title', o) // 'exciting!' + * mpath.get('comments.0.title', o, '_doc') // 'great!' + * mpath.get('comments.title', o) // ['exciting!', 'number dos'] + * + * // summary + * mpath.get(path, o) + * mpath.get(path, o, special) + * mpath.get(path, o, map) + * mpath.get(path, o, special, map) + * + * @param {String} path + * @param {Object} o + * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. + * @param {Function} [map] Optional function which receives each individual found value. The value returned from `map` is used in the original values place. + */ - /***/ - }, +exports.get = function(path, o, special, map) { + var lookup; - /***/ 632: /***/ (module) => { - "use strict"; + if ('function' == typeof special) { + if (special.length < 2) { + map = special; + special = undefined; + } else { + lookup = special; + special = undefined; + } + } - function arrayMove(src, srcIndex, dst, dstIndex, len) { - for (var j = 0; j < len; ++j) { - dst[j + dstIndex] = src[j + srcIndex]; - src[j + srcIndex] = void 0; - } - } + map || (map = K); - function Queue(capacity) { - this._capacity = capacity; - this._length = 0; - this._front = 0; - } + var parts = 'string' == typeof path + ? stringToParts(path) + : path; - Queue.prototype._willBeOverCapacity = function (size) { - return this._capacity < size; - }; + if (!Array.isArray(parts)) { + throw new TypeError('Invalid `path`. Must be either string or array'); + } - Queue.prototype._pushOne = function (arg) { - var length = this.length(); - this._checkCapacity(length + 1); - var i = (this._front + length) & (this._capacity - 1); - this[i] = arg; - this._length = length + 1; - }; + var obj = o, + part; - Queue.prototype.push = function (fn, receiver, arg) { - var length = this.length() + 3; - if (this._willBeOverCapacity(length)) { - this._pushOne(fn); - this._pushOne(receiver); - this._pushOne(arg); - return; - } - var j = this._front + length - 3; - this._checkCapacity(length); - var wrapMask = this._capacity - 1; - this[(j + 0) & wrapMask] = fn; - this[(j + 1) & wrapMask] = receiver; - this[(j + 2) & wrapMask] = arg; - this._length = length; - }; + for (var i = 0; i < parts.length; ++i) { + part = parts[i]; + if (typeof parts[i] !== 'string' && typeof parts[i] !== 'number') { + throw new TypeError('Each segment of path to `get()` must be a string or number, got ' + typeof parts[i]); + } - Queue.prototype.shift = function () { - var front = this._front, - ret = this[front]; + if (Array.isArray(obj) && !/^\d+$/.test(part)) { + // reading a property from the array items + var paths = parts.slice(i); - this[front] = undefined; - this._front = (front + 1) & (this._capacity - 1); - this._length--; - return ret; - }; + // Need to `concat()` to avoid `map()` calling a constructor of an array + // subclass + return [].concat(obj).map(function(item) { + return item + ? exports.get(paths, item, special || lookup, map) + : map(undefined); + }); + } - Queue.prototype.length = function () { - return this._length; - }; + if (lookup) { + obj = lookup(obj, part); + } else { + var _from = special && obj[special] ? obj[special] : obj; + obj = _from instanceof Map ? + _from.get(part) : + _from[part]; + } - Queue.prototype._checkCapacity = function (size) { - if (this._capacity < size) { - this._resizeTo(this._capacity << 1); - } - }; + if (!obj) return map(obj); + } - Queue.prototype._resizeTo = function (capacity) { - var oldCapacity = this._capacity; - this._capacity = capacity; - var front = this._front; - var length = this._length; - var moveItemsCount = (front + length) & (oldCapacity - 1); - arrayMove(this, 0, this, oldCapacity, moveItemsCount); - }; + return map(obj); +}; - module.exports = Queue; +/** + * Returns true if `in` returns true for every piece of the path + * + * @param {String} path + * @param {Object} o + */ - /***/ - }, +exports.has = function(path, o) { + var parts = typeof path === 'string' ? + stringToParts(path) : + path; - /***/ 4668: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function ( - Promise, - INTERNAL, - tryConvertToPromise, - apiRejection - ) { - var util = __nccwpck_require__(2122); - - var raceLater = function (promise) { - return promise.then(function (array) { - return race(array, promise); - }); - }; + if (!Array.isArray(parts)) { + throw new TypeError('Invalid `path`. Must be either string or array'); + } - function race(promises, parent) { - var maybePromise = tryConvertToPromise(promises); + var len = parts.length; + var cur = o; + for (var i = 0; i < len; ++i) { + if (typeof parts[i] !== 'string' && typeof parts[i] !== 'number') { + throw new TypeError('Each segment of path to `has()` must be a string or number, got ' + typeof parts[i]); + } + if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) { + return false; + } + cur = cur[parts[i]]; + } - if (maybePromise instanceof Promise) { - return raceLater(maybePromise); - } else { - promises = util.asArray(promises); - if (promises === null) - return apiRejection( - "expecting an array or an iterable object but got " + - util.classString(promises) - ); - } + return true; +}; - var ret = new Promise(INTERNAL); - if (parent !== undefined) { - ret._propagateFrom(parent, 3); - } - var fulfill = ret._fulfill; - var reject = ret._reject; - for (var i = 0, len = promises.length; i < len; ++i) { - var val = promises[i]; +/** + * Deletes the last piece of `path` + * + * @param {String} path + * @param {Object} o + */ - if (val === undefined && !(i in promises)) { - continue; - } +exports.unset = function(path, o) { + var parts = typeof path === 'string' ? + stringToParts(path) : + path; - Promise.cast(val)._then(fulfill, reject, undefined, ret, null); - } - return ret; - } + if (!Array.isArray(parts)) { + throw new TypeError('Invalid `path`. Must be either string or array'); + } - Promise.race = function (promises) { - return race(promises, undefined); - }; + var len = parts.length; + var cur = o; + for (var i = 0; i < len; ++i) { + if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) { + return false; + } + if (typeof parts[i] !== 'string' && typeof parts[i] !== 'number') { + throw new TypeError('Each segment of path to `unset()` must be a string or number, got ' + typeof parts[i]); + } + // Disallow any updates to __proto__ or special properties. + if (ignoreProperties.indexOf(parts[i]) !== -1) { + return false; + } + if (i === len - 1) { + delete cur[parts[i]]; + return true; + } + cur = cur instanceof Map ? cur.get(parts[i]) : cur[parts[i]]; + } - Promise.prototype.race = function () { - return race(this, undefined); - }; - }; + return true; +}; - /***/ - }, +/** + * Sets the `val` at the given `path` of object `o`. + * + * @param {String} path + * @param {Anything} val + * @param {Object} o + * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. + * @param {Function} [map] Optional function which is passed each individual value before setting it. The value returned from `map` is used in the original values place. + */ - /***/ 986: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function ( - Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug - ) { - var getDomain = Promise._getDomain; - var util = __nccwpck_require__(2122); - var tryCatch = util.tryCatch; - - function ReductionPromiseArray(promises, fn, initialValue, _each) { - this.constructor$(promises); - var domain = getDomain(); - this._fn = domain === null ? fn : util.domainBind(domain, fn); - if (initialValue !== undefined) { - initialValue = Promise.resolve(initialValue); - initialValue._attachCancellationCallback(this); - } - this._initialValue = initialValue; - this._currentCancellable = null; - if (_each === INTERNAL) { - this._eachValues = Array(this._length); - } else if (_each === 0) { - this._eachValues = null; - } else { - this._eachValues = undefined; - } - this._promise._captureStackTrace(); - this._init$(undefined, -5); - } - util.inherits(ReductionPromiseArray, PromiseArray); - - ReductionPromiseArray.prototype._gotAccum = function (accum) { - if ( - this._eachValues !== undefined && - this._eachValues !== null && - accum !== INTERNAL - ) { - this._eachValues.push(accum); - } - }; +exports.set = function(path, val, o, special, map, _copying) { + var lookup; - ReductionPromiseArray.prototype._eachComplete = function (value) { - if (this._eachValues !== null) { - this._eachValues.push(value); - } - return this._eachValues; - }; + if ('function' == typeof special) { + if (special.length < 2) { + map = special; + special = undefined; + } else { + lookup = special; + special = undefined; + } + } - ReductionPromiseArray.prototype._init = function () {}; + map || (map = K); - ReductionPromiseArray.prototype._resolveEmptyArray = function () { - this._resolve( - this._eachValues !== undefined - ? this._eachValues - : this._initialValue - ); - }; + var parts = 'string' == typeof path + ? stringToParts(path) + : path; - ReductionPromiseArray.prototype.shouldCopyValues = function () { - return false; - }; + if (!Array.isArray(parts)) { + throw new TypeError('Invalid `path`. Must be either string or array'); + } - ReductionPromiseArray.prototype._resolve = function (value) { - this._promise._resolveCallback(value); - this._values = null; - }; + if (null == o) return; - ReductionPromiseArray.prototype._resultCancelled = function (sender) { - if (sender === this._initialValue) return this._cancel(); - if (this._isResolved()) return; - this._resultCancelled$(); - if (this._currentCancellable instanceof Promise) { - this._currentCancellable.cancel(); - } - if (this._initialValue instanceof Promise) { - this._initialValue.cancel(); - } - }; + for (var i = 0; i < parts.length; ++i) { + if (typeof parts[i] !== 'string' && typeof parts[i] !== 'number') { + throw new TypeError('Each segment of path to `set()` must be a string or number, got ' + typeof parts[i]); + } + // Silently ignore any updates to `__proto__`, these are potentially + // dangerous if using mpath with unsanitized data. + if (ignoreProperties.indexOf(parts[i]) !== -1) { + return; + } + } - ReductionPromiseArray.prototype._iterate = function (values) { - this._values = values; - var value; - var i; - var length = values.length; - if (this._initialValue !== undefined) { - value = this._initialValue; - i = 0; - } else { - value = Promise.resolve(values[0]); - i = 1; - } + // the existance of $ in a path tells us if the user desires + // the copying of an array instead of setting each value of + // the array to the one by one to matching positions of the + // current array. Unless the user explicitly opted out by passing + // false, see Automattic/mongoose#6273 + var copy = _copying || (/\$/.test(path) && _copying !== false), + obj = o, + part; + + for (var i = 0, len = parts.length - 1; i < len; ++i) { + part = parts[i]; + + if ('$' == part) { + if (i == len - 1) { + break; + } else { + continue; + } + } - this._currentCancellable = value; - - if (!value.isRejected()) { - for (; i < length; ++i) { - var ctx = { - accum: null, - value: values[i], - index: i, - length: length, - array: this, - }; - value = value._then( - gotAccum, - undefined, - undefined, - ctx, - undefined - ); - } - } + if (Array.isArray(obj) && !/^\d+$/.test(part)) { + var paths = parts.slice(i); + if (!copy && Array.isArray(val)) { + for (var j = 0; j < obj.length && j < val.length; ++j) { + // assignment of single values of array + exports.set(paths, val[j], obj[j], special || lookup, map, copy); + } + } else { + for (var j = 0; j < obj.length; ++j) { + // assignment of entire value + exports.set(paths, val, obj[j], special || lookup, map, copy); + } + } + return; + } - if (this._eachValues !== undefined) { - value = value._then( - this._eachComplete, - undefined, - undefined, - this, - undefined - ); - } - value._then(completed, completed, undefined, value, this); - }; + if (lookup) { + obj = lookup(obj, part); + } else { + var _to = special && obj[special] ? obj[special] : obj; + obj = _to instanceof Map ? + _to.get(part) : + _to[part]; + } - Promise.prototype.reduce = function (fn, initialValue) { - return reduce(this, fn, initialValue, null); - }; + if (!obj) return; + } - Promise.reduce = function (promises, fn, initialValue, _each) { - return reduce(promises, fn, initialValue, _each); - }; + // process the last property of the path - function completed(valueOrReason, array) { - if (this.isFulfilled()) { - array._resolve(valueOrReason); - } else { - array._reject(valueOrReason); - } - } + part = parts[len]; - function reduce(promises, fn, initialValue, _each) { - if (typeof fn !== "function") { - return apiRejection( - "expecting a function but got " + util.classString(fn) - ); - } - var array = new ReductionPromiseArray( - promises, - fn, - initialValue, - _each - ); - return array.promise(); - } + // use the special property if exists + if (special && obj[special]) { + obj = obj[special]; + } - function gotAccum(accum) { - this.accum = accum; - this.array._gotAccum(accum); - var value = tryConvertToPromise(this.value, this.array._promise); - if (value instanceof Promise) { - this.array._currentCancellable = value; - return value._then(gotValue, undefined, undefined, this, undefined); + // set the value on the last branch + if (Array.isArray(obj) && !/^\d+$/.test(part)) { + if (!copy && Array.isArray(val)) { + _setArray(obj, val, part, lookup, special, map); + } else { + for (var j = 0; j < obj.length; ++j) { + var item = obj[j]; + if (item) { + if (lookup) { + lookup(item, part, map(val)); } else { - return gotValue.call(this, value); + if (item[special]) item = item[special]; + item[part] = map(val); } } + } + } + } else { + if (lookup) { + lookup(obj, part, map(val)); + } else if (obj instanceof Map) { + obj.set(part, map(val)); + } else { + obj[part] = map(val); + } + } +}; - function gotValue(value) { - var array = this.array; - var promise = array._promise; - var fn = tryCatch(array._fn); - promise._pushContext(); - var ret; - if (array._eachValues !== undefined) { - ret = fn.call( - promise._boundValue(), - value, - this.index, - this.length - ); - } else { - ret = fn.call( - promise._boundValue(), - this.accum, - value, - this.index, - this.length - ); - } - if (ret instanceof Promise) { - array._currentCancellable = ret; - } - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", - promise - ); - return ret; - } - }; +/*! + * Recursively set nested arrays + */ - /***/ - }, +function _setArray(obj, val, part, lookup, special, map) { + for (var item, j = 0; j < obj.length && j < val.length; ++j) { + item = obj[j]; + if (Array.isArray(item) && Array.isArray(val[j])) { + _setArray(item, val[j], part, lookup, special, map); + } else if (item) { + if (lookup) { + lookup(item, part, map(val[j])); + } else { + if (item[special]) item = item[special]; + item[part] = map(val[j]); + } + } + } +} - /***/ 5989: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - var util = __nccwpck_require__(2122); - var schedule; - var noAsyncScheduler = function () { - throw new Error( - "No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a" - ); - }; - var NativePromise = util.getNativePromise(); - if (util.isNode && typeof MutationObserver === "undefined") { - var GlobalSetImmediate = global.setImmediate; - var ProcessNextTick = process.nextTick; - schedule = util.isRecentNode - ? function (fn) { - GlobalSetImmediate.call(global, fn); - } - : function (fn) { - ProcessNextTick.call(process, fn); - }; - } else if ( - typeof NativePromise === "function" && - typeof NativePromise.resolve === "function" - ) { - var nativePromise = NativePromise.resolve(); - schedule = function (fn) { - nativePromise.then(fn); - }; - } else if ( - typeof MutationObserver !== "undefined" && - !( - typeof window !== "undefined" && - window.navigator && - (window.navigator.standalone || window.cordova) - ) - ) { - schedule = (function () { - var div = document.createElement("div"); - var opts = { attributes: true }; - var toggleScheduled = false; - var div2 = document.createElement("div"); - var o2 = new MutationObserver(function () { - div.classList.toggle("foo"); - toggleScheduled = false; - }); - o2.observe(div2, opts); +/*! + * Returns the value passed to it. + */ - var scheduleToggle = function () { - if (toggleScheduled) return; - toggleScheduled = true; - div2.classList.toggle("foo"); - }; +function K(v) { + return v; +} - return function schedule(fn) { - var o = new MutationObserver(function () { - o.disconnect(); - fn(); - }); - o.observe(div, opts); - scheduleToggle(); - }; - })(); - } else if (typeof setImmediate !== "undefined") { - schedule = function (fn) { - setImmediate(fn); - }; - } else if (typeof setTimeout !== "undefined") { - schedule = function (fn) { - setTimeout(fn, 0); - }; - } else { - schedule = noAsyncScheduler; - } - module.exports = schedule; +/***/ }), - /***/ - }, +/***/ 9655: +/***/ ((module) => { - /***/ 1506: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +"use strict"; - module.exports = function (Promise, PromiseArray, debug) { - var PromiseInspection = Promise.PromiseInspection; - var util = __nccwpck_require__(2122); - function SettledPromiseArray(values) { - this.constructor$(values); - } - util.inherits(SettledPromiseArray, PromiseArray); +module.exports = function stringToParts(str) { + const result = []; - SettledPromiseArray.prototype._promiseResolved = function ( - index, - inspection - ) { - this._values[index] = inspection; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; - }; + let curPropertyName = ''; + let state = 'DEFAULT'; + for (let i = 0; i < str.length; ++i) { + // Fall back to treating as property name rather than bracket notation if + // square brackets contains something other than a number. + if (state === 'IN_SQUARE_BRACKETS' && !/\d/.test(str[i]) && str[i] !== ']') { + state = 'DEFAULT'; + curPropertyName = result[result.length - 1] + '[' + curPropertyName; + result.splice(result.length - 1, 1); + } - SettledPromiseArray.prototype._promiseFulfilled = function ( - value, - index - ) { - var ret = new PromiseInspection(); - ret._bitField = 33554432; - ret._settledValueField = value; - return this._promiseResolved(index, ret); - }; - SettledPromiseArray.prototype._promiseRejected = function ( - reason, - index - ) { - var ret = new PromiseInspection(); - ret._bitField = 16777216; - ret._settledValueField = reason; - return this._promiseResolved(index, ret); - }; + if (str[i] === '[') { + if (state !== 'IMMEDIATELY_AFTER_SQUARE_BRACKETS') { + result.push(curPropertyName); + curPropertyName = ''; + } + state = 'IN_SQUARE_BRACKETS'; + } else if (str[i] === ']') { + if (state === 'IN_SQUARE_BRACKETS') { + state = 'IMMEDIATELY_AFTER_SQUARE_BRACKETS'; + result.push(curPropertyName); + curPropertyName = ''; + } else { + state = 'DEFAULT'; + curPropertyName += str[i]; + } + } else if (str[i] === '.') { + if (state !== 'IMMEDIATELY_AFTER_SQUARE_BRACKETS') { + result.push(curPropertyName); + curPropertyName = ''; + } + state = 'DEFAULT'; + } else { + curPropertyName += str[i]; + } + } - Promise.settle = function (promises) { - debug.deprecated(".settle()", ".reflect()"); - return new SettledPromiseArray(promises).promise(); - }; + if (state !== 'IMMEDIATELY_AFTER_SQUARE_BRACKETS') { + result.push(curPropertyName); + } - Promise.prototype.settle = function () { - return Promise.settle(this); - }; - }; + return result; +}; - /***/ - }, +/***/ }), - /***/ 2807: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function (Promise, PromiseArray, apiRejection) { - var util = __nccwpck_require__(2122); - var RangeError = __nccwpck_require__(1522).RangeError; - var AggregateError = __nccwpck_require__(1522).AggregateError; - var isArray = util.isArray; - var CANCELLATION = {}; - - function SomePromiseArray(values) { - this.constructor$(values); - this._howMany = 0; - this._unwrap = false; - this._initialized = false; - } - util.inherits(SomePromiseArray, PromiseArray); - - SomePromiseArray.prototype._init = function () { - if (!this._initialized) { - return; - } - if (this._howMany === 0) { - this._resolve([]); - return; - } - this._init$(undefined, -5); - var isArrayResolved = isArray(this._values); - if ( - !this._isResolved() && - isArrayResolved && - this._howMany > this._canPossiblyFulfill() - ) { - this._reject(this._getRangeError(this.length())); - } - }; +/***/ 5257: +/***/ ((module, exports) => { - SomePromiseArray.prototype.init = function () { - this._initialized = true; - this._init(); - }; +"use strict"; - SomePromiseArray.prototype.setUnwrap = function () { - this._unwrap = true; - }; - SomePromiseArray.prototype.howMany = function () { - return this._howMany; - }; +/** + * methods a collection must implement + */ - SomePromiseArray.prototype.setHowMany = function (count) { - this._howMany = count; - }; +const methods = [ + 'find', + 'findOne', + 'update', + 'updateMany', + 'updateOne', + 'replaceOne', + 'remove', + 'count', + 'distinct', + 'findOneAndDelete', + 'findOneAndUpdate', + 'aggregate', + 'findCursor', + 'deleteOne', + 'deleteMany' +]; + +/** + * Collection base class from which implementations inherit + */ - SomePromiseArray.prototype._promiseFulfilled = function (value) { - this._addFulfilled(value); - if (this._fulfilled() === this.howMany()) { - this._values.length = this.howMany(); - if (this.howMany() === 1 && this._unwrap) { - this._resolve(this._values[0]); - } else { - this._resolve(this._values); - } - return true; - } - return false; - }; - SomePromiseArray.prototype._promiseRejected = function (reason) { - this._addRejected(reason); - return this._checkOutcome(); - }; +function Collection() {} - SomePromiseArray.prototype._promiseCancelled = function () { - if (this._values instanceof Promise || this._values == null) { - return this._cancel(); - } - this._addRejected(CANCELLATION); - return this._checkOutcome(); - }; +for (let i = 0, len = methods.length; i < len; ++i) { + const method = methods[i]; + Collection.prototype[method] = notImplemented(method); +} - SomePromiseArray.prototype._checkOutcome = function () { - if (this.howMany() > this._canPossiblyFulfill()) { - var e = new AggregateError(); - for (var i = this.length(); i < this._values.length; ++i) { - if (this._values[i] !== CANCELLATION) { - e.push(this._values[i]); - } - } - if (e.length > 0) { - this._reject(e); - } else { - this._cancel(); - } - return true; - } - return false; - }; +module.exports = exports = Collection; +Collection.methods = methods; - SomePromiseArray.prototype._fulfilled = function () { - return this._totalResolved; - }; +/** + * creates a function which throws an implementation error + */ - SomePromiseArray.prototype._rejected = function () { - return this._values.length - this.length(); - }; +function notImplemented(method) { + return function() { + throw new Error('collection.' + method + ' not implemented'); + }; +} - SomePromiseArray.prototype._addRejected = function (reason) { - this._values.push(reason); - }; - SomePromiseArray.prototype._addFulfilled = function (value) { - this._values[this._totalResolved++] = value; - }; +/***/ }), + +/***/ 5680: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - SomePromiseArray.prototype._canPossiblyFulfill = function () { - return this.length() - this._rejected(); - }; +"use strict"; - SomePromiseArray.prototype._getRangeError = function (count) { - var message = - "Input array must contain at least " + - this._howMany + - " items but contains only " + - count + - " items"; - return new RangeError(message); - }; - SomePromiseArray.prototype._resolveEmptyArray = function () { - this._reject(this._getRangeError(0)); - }; +const env = __nccwpck_require__(5928); - function some(promises, howMany) { - if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection( - "expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a" - ); - } - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - ret.setHowMany(howMany); - ret.init(); - return promise; - } +if ('unknown' == env.type) { + throw new Error('Unknown environment'); +} - Promise.some = function (promises, howMany) { - return some(promises, howMany); - }; +module.exports = + env.isNode ? __nccwpck_require__(7901) : + env.isMongo ? __nccwpck_require__(5257) : + __nccwpck_require__(5257); - Promise.prototype.some = function (howMany) { - return some(this, howMany); - }; - Promise._SomePromiseArray = SomePromiseArray; - }; - /***/ - }, +/***/ }), - /***/ 4084: /***/ (module) => { - "use strict"; - - module.exports = function (Promise) { - function PromiseInspection(promise) { - if (promise !== undefined) { - promise = promise._target(); - this._bitField = promise._bitField; - this._settledValueField = promise._isFateSealed() - ? promise._settledValue() - : undefined; - } else { - this._bitField = 0; - this._settledValueField = undefined; - } - } +/***/ 7901: +/***/ ((module, exports, __nccwpck_require__) => { - PromiseInspection.prototype._settledValue = function () { - return this._settledValueField; - }; +"use strict"; - var value = (PromiseInspection.prototype.value = function () { - if (!this.isFulfilled()) { - throw new TypeError( - "cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a" - ); - } - return this._settledValue(); - }); - var reason = - (PromiseInspection.prototype.error = - PromiseInspection.prototype.reason = - function () { - if (!this.isRejected()) { - throw new TypeError( - "cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a" - ); - } - return this._settledValue(); - }); +/** + * Module dependencies + */ - var isFulfilled = (PromiseInspection.prototype.isFulfilled = - function () { - return (this._bitField & 33554432) !== 0; - }); +const Collection = __nccwpck_require__(5257); +const utils = __nccwpck_require__(7483); - var isRejected = (PromiseInspection.prototype.isRejected = function () { - return (this._bitField & 16777216) !== 0; - }); +function NodeCollection(col) { + this.collection = col; + this.collectionName = col.collectionName; +} - var isPending = (PromiseInspection.prototype.isPending = function () { - return (this._bitField & 50397184) === 0; - }); +/** + * inherit from collection base class + */ - var isResolved = (PromiseInspection.prototype.isResolved = function () { - return (this._bitField & 50331648) !== 0; - }); +utils.inherits(NodeCollection, Collection); - PromiseInspection.prototype.isCancelled = function () { - return (this._bitField & 8454144) !== 0; - }; +/** + * find(match, options, function(err, docs)) + */ - Promise.prototype.__isCancelled = function () { - return (this._bitField & 65536) === 65536; - }; +NodeCollection.prototype.find = function(match, options, cb) { + const cursor = this.collection.find(match, options); - Promise.prototype._isCancelled = function () { - return this._target().__isCancelled(); - }; + try { + cursor.toArray(cb); + } catch (error) { + cb(error); + } +}; - Promise.prototype.isCancelled = function () { - return (this._target()._bitField & 8454144) !== 0; - }; +/** + * findOne(match, options, function(err, doc)) + */ - Promise.prototype.isPending = function () { - return isPending.call(this._target()); - }; +NodeCollection.prototype.findOne = function(match, options, cb) { + this.collection.findOne(match, options, cb); +}; - Promise.prototype.isRejected = function () { - return isRejected.call(this._target()); - }; +/** + * count(match, options, function(err, count)) + */ - Promise.prototype.isFulfilled = function () { - return isFulfilled.call(this._target()); - }; +NodeCollection.prototype.count = function(match, options, cb) { + this.collection.count(match, options, cb); +}; - Promise.prototype.isResolved = function () { - return isResolved.call(this._target()); - }; +/** + * distinct(prop, match, options, function(err, count)) + */ - Promise.prototype.value = function () { - return value.call(this._target()); - }; +NodeCollection.prototype.distinct = function(prop, match, options, cb) { + this.collection.distinct(prop, match, options, cb); +}; - Promise.prototype.reason = function () { - var target = this._target(); - target._unsetRejectionIsUnhandled(); - return reason.call(target); - }; +/** + * update(match, update, options, function(err[, result])) + */ - Promise.prototype._value = function () { - return this._settledValue(); - }; +NodeCollection.prototype.update = function(match, update, options, cb) { + this.collection.update(match, update, options, cb); +}; - Promise.prototype._reason = function () { - this._unsetRejectionIsUnhandled(); - return this._settledValue(); - }; +/** + * update(match, update, options, function(err[, result])) + */ - Promise.PromiseInspection = PromiseInspection; - }; +NodeCollection.prototype.updateMany = function(match, update, options, cb) { + this.collection.updateMany(match, update, options, cb); +}; - /***/ - }, +/** + * update(match, update, options, function(err[, result])) + */ - /***/ 4997: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function (Promise, INTERNAL) { - var util = __nccwpck_require__(2122); - var errorObj = util.errorObj; - var isObject = util.isObject; - - function tryConvertToPromise(obj, context) { - if (isObject(obj)) { - if (obj instanceof Promise) return obj; - var then = getThen(obj); - if (then === errorObj) { - if (context) context._pushContext(); - var ret = Promise.reject(then.e); - if (context) context._popContext(); - return ret; - } else if (typeof then === "function") { - if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - obj._then(ret._fulfill, ret._reject, undefined, ret, null); - return ret; - } - return doThenable(obj, then, context); - } - } - return obj; - } +NodeCollection.prototype.updateOne = function(match, update, options, cb) { + this.collection.updateOne(match, update, options, cb); +}; - function doGetThen(obj) { - return obj.then; - } +/** + * replaceOne(match, update, options, function(err[, result])) + */ - function getThen(obj) { - try { - return doGetThen(obj); - } catch (e) { - errorObj.e = e; - return errorObj; - } - } +NodeCollection.prototype.replaceOne = function(match, update, options, cb) { + this.collection.replaceOne(match, update, options, cb); +}; - var hasProp = {}.hasOwnProperty; - function isAnyBluebirdPromise(obj) { - try { - return hasProp.call(obj, "_promise0"); - } catch (e) { - return false; - } - } +/** + * deleteOne(match, options, function(err[, result]) + */ - function doThenable(x, then, context) { - var promise = new Promise(INTERNAL); - var ret = promise; - if (context) context._pushContext(); - promise._captureStackTrace(); - if (context) context._popContext(); - var synchronous = true; - var result = util.tryCatch(then).call(x, resolve, reject); - synchronous = false; +NodeCollection.prototype.deleteOne = function(match, options, cb) { + this.collection.deleteOne(match, options, cb); +}; - if (promise && result === errorObj) { - promise._rejectCallback(result.e, true, true); - promise = null; - } +/** + * deleteMany(match, options, function(err[, result]) + */ - function resolve(value) { - if (!promise) return; - promise._resolveCallback(value); - promise = null; - } +NodeCollection.prototype.deleteMany = function(match, options, cb) { + this.collection.deleteMany(match, options, cb); +}; - function reject(reason) { - if (!promise) return; - promise._rejectCallback(reason, synchronous, true); - promise = null; - } - return ret; - } +/** + * remove(match, options, function(err[, result]) + */ - return tryConvertToPromise; - }; +NodeCollection.prototype.remove = function(match, options, cb) { + this.collection.remove(match, options, cb); +}; - /***/ - }, +/** + * findOneAndDelete(match, options, function(err[, result]) + */ - /***/ 3482: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +NodeCollection.prototype.findOneAndDelete = function(match, options, cb) { + this.collection.findOneAndDelete(match, options, cb); +}; - module.exports = function (Promise, INTERNAL, debug) { - var util = __nccwpck_require__(2122); - var TimeoutError = Promise.TimeoutError; +/** + * findOneAndUpdate(match, update, options, function(err[, result]) + */ - function HandleWrapper(handle) { - this.handle = handle; - } +NodeCollection.prototype.findOneAndUpdate = function(match, update, options, cb) { + this.collection.findOneAndUpdate(match, update, options, cb); +}; - HandleWrapper.prototype._resultCancelled = function () { - clearTimeout(this.handle); - }; +/** + * var cursor = findCursor(match, options) + */ - var afterValue = function (value) { - return delay(+this).thenReturn(value); - }; - var delay = (Promise.delay = function (ms, value) { - var ret; - var handle; - if (value !== undefined) { - ret = Promise.resolve(value)._then( - afterValue, - null, - null, - ms, - undefined - ); - if (debug.cancellation() && value instanceof Promise) { - ret._setOnCancel(value); - } - } else { - ret = new Promise(INTERNAL); - handle = setTimeout(function () { - ret._fulfill(); - }, +ms); - if (debug.cancellation()) { - ret._setOnCancel(new HandleWrapper(handle)); - } - ret._captureStackTrace(); - } - ret._setAsyncGuaranteed(); - return ret; - }); +NodeCollection.prototype.findCursor = function(match, options) { + return this.collection.find(match, options); +}; - Promise.prototype.delay = function (ms) { - return delay(ms, this); - }; +/** + * aggregation(operators..., function(err, doc)) + * TODO + */ - var afterTimeout = function (promise, message, parent) { - var err; - if (typeof message !== "string") { - if (message instanceof Error) { - err = message; - } else { - err = new TimeoutError("operation timed out"); - } - } else { - err = new TimeoutError(message); - } - util.markAsOriginatingFromRejection(err); - promise._attachExtraTrace(err); - promise._reject(err); +/** + * Expose + */ - if (parent != null) { - parent.cancel(); - } - }; +module.exports = exports = NodeCollection; - function successClear(value) { - clearTimeout(this.handle); - return value; - } - function failureClear(reason) { - clearTimeout(this.handle); - throw reason; - } +/***/ }), - Promise.prototype.timeout = function (ms, message) { - ms = +ms; - var ret, parent; +/***/ 5928: +/***/ ((__unused_webpack_module, exports) => { - var handleWrapper = new HandleWrapper( - setTimeout(function timeoutTimeout() { - if (ret.isPending()) { - afterTimeout(ret, message, parent); - } - }, ms) - ); +"use strict"; - if (debug.cancellation()) { - parent = this.then(); - ret = parent._then( - successClear, - failureClear, - undefined, - handleWrapper, - undefined - ); - ret._setOnCancel(handleWrapper); - } else { - ret = this._then( - successClear, - failureClear, - undefined, - handleWrapper, - undefined - ); - } - return ret; - }; - }; +exports.isNode = 'undefined' != typeof process + && 'object' == "object" + && 'object' == typeof global + && 'function' == typeof Buffer + && process.argv; - /***/ - }, +exports.isMongo = !exports.isNode + && 'function' == typeof printjson + && 'function' == typeof ObjectId + && 'function' == typeof rs + && 'function' == typeof sh; - /***/ 9626: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - module.exports = function ( - Promise, - apiRejection, - tryConvertToPromise, - createContext, - INTERNAL, - debug - ) { - var util = __nccwpck_require__(2122); - var TypeError = __nccwpck_require__(1522).TypeError; - var inherits = __nccwpck_require__(2122).inherits; - var errorObj = util.errorObj; - var tryCatch = util.tryCatch; - var NULL = {}; - - function thrower(e) { - setTimeout(function () { - throw e; - }, 0); - } - - function castPreservingDisposable(thenable) { - var maybePromise = tryConvertToPromise(thenable); - if ( - maybePromise !== thenable && - typeof thenable._isDisposable === "function" && - typeof thenable._getDisposer === "function" && - thenable._isDisposable() - ) { - maybePromise._setDisposable(thenable._getDisposer()); - } - return maybePromise; - } - function dispose(resources, inspection) { - var i = 0; - var len = resources.length; - var ret = new Promise(INTERNAL); - function iterator() { - if (i >= len) return ret._fulfill(); - var maybePromise = castPreservingDisposable(resources[i++]); - if ( - maybePromise instanceof Promise && - maybePromise._isDisposable() - ) { - try { - maybePromise = tryConvertToPromise( - maybePromise._getDisposer().tryDispose(inspection), - resources.promise - ); - } catch (e) { - return thrower(e); - } - if (maybePromise instanceof Promise) { - return maybePromise._then(iterator, thrower, null, null, null); - } - } - iterator(); - } - iterator(); - return ret; - } +exports.isBrowser = !exports.isNode + && !exports.isMongo + && 'undefined' != typeof window; - function Disposer(data, promise, context) { - this._data = data; - this._promise = promise; - this._context = context; - } +exports.type = exports.isNode ? 'node' + : exports.isMongo ? 'mongo' + : exports.isBrowser ? 'browser' + : 'unknown'; - Disposer.prototype.data = function () { - return this._data; - }; - Disposer.prototype.promise = function () { - return this._promise; - }; +/***/ }), - Disposer.prototype.resource = function () { - if (this.promise().isFulfilled()) { - return this.promise().value(); - } - return NULL; - }; +/***/ 3821: +/***/ ((module, exports, __nccwpck_require__) => { - Disposer.prototype.tryDispose = function (inspection) { - var resource = this.resource(); - var context = this._context; - if (context !== undefined) context._pushContext(); - var ret = - resource !== NULL ? this.doDispose(resource, inspection) : null; - if (context !== undefined) context._popContext(); - this._promise._unsetDisposable(); - this._data = null; - return ret; - }; +"use strict"; - Disposer.isDisposer = function (d) { - return ( - d != null && - typeof d.resource === "function" && - typeof d.tryDispose === "function" - ); - }; - function FunctionDisposer(fn, promise, context) { - this.constructor$(fn, promise, context); - } - inherits(FunctionDisposer, Disposer); +/** + * Dependencies + */ - FunctionDisposer.prototype.doDispose = function (resource, inspection) { - var fn = this.data(); - return fn.call(resource, resource, inspection); - }; +const slice = __nccwpck_require__(9889); +const assert = __nccwpck_require__(2357); +const util = __nccwpck_require__(1669); +const utils = __nccwpck_require__(7483); +const debug = __nccwpck_require__(7816)('mquery'); - function maybeUnwrapDisposer(value) { - if (Disposer.isDisposer(value)) { - this.resources[this.index]._setDisposable(value); - return value.promise(); - } - return value; - } +/* global Map */ - function ResourceList(length) { - this.length = length; - this.promise = null; - this[length - 1] = null; - } +/** + * Query constructor used for building queries. + * + * ####Example: + * + * var query = new Query({ name: 'mquery' }); + * query.setOptions({ collection: moduleCollection }) + * query.where('age').gte(21).exec(callback); + * + * @param {Object} [criteria] + * @param {Object} [options] + * @api public + */ - ResourceList.prototype._resultCancelled = function () { - var len = this.length; - for (var i = 0; i < len; ++i) { - var item = this[i]; - if (item instanceof Promise) { - item.cancel(); - } - } - }; +function Query(criteria, options) { + if (!(this instanceof Query)) + return new Query(criteria, options); - Promise.using = function () { - var len = arguments.length; - if (len < 2) - return apiRejection( - "you must pass at least 2 arguments to Promise.using" - ); - var fn = arguments[len - 1]; - if (typeof fn !== "function") { - return apiRejection( - "expecting a function but got " + util.classString(fn) - ); - } - var input; - var spreadArgs = true; - if (len === 2 && Array.isArray(arguments[0])) { - input = arguments[0]; - len = input.length; - spreadArgs = false; - } else { - input = arguments; - len--; - } - var resources = new ResourceList(len); - for (var i = 0; i < len; ++i) { - var resource = input[i]; - if (Disposer.isDisposer(resource)) { - var disposer = resource; - resource = resource.promise(); - resource._setDisposable(disposer); - } else { - var maybePromise = tryConvertToPromise(resource); - if (maybePromise instanceof Promise) { - resource = maybePromise._then( - maybeUnwrapDisposer, - null, - null, - { - resources: resources, - index: i, - }, - undefined - ); - } - } - resources[i] = resource; - } + const proto = this.constructor.prototype; - var reflectedResources = new Array(resources.length); - for (var i = 0; i < reflectedResources.length; ++i) { - reflectedResources[i] = Promise.resolve(resources[i]).reflect(); - } + this.op = proto.op || undefined; - var resultPromise = Promise.all(reflectedResources).then(function ( - inspections - ) { - for (var i = 0; i < inspections.length; ++i) { - var inspection = inspections[i]; - if (inspection.isRejected()) { - errorObj.e = inspection.error(); - return errorObj; - } else if (!inspection.isFulfilled()) { - resultPromise.cancel(); - return; - } - inspections[i] = inspection.value(); - } - promise._pushContext(); - - fn = tryCatch(fn); - var ret = spreadArgs - ? fn.apply(undefined, inspections) - : fn(inspections); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - "Promise.using", - promise - ); - return ret; - }); + this.options = Object.assign({}, proto.options); - var promise = resultPromise.lastly(function () { - var inspection = new Promise.PromiseInspection(resultPromise); - return dispose(resources, inspection); - }); - resources.promise = promise; - promise._setOnCancel(resources); - return promise; - }; + this._conditions = proto._conditions + ? utils.clone(proto._conditions) + : {}; - Promise.prototype._setDisposable = function (disposer) { - this._bitField = this._bitField | 131072; - this._disposer = disposer; - }; + this._fields = proto._fields + ? utils.clone(proto._fields) + : undefined; - Promise.prototype._isDisposable = function () { - return (this._bitField & 131072) > 0; - }; + this._update = proto._update + ? utils.clone(proto._update) + : undefined; - Promise.prototype._getDisposer = function () { - return this._disposer; - }; + this._path = proto._path || undefined; + this._distinct = proto._distinct || undefined; + this._collection = proto._collection || undefined; + this._traceFunction = proto._traceFunction || undefined; - Promise.prototype._unsetDisposable = function () { - this._bitField = this._bitField & ~131072; - this._disposer = undefined; - }; + if (options) { + this.setOptions(options); + } - Promise.prototype.disposer = function (fn) { - if (typeof fn === "function") { - return new FunctionDisposer(fn, this, createContext()); - } - throw new TypeError(); - }; - }; + if (criteria) { + if (criteria.find && criteria.remove && criteria.update) { + // quack quack! + this.collection(criteria); + } else { + this.find(criteria); + } + } +} - /***/ - }, +/** + * This is a parameter that the user can set which determines if mquery + * uses $within or $geoWithin for queries. It defaults to true which + * means $geoWithin will be used. If using MongoDB < 2.4 you should + * set this to false. + * + * @api public + * @property use$geoWithin + */ - /***/ 2122: /***/ function ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) { - "use strict"; - - var es5 = __nccwpck_require__(9432); - var canEvaluate = typeof navigator == "undefined"; - - var errorObj = { e: {} }; - var tryCatchTarget; - var globalObject = - typeof self !== "undefined" - ? self - : typeof window !== "undefined" - ? window - : typeof global !== "undefined" - ? global - : this !== undefined - ? this - : null; - - function tryCatcher() { - try { - var target = tryCatchTarget; - tryCatchTarget = null; - return target.apply(this, arguments); - } catch (e) { - errorObj.e = e; - return errorObj; - } - } - function tryCatch(fn) { - tryCatchTarget = fn; - return tryCatcher; - } +let $withinCmd = '$geoWithin'; +Object.defineProperty(Query, 'use$geoWithin', { + get: function() { return $withinCmd == '$geoWithin'; }, + set: function(v) { + if (true === v) { + // mongodb >= 2.4 + $withinCmd = '$geoWithin'; + } else { + $withinCmd = '$within'; + } + } +}); - var inherits = function (Child, Parent) { - var hasProp = {}.hasOwnProperty; +/** + * Converts this query to a constructor function with all arguments and options retained. + * + * ####Example + * + * // Create a query that will read documents with a "video" category from + * // `aCollection` on the primary node in the replica-set unless it is down, + * // in which case we'll read from a secondary node. + * var query = mquery({ category: 'video' }) + * query.setOptions({ collection: aCollection, read: 'primaryPreferred' }); + * + * // create a constructor based off these settings + * var Video = query.toConstructor(); + * + * // Video is now a subclass of mquery() and works the same way but with the + * // default query parameters and options set. + * + * // run a query with the previous settings but filter for movies with names + * // that start with "Life". + * Video().where({ name: /^Life/ }).exec(cb); + * + * @return {Query} new Query + * @api public + */ - function T() { - this.constructor = Child; - this.constructor$ = Parent; - for (var propertyName in Parent.prototype) { - if ( - hasProp.call(Parent.prototype, propertyName) && - propertyName.charAt(propertyName.length - 1) !== "$" - ) { - this[propertyName + "$"] = Parent.prototype[propertyName]; - } - } - } - T.prototype = Parent.prototype; - Child.prototype = new T(); - return Child.prototype; - }; +Query.prototype.toConstructor = function toConstructor() { + function CustomQuery(criteria, options) { + if (!(this instanceof CustomQuery)) + return new CustomQuery(criteria, options); + Query.call(this, criteria, options); + } - function isPrimitive(val) { - return ( - val == null || - val === true || - val === false || - typeof val === "string" || - typeof val === "number" - ); - } + utils.inherits(CustomQuery, Query); - function isObject(value) { - return ( - typeof value === "function" || - (typeof value === "object" && value !== null) - ); - } + // set inherited defaults + const p = CustomQuery.prototype; - function maybeWrapAsError(maybeError) { - if (!isPrimitive(maybeError)) return maybeError; + p.options = {}; + p.setOptions(this.options); - return new Error(safeToString(maybeError)); - } + p.op = this.op; + p._conditions = utils.clone(this._conditions); + p._fields = utils.clone(this._fields); + p._update = utils.clone(this._update); + p._path = this._path; + p._distinct = this._distinct; + p._collection = this._collection; + p._traceFunction = this._traceFunction; - function withAppended(target, appendee) { - var len = target.length; - var ret = new Array(len + 1); - var i; - for (i = 0; i < len; ++i) { - ret[i] = target[i]; - } - ret[i] = appendee; - return ret; - } + return CustomQuery; +}; - function getDataPropertyOrDefault(obj, key, defaultValue) { - if (es5.isES5) { - var desc = Object.getOwnPropertyDescriptor(obj, key); +/** + * Sets query options. + * + * ####Options: + * + * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) * + * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) * + * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) * + * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) * + * - [maxScan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) * + * - [maxTime](http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS) * + * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) * + * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) * + * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) * + * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) * + * - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) * + * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command) + * - collection the collection to query against + * + * _* denotes a query helper method is also available_ + * + * @param {Object} options + * @api public + */ - if (desc != null) { - return desc.get == null && desc.set == null - ? desc.value - : defaultValue; - } - } else { - return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; - } - } +Query.prototype.setOptions = function(options) { + if (!(options && utils.isObject(options))) + return this; + + // set arbitrary options + const methods = utils.keys(options); + let method; + + for (let i = 0; i < methods.length; ++i) { + method = methods[i]; + + // use methods if exist (safer option manipulation) + if ('function' == typeof this[method]) { + const args = utils.isArray(options[method]) + ? options[method] + : [options[method]]; + this[method].apply(this, args); + } else { + this.options[method] = options[method]; + } + } - function notEnumerableProp(obj, name, value) { - if (isPrimitive(obj)) return obj; - var descriptor = { - value: value, - configurable: true, - enumerable: false, - writable: true, - }; - es5.defineProperty(obj, name, descriptor); - return obj; - } + return this; +}; - function thrower(r) { - throw r; - } +/** + * Sets this Querys collection. + * + * @param {Collection} coll + * @return {Query} this + */ - var inheritedDataKeys = (function () { - var excludedPrototypes = [ - Array.prototype, - Object.prototype, - Function.prototype, - ]; +Query.prototype.collection = function collection(coll) { + this._collection = new Query.Collection(coll); - var isExcludedProto = function (val) { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (excludedPrototypes[i] === val) { - return true; - } - } - return false; - }; + return this; +}; - if (es5.isES5) { - var getKeys = Object.getOwnPropertyNames; - return function (obj) { - var ret = []; - var visitedKeys = Object.create(null); - while (obj != null && !isExcludedProto(obj)) { - var keys; - try { - keys = getKeys(obj); - } catch (e) { - return ret; - } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (visitedKeys[key]) continue; - visitedKeys[key] = true; - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null && desc.get == null && desc.set == null) { - ret.push(key); - } - } - obj = es5.getPrototypeOf(obj); - } - return ret; - }; - } else { - var hasProp = {}.hasOwnProperty; - return function (obj) { - if (isExcludedProto(obj)) return []; - var ret = []; - - /*jshint forin:false */ - enumeration: for (var key in obj) { - if (hasProp.call(obj, key)) { - ret.push(key); - } else { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (hasProp.call(excludedPrototypes[i], key)) { - continue enumeration; - } - } - ret.push(key); - } - } - return ret; - }; - } - })(); +/** + * Adds a collation to this op (MongoDB 3.4 and up) + * + * ####Example + * + * query.find().collation({ locale: "en_US", strength: 1 }) + * + * @param {Object} value + * @return {Query} this + * @see MongoDB docs https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation + * @api public + */ - var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; - function isClass(fn) { - try { - if (typeof fn === "function") { - var keys = es5.names(fn.prototype); - - var hasMethods = es5.isES5 && keys.length > 1; - var hasMethodsOtherThanConstructor = - keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); - var hasThisAssignmentAndStaticMethods = - thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; - - if ( - hasMethods || - hasMethodsOtherThanConstructor || - hasThisAssignmentAndStaticMethods - ) { - return true; - } - } - return false; - } catch (e) { - return false; - } - } +Query.prototype.collation = function(value) { + this.options.collation = value; + return this; +}; - function toFastProperties(obj) { - /*jshint -W027,-W055,-W031*/ - function FakeConstructor() {} - FakeConstructor.prototype = obj; - var l = 8; - while (l--) new FakeConstructor(); - return obj; - eval(obj); - } +/** + * Specifies a `$where` condition + * + * Use `$where` when you need to select documents using a JavaScript expression. + * + * ####Example + * + * query.$where('this.comments.length > 10 || this.name.length > 5') + * + * query.$where(function () { + * return this.comments.length > 10 || this.name.length > 5; + * }) + * + * @param {String|Function} js javascript string or function + * @return {Query} this + * @memberOf Query + * @method $where + * @api public + */ - var rident = /^[a-z$_][a-z$_0-9]*$/i; - function isIdentifier(str) { - return rident.test(str); - } +Query.prototype.$where = function(js) { + this._conditions.$where = js; + return this; +}; - function filledRange(count, prefix, suffix) { - var ret = new Array(count); - for (var i = 0; i < count; ++i) { - ret[i] = prefix + i + suffix; - } - return ret; - } +/** + * Specifies a `path` for use with chaining. + * + * ####Example + * + * // instead of writing: + * User.find({age: {$gte: 21, $lte: 65}}, callback); + * + * // we can instead write: + * User.where('age').gte(21).lte(65); + * + * // passing query conditions is permitted + * User.find().where({ name: 'vonderful' }) + * + * // chaining + * User + * .where('age').gte(21).lte(65) + * .where('name', /^vonderful/i) + * .where('friends').slice(10) + * .exec(callback) + * + * @param {String} [path] + * @param {Object} [val] + * @return {Query} this + * @api public + */ - function safeToString(obj) { - try { - return obj + ""; - } catch (e) { - return "[no string representation]"; - } - } +Query.prototype.where = function() { + if (!arguments.length) return this; + if (!this.op) this.op = 'find'; - function isError(obj) { - return ( - obj instanceof Error || - (obj !== null && - typeof obj === "object" && - typeof obj.message === "string" && - typeof obj.name === "string") - ); - } + const type = typeof arguments[0]; - function markAsOriginatingFromRejection(e) { - try { - notEnumerableProp(e, "isOperational", true); - } catch (ignore) {} - } + if ('string' == type) { + this._path = arguments[0]; - function originatesFromRejection(e) { - if (e == null) return false; - return ( - e instanceof Error["__BluebirdErrorTypes__"].OperationalError || - e["isOperational"] === true - ); - } + if (2 === arguments.length) { + this._conditions[this._path] = arguments[1]; + } - function canAttachTrace(obj) { - return isError(obj) && es5.propertyIsWritable(obj, "stack"); - } + return this; + } - var ensureErrorObject = (function () { - if (!("stack" in new Error())) { - return function (value) { - if (canAttachTrace(value)) return value; - try { - throw new Error(safeToString(value)); - } catch (err) { - return err; - } - }; - } else { - return function (value) { - if (canAttachTrace(value)) return value; - return new Error(safeToString(value)); - }; - } - })(); + if ('object' == type && !Array.isArray(arguments[0])) { + return this.merge(arguments[0]); + } - function classString(obj) { - return {}.toString.call(obj); - } + throw new TypeError('path must be a string or object'); +}; - function copyDescriptors(from, to, filter) { - var keys = es5.names(from); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (filter(key)) { - try { - es5.defineProperty(to, key, es5.getDescriptor(from, key)); - } catch (ignore) {} - } - } - } +/** + * Specifies the complementary comparison value for paths specified with `where()` + * + * ####Example + * + * User.where('age').equals(49); + * + * // is the same as + * + * User.where('age', 49); + * + * @param {Object} val + * @return {Query} this + * @api public + */ - var asArray = function (v) { - if (es5.isArray(v)) { - return v; - } - return null; - }; +Query.prototype.equals = function equals(val) { + this._ensurePath('equals'); + const path = this._path; + this._conditions[path] = val; + return this; +}; - if (typeof Symbol !== "undefined" && Symbol.iterator) { - var ArrayFrom = - typeof Array.from === "function" - ? function (v) { - return Array.from(v); - } - : function (v) { - var ret = []; - var it = v[Symbol.iterator](); - var itResult; - while (!(itResult = it.next()).done) { - ret.push(itResult.value); - } - return ret; - }; +/** + * Specifies the complementary comparison value for paths specified with `where()` + * This is alias of `equals` + * + * ####Example + * + * User.where('age').eq(49); + * + * // is the same as + * + * User.shere('age').equals(49); + * + * // is the same as + * + * User.where('age', 49); + * + * @param {Object} val + * @return {Query} this + * @api public + */ - asArray = function (v) { - if (es5.isArray(v)) { - return v; - } else if (v != null && typeof v[Symbol.iterator] === "function") { - return ArrayFrom(v); - } - return null; - }; - } +Query.prototype.eq = function eq(val) { + this._ensurePath('eq'); + const path = this._path; + this._conditions[path] = val; + return this; +}; - var isNode = - typeof process !== "undefined" && - classString(process).toLowerCase() === "[object process]"; +/** + * Specifies arguments for an `$or` condition. + * + * ####Example + * + * query.or([{ color: 'red' }, { status: 'emergency' }]) + * + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ - var hasEnvVariables = - typeof process !== "undefined" && typeof process.env !== "undefined"; +Query.prototype.or = function or(array) { + const or = this._conditions.$or || (this._conditions.$or = []); + if (!utils.isArray(array)) array = [array]; + or.push.apply(or, array); + return this; +}; - function env(key) { - return hasEnvVariables ? process.env[key] : undefined; - } +/** + * Specifies arguments for a `$nor` condition. + * + * ####Example + * + * query.nor([{ color: 'green' }, { status: 'ok' }]) + * + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ - function getNativePromise() { - if (typeof Promise === "function") { - try { - var promise = new Promise(function () {}); - if ({}.toString.call(promise) === "[object Promise]") { - return Promise; - } - } catch (e) {} - } - } - - function domainBind(self, cb) { - return self.bind(cb); - } - - var ret = { - isClass: isClass, - isIdentifier: isIdentifier, - inheritedDataKeys: inheritedDataKeys, - getDataPropertyOrDefault: getDataPropertyOrDefault, - thrower: thrower, - isArray: es5.isArray, - asArray: asArray, - notEnumerableProp: notEnumerableProp, - isPrimitive: isPrimitive, - isObject: isObject, - isError: isError, - canEvaluate: canEvaluate, - errorObj: errorObj, - tryCatch: tryCatch, - inherits: inherits, - withAppended: withAppended, - maybeWrapAsError: maybeWrapAsError, - toFastProperties: toFastProperties, - filledRange: filledRange, - toString: safeToString, - canAttachTrace: canAttachTrace, - ensureErrorObject: ensureErrorObject, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - classString: classString, - copyDescriptors: copyDescriptors, - hasDevTools: - typeof chrome !== "undefined" && - chrome && - typeof chrome.loadTimes === "function", - isNode: isNode, - hasEnvVariables: hasEnvVariables, - env: env, - global: globalObject, - getNativePromise: getNativePromise, - domainBind: domainBind, - }; - ret.isRecentNode = - ret.isNode && - (function () { - var version = process.versions.node.split(".").map(Number); - return (version[0] === 0 && version[1] > 10) || version[0] > 0; - })(); +Query.prototype.nor = function nor(array) { + const nor = this._conditions.$nor || (this._conditions.$nor = []); + if (!utils.isArray(array)) array = [array]; + nor.push.apply(nor, array); + return this; +}; - if (ret.isNode) ret.toFastProperties(process); +/** + * Specifies arguments for a `$and` condition. + * + * ####Example + * + * query.and([{ color: 'green' }, { status: 'ok' }]) + * + * @see $and http://docs.mongodb.org/manual/reference/operator/and/ + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ - try { - throw new Error(); - } catch (e) { - ret.lastLineError = e; - } - module.exports = ret; +Query.prototype.and = function and(array) { + const and = this._conditions.$and || (this._conditions.$and = []); + if (!Array.isArray(array)) array = [array]; + and.push.apply(and, array); + return this; +}; - /***/ - }, +/** + * Specifies a $gt query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * ####Example + * + * Thing.find().where('age').gt(21) + * + * // or + * Thing.find().gt('age', 21) + * + * @method gt + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ - /***/ 3081: /***/ (module, exports, __nccwpck_require__) => { - /** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - - exports = module.exports = __nccwpck_require__(201); - exports.log = log; - exports.formatArgs = formatArgs; - exports.save = save; - exports.load = load; - exports.useColors = useColors; - exports.storage = - "undefined" != typeof chrome && "undefined" != typeof chrome.storage - ? chrome.storage.local - : localstorage(); - - /** - * Colors. - */ - - exports.colors = [ - "#0000CC", - "#0000FF", - "#0033CC", - "#0033FF", - "#0066CC", - "#0066FF", - "#0099CC", - "#0099FF", - "#00CC00", - "#00CC33", - "#00CC66", - "#00CC99", - "#00CCCC", - "#00CCFF", - "#3300CC", - "#3300FF", - "#3333CC", - "#3333FF", - "#3366CC", - "#3366FF", - "#3399CC", - "#3399FF", - "#33CC00", - "#33CC33", - "#33CC66", - "#33CC99", - "#33CCCC", - "#33CCFF", - "#6600CC", - "#6600FF", - "#6633CC", - "#6633FF", - "#66CC00", - "#66CC33", - "#9900CC", - "#9900FF", - "#9933CC", - "#9933FF", - "#99CC00", - "#99CC33", - "#CC0000", - "#CC0033", - "#CC0066", - "#CC0099", - "#CC00CC", - "#CC00FF", - "#CC3300", - "#CC3333", - "#CC3366", - "#CC3399", - "#CC33CC", - "#CC33FF", - "#CC6600", - "#CC6633", - "#CC9900", - "#CC9933", - "#CCCC00", - "#CCCC33", - "#FF0000", - "#FF0033", - "#FF0066", - "#FF0099", - "#FF00CC", - "#FF00FF", - "#FF3300", - "#FF3333", - "#FF3366", - "#FF3399", - "#FF33CC", - "#FF33FF", - "#FF6600", - "#FF6633", - "#FF9900", - "#FF9933", - "#FFCC00", - "#FFCC33", - ]; +/** + * Specifies a $gte query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method gte + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ - /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - - function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if ( - typeof window !== "undefined" && - window.process && - window.process.type === "renderer" - ) { - return true; - } +/** + * Specifies a $lt query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lt + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ - // Internet Explorer and Edge do not support colors. - if ( - typeof navigator !== "undefined" && - navigator.userAgent && - navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/) - ) { - return false; - } +/** + * Specifies a $lte query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lte + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return ( - (typeof document !== "undefined" && - document.documentElement && - document.documentElement.style && - document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== "undefined" && - window.console && - (window.console.firebug || - (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== "undefined" && - navigator.userAgent && - navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && - parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== "undefined" && - navigator.userAgent && - navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)) - ); - } +/** + * Specifies a $ne query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method ne + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ - /** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ +/** + * Specifies an $in query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method in + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ - exports.formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (err) { - return "[UnexpectedJSONParseError]: " + err.message; - } - }; +/** + * Specifies an $nin query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method nin + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ - /** - * Colorize log arguments if enabled. - * - * @api public - */ +/** + * Specifies an $all query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method all + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ - function formatArgs(args) { - var useColors = this.useColors; +/** + * Specifies a $size query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method size + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ - args[0] = - (useColors ? "%c" : "") + - this.namespace + - (useColors ? " %c" : " ") + - args[0] + - (useColors ? "%c " : " ") + - "+" + - exports.humanize(this.diff); +/** + * Specifies a $regex query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method regex + * @memberOf Query + * @param {String} [path] + * @param {String|RegExp} val + * @api public + */ - if (!useColors) return; +/** + * Specifies a $maxDistance query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method maxDistance + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ - var c = "color: " + this.color; - args.splice(1, 0, c, "color: inherit"); +/*! + * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance + * + * Thing.where('type').nin(array) + */ - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function (match) { - if ("%%" === match) return; - index++; - if ("%c" === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); +'gt gte lt lte ne in nin all regex size maxDistance minDistance'.split(' ').forEach(function($conditional) { + Query.prototype[$conditional] = function() { + let path, val; + + if (1 === arguments.length) { + this._ensurePath($conditional); + val = arguments[0]; + path = this._path; + } else { + val = arguments[1]; + path = arguments[0]; + } - args.splice(lastC, 0, c); - } + const conds = this._conditions[path] === null || typeof this._conditions[path] === 'object' ? + this._conditions[path] : + (this._conditions[path] = {}); + conds['$' + $conditional] = val; + return this; + }; +}); - /** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ +/** + * Specifies a `$mod` condition + * + * @param {String} [path] + * @param {Number} val + * @return {Query} this + * @api public + */ - function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return ( - "object" === typeof console && - console.log && - Function.prototype.apply.call(console.log, console, arguments) - ); - } +Query.prototype.mod = function() { + let val, path; + + if (1 === arguments.length) { + this._ensurePath('mod'); + val = arguments[0]; + path = this._path; + } else if (2 === arguments.length && !utils.isArray(arguments[1])) { + this._ensurePath('mod'); + val = slice(arguments); + path = this._path; + } else if (3 === arguments.length) { + val = slice(arguments, 1); + path = arguments[0]; + } else { + val = arguments[1]; + path = arguments[0]; + } - /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + const conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$mod = val; + return this; +}; - function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem("debug"); - } else { - exports.storage.debug = namespaces; - } - } catch (e) {} - } +/** + * Specifies an `$exists` condition + * + * ####Example + * + * // { name: { $exists: true }} + * Thing.where('name').exists() + * Thing.where('name').exists(true) + * Thing.find().exists('name') + * + * // { name: { $exists: false }} + * Thing.where('name').exists(false); + * Thing.find().exists('name', false); + * + * @param {String} [path] + * @param {Number} val + * @return {Query} this + * @api public + */ - /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ +Query.prototype.exists = function() { + let path, val; + + if (0 === arguments.length) { + this._ensurePath('exists'); + path = this._path; + val = true; + } else if (1 === arguments.length) { + if ('boolean' === typeof arguments[0]) { + this._ensurePath('exists'); + path = this._path; + val = arguments[0]; + } else { + path = arguments[0]; + val = true; + } + } else if (2 === arguments.length) { + path = arguments[0]; + val = arguments[1]; + } - function load() { - var r; - try { - r = exports.storage.debug; - } catch (e) {} + const conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$exists = val; + return this; +}; - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== "undefined" && "env" in process) { - r = process.env.DEBUG; - } +/** + * Specifies an `$elemMatch` condition + * + * ####Example + * + * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) + * + * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) + * + * query.elemMatch('comment', function (elem) { + * elem.where('author').equals('autobot'); + * elem.where('votes').gte(5); + * }) + * + * query.where('comment').elemMatch(function (elem) { + * elem.where({ author: 'autobot' }); + * elem.where('votes').gte(5); + * }) + * + * @param {String|Object|Function} path + * @param {Object|Function} criteria + * @return {Query} this + * @api public + */ - return r; - } +Query.prototype.elemMatch = function() { + if (null == arguments[0]) + throw new TypeError('Invalid argument'); + + let fn, path, criteria; + + if ('function' === typeof arguments[0]) { + this._ensurePath('elemMatch'); + path = this._path; + fn = arguments[0]; + } else if (utils.isObject(arguments[0])) { + this._ensurePath('elemMatch'); + path = this._path; + criteria = arguments[0]; + } else if ('function' === typeof arguments[1]) { + path = arguments[0]; + fn = arguments[1]; + } else if (arguments[1] && utils.isObject(arguments[1])) { + path = arguments[0]; + criteria = arguments[1]; + } else { + throw new TypeError('Invalid argument'); + } - /** - * Enable namespaces listed in `localStorage.debug` initially. - */ + if (fn) { + criteria = new Query; + fn(criteria); + criteria = criteria._conditions; + } - exports.enable(load()); + const conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$elemMatch = criteria; + return this; +}; - /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ +// Spatial queries - function localstorage() { - try { - return window.localStorage; - } catch (e) {} - } +/** + * Sugar for geo-spatial queries. + * + * ####Example + * + * query.within().box() + * query.within().circle() + * query.within().geometry() + * + * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); + * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); + * query.where('loc').within({ polygon: [[],[],[],[]] }); + * + * query.where('loc').within([], [], []) // polygon + * query.where('loc').within([], []) // box + * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry + * + * ####NOTE: + * + * Must be used after `where()`. + * + * @memberOf Query + * @return {Query} this + * @api public + */ - /***/ - }, +Query.prototype.within = function within() { + // opinionated, must be used after where + this._ensurePath('within'); + this._geoComparison = $withinCmd; - /***/ 201: /***/ (module, exports, __nccwpck_require__) => { - /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ - - exports = - module.exports = - createDebug.debug = - createDebug["default"] = - createDebug; - exports.coerce = coerce; - exports.disable = disable; - exports.enable = enable; - exports.enabled = enabled; - exports.humanize = __nccwpck_require__(8695); - - /** - * Active `debug` instances. - */ - exports.instances = []; - - /** - * The currently active debug mode names, and names to skip. - */ - - exports.names = []; - exports.skips = []; - - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - - exports.formatters = {}; - - /** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ - - function selectColor(namespace) { - var hash = 0, - i; - - for (i in namespace) { - hash = (hash << 5) - hash + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return exports.colors[Math.abs(hash) % exports.colors.length]; - } - - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - - function createDebug(namespace) { - var prevTime; - - function debug() { - // disabled? - if (!debug.enabled) return; - - var self = debug; - - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } + if (0 === arguments.length) { + return this; + } - args[0] = exports.coerce(args[0]); + if (2 === arguments.length) { + return this.box.apply(this, arguments); + } else if (2 < arguments.length) { + return this.polygon.apply(this, arguments); + } - if ("string" !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift("%O"); - } + const area = arguments[0]; - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === "%%") return match; - index++; - var formatter = exports.formatters[format]; - if ("function" === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + if (!area) + throw new TypeError('Invalid argument'); - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); + if (area.center) + return this.circle(area); - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } + if (area.box) + return this.box.apply(this, area.box); - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - debug.destroy = destroy; + if (area.polygon) + return this.polygon.apply(this, area.polygon); - // env-specific initialization logic for debug instances - if ("function" === typeof exports.init) { - exports.init(debug); - } + if (area.type && area.coordinates) + return this.geometry(area); - exports.instances.push(debug); + throw new TypeError('Invalid argument'); +}; - return debug; - } +/** + * Specifies a $box condition + * + * ####Example + * + * var lowerLeft = [40.73083, -73.99756] + * var upperRight= [40.741404, -73.988135] + * + * query.where('loc').within().box(lowerLeft, upperRight) + * query.box('loc', lowerLeft, upperRight ) + * + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @see Query#within #query_Query-within + * @param {String} path + * @param {Object} val + * @return {Query} this + * @api public + */ - function destroy() { - var index = exports.instances.indexOf(this); - if (index !== -1) { - exports.instances.splice(index, 1); - return true; - } else { - return false; - } - } +Query.prototype.box = function() { + let path, box; + + if (3 === arguments.length) { + // box('loc', [], []) + path = arguments[0]; + box = [arguments[1], arguments[2]]; + } else if (2 === arguments.length) { + // box([], []) + this._ensurePath('box'); + path = this._path; + box = [arguments[0], arguments[1]]; + } else { + throw new TypeError('Invalid argument'); + } - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ + const conds = this._conditions[path] || (this._conditions[path] = {}); + conds[this._geoComparison || $withinCmd] = { $box: box }; + return this; +}; - function enable(namespaces) { - exports.save(namespaces); +/** + * Specifies a $polygon condition + * + * ####Example + * + * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) + * query.polygon('loc', [10,20], [13, 25], [7,15]) + * + * @param {String|Array} [path] + * @param {Array|Object} [val] + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ - exports.names = []; - exports.skips = []; +Query.prototype.polygon = function() { + let val, path; + + if ('string' == typeof arguments[0]) { + // polygon('loc', [],[],[]) + path = arguments[0]; + val = slice(arguments, 1); + } else { + // polygon([],[],[]) + this._ensurePath('polygon'); + path = this._path; + val = slice(arguments); + } - var i; - var split = (typeof namespaces === "string" ? namespaces : "").split( - /[\s,]+/ - ); - var len = split.length; + const conds = this._conditions[path] || (this._conditions[path] = {}); + conds[this._geoComparison || $withinCmd] = { $polygon: val }; + return this; +}; - for (i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, ".*?"); - if (namespaces[0] === "-") { - exports.skips.push(new RegExp("^" + namespaces.substr(1) + "$")); - } else { - exports.names.push(new RegExp("^" + namespaces + "$")); - } - } +/** + * Specifies a $center or $centerSphere condition. + * + * ####Example + * + * var area = { center: [50, 50], radius: 10, unique: true } + * query.where('loc').within().circle(area) + * query.center('loc', area); + * + * // for spherical calculations + * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } + * query.where('loc').within().circle(area) + * query.center('loc', area); + * + * @param {String} [path] + * @param {Object} area + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ - for (i = 0; i < exports.instances.length; i++) { - var instance = exports.instances[i]; - instance.enabled = exports.enabled(instance.namespace); - } - } +Query.prototype.circle = function() { + let path, val; + + if (1 === arguments.length) { + this._ensurePath('circle'); + path = this._path; + val = arguments[0]; + } else if (2 === arguments.length) { + path = arguments[0]; + val = arguments[1]; + } else { + throw new TypeError('Invalid argument'); + } - /** - * Disable debug output. - * - * @api public - */ + if (!('radius' in val && val.center)) + throw new Error('center and radius are required'); - function disable() { - exports.enable(""); - } + const conds = this._conditions[path] || (this._conditions[path] = {}); - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ + const type = val.spherical + ? '$centerSphere' + : '$center'; - function enabled(name) { - if (name[name.length - 1] === "*") { - return true; - } - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; - } + const wKey = this._geoComparison || $withinCmd; + conds[wKey] = {}; + conds[wKey][type] = [val.center, val.radius]; - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ + if ('unique' in val) + conds[wKey].$uniqueDocs = !!val.unique; - function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; - } + return this; +}; - /***/ - }, +/** + * Specifies a `$near` or `$nearSphere` condition + * + * These operators return documents sorted by distance. + * + * ####Example + * + * query.where('loc').near({ center: [10, 10] }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); + * query.near('loc', { center: [10, 10], maxDistance: 5 }); + * query.near({ center: { type: 'Point', coordinates: [..] }}) + * query.near().geometry({ type: 'Point', coordinates: [..] }) + * + * @param {String} [path] + * @param {Object} val + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ - /***/ 5831: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - /** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ - - if (typeof process === "undefined" || process.type === "renderer") { - module.exports = __nccwpck_require__(3081); - } else { - module.exports = __nccwpck_require__(7879); - } +Query.prototype.near = function near() { + let path, val; + + this._geoComparison = '$near'; + + if (0 === arguments.length) { + return this; + } else if (1 === arguments.length) { + this._ensurePath('near'); + path = this._path; + val = arguments[0]; + } else if (2 === arguments.length) { + path = arguments[0]; + val = arguments[1]; + } else { + throw new TypeError('Invalid argument'); + } - /***/ - }, + if (!val.center) { + throw new Error('center is required'); + } - /***/ 7879: /***/ (module, exports, __nccwpck_require__) => { - /** - * Module dependencies. - */ + const conds = this._conditions[path] || (this._conditions[path] = {}); - var tty = __nccwpck_require__(3867); - var util = __nccwpck_require__(1669); + const type = val.spherical + ? '$nearSphere' + : '$near'; - /** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + // center could be a GeoJSON object or an Array + if (Array.isArray(val.center)) { + conds[type] = val.center; - exports = module.exports = __nccwpck_require__(201); - exports.init = init; - exports.log = log; - exports.formatArgs = formatArgs; - exports.save = save; - exports.load = load; - exports.useColors = useColors; + const radius = 'maxDistance' in val + ? val.maxDistance + : null; - /** - * Colors. - */ + if (null != radius) { + conds.$maxDistance = radius; + } + if (null != val.minDistance) { + conds.$minDistance = val.minDistance; + } + } else { + // GeoJSON? + if (val.center.type != 'Point' || !Array.isArray(val.center.coordinates)) { + throw new Error(util.format('Invalid GeoJSON specified for %s', type)); + } + conds[type] = { $geometry: val.center }; - exports.colors = [6, 2, 3, 4, 5, 1]; + // MongoDB 2.6 insists on maxDistance being in $near / $nearSphere + if ('maxDistance' in val) { + conds[type]['$maxDistance'] = val.maxDistance; + } + if ('minDistance' in val) { + conds[type]['$minDistance'] = val.minDistance; + } + } - try { - var supportsColor = __nccwpck_require__(9318); - if (supportsColor && supportsColor.level >= 2) { - exports.colors = [ - 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, - 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, - 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, - 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, - 214, 215, 220, 221, - ]; - } - } catch (err) { - // swallow - we only care if `supports-color` is available; it doesn't have to be. - } + return this; +}; - /** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ +/** + * Declares an intersects query for `geometry()`. + * + * ####Example + * + * query.where('path').intersects().geometry({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * query.where('path').intersects({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * @param {Object} [arg] + * @return {Query} this + * @api public + */ - exports.inspectOpts = Object.keys(process.env) - .filter(function (key) { - return /^debug_/i.test(key); - }) - .reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { - return k.toUpperCase(); - }); +Query.prototype.intersects = function intersects() { + // opinionated, must be used after where + this._ensurePath('intersects'); - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === "null") val = null; - else val = Number(val); - - obj[prop] = val; - return obj; - }, {}); - - /** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - - function useColors() { - return "colors" in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(process.stderr.fd); - } - - /** - * Map %o to `util.inspect()`, all on a single line. - */ - - exports.formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util - .inspect(v, this.inspectOpts) - .split("\n") - .map(function (str) { - return str.trim(); - }) - .join(" "); - }; + this._geoComparison = '$geoIntersects'; - /** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ + if (0 === arguments.length) { + return this; + } - exports.formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); - }; + const area = arguments[0]; - /** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ + if (null != area && area.type && area.coordinates) + return this.geometry(area); - function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; + throw new TypeError('Invalid argument'); +}; - if (useColors) { - var c = this.color; - var colorCode = "\u001b[3" + (c < 8 ? c : "8;5;" + c); - var prefix = " " + colorCode + ";1m" + name + " " + "\u001b[0m"; +/** + * Specifies a `$geometry` condition + * + * ####Example + * + * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] + * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) + * + * // or + * var polyB = [[ 0, 0 ], [ 1, 1 ]] + * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) + * + * // or + * var polyC = [ 0, 0 ] + * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) + * + * // or + * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) + * + * ####NOTE: + * + * `geometry()` **must** come after either `intersects()` or `within()`. + * + * The `object` argument must contain `type` and `coordinates` properties. + * - type {String} + * - coordinates {Array} + * + * The most recent path passed to `where()` is used. + * + * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. + * @return {Query} this + * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @api public + */ - args[0] = prefix + args[0].split("\n").join("\n" + prefix); - args.push( - colorCode + "m+" + exports.humanize(this.diff) + "\u001b[0m" - ); - } else { - args[0] = getDate() + name + " " + args[0]; - } - } +Query.prototype.geometry = function geometry() { + if (!('$within' == this._geoComparison || + '$geoWithin' == this._geoComparison || + '$near' == this._geoComparison || + '$geoIntersects' == this._geoComparison)) { + throw new Error('geometry() must come after `within()`, `intersects()`, or `near()'); + } - function getDate() { - if (exports.inspectOpts.hideDate) { - return ""; - } else { - return new Date().toISOString() + " "; - } - } + let val, path; - /** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ + if (1 === arguments.length) { + this._ensurePath('geometry'); + path = this._path; + val = arguments[0]; + } else { + throw new TypeError('Invalid argument'); + } - function log() { - return process.stderr.write(util.format.apply(util, arguments) + "\n"); - } + if (!(val.type && Array.isArray(val.coordinates))) { + throw new TypeError('Invalid argument'); + } - /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + const conds = this._conditions[path] || (this._conditions[path] = {}); + conds[this._geoComparison] = { $geometry: val }; - function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } - } + return this; +}; - /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ +// end spatial - function load() { - return process.env.DEBUG; - } +/** + * Specifies which document fields to include or exclude + * + * ####String syntax + * + * When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. + * + * ####Example + * + * // include a and b, exclude c + * query.select('a b -c'); + * + * // or you may use object notation, useful when + * // you have keys already prefixed with a "-" + * query.select({a: 1, b: 1, c: 0}); + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object|String} arg + * @return {Query} this + * @see SchemaType + * @api public + */ - /** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ +Query.prototype.select = function select() { + let arg = arguments[0]; + if (!arg) return this; - function init(debug) { - debug.inspectOpts = {}; + if (arguments.length !== 1) { + throw new Error('Invalid select: select only takes 1 argument'); + } - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } - } + this._validate('select'); - /** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ + const fields = this._fields || (this._fields = {}); + const type = typeof arg; + let i, len; - exports.enable(load()); + if (('string' == type || utils.isArgumentsObject(arg)) && + 'number' == typeof arg.length || Array.isArray(arg)) { + if ('string' == type) + arg = arg.split(/\s+/); - /***/ - }, + for (i = 0, len = arg.length; i < len; ++i) { + let field = arg[i]; + if (!field) continue; + const include = '-' == field[0] ? 0 : 1; + if (include === 0) field = field.substring(1); + fields[field] = include; + } - /***/ 8695: /***/ (module) => { - /** - * Helpers. - */ - - var s = 1000; - var m = s * 60; - var h = m * 60; - var d = h * 24; - var y = d * 365.25; - - /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - - module.exports = function (val, options) { - options = options || {}; - var type = typeof val; - if (type === "string" && val.length > 0) { - return parse(val); - } else if (type === "number" && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - "val is not a non-empty string or a valid number. val=" + - JSON.stringify(val) - ); - }; + return this; + } - /** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - - function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = - /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || "ms").toLowerCase(); - switch (type) { - case "years": - case "year": - case "yrs": - case "yr": - case "y": - return n * y; - case "days": - case "day": - case "d": - return n * d; - case "hours": - case "hour": - case "hrs": - case "hr": - case "h": - return n * h; - case "minutes": - case "minute": - case "mins": - case "min": - case "m": - return n * m; - case "seconds": - case "second": - case "secs": - case "sec": - case "s": - return n * s; - case "milliseconds": - case "millisecond": - case "msecs": - case "msec": - case "ms": - return n; - default: - return undefined; - } - } + if (utils.isObject(arg)) { + const keys = utils.keys(arg); + for (i = 0; i < keys.length; ++i) { + fields[keys[i]] = arg[keys[i]]; + } + return this; + } - /** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + throw new TypeError('Invalid select() argument. Must be string or object.'); +}; - function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + "d"; - } - if (ms >= h) { - return Math.round(ms / h) + "h"; - } - if (ms >= m) { - return Math.round(ms / m) + "m"; - } - if (ms >= s) { - return Math.round(ms / s) + "s"; - } - return ms + "ms"; - } +/** + * Specifies a $slice condition for a `path` + * + * ####Example + * + * query.slice('comments', 5) + * query.slice('comments', -5) + * query.slice('comments', [10, 5]) + * query.where('comments').slice(5) + * query.where('comments').slice([-10, 5]) + * + * @param {String} [path] + * @param {Number} val number/range of elements to slice + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements + * @api public + */ - /** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +Query.prototype.slice = function() { + if (0 === arguments.length) + return this; - function fmtLong(ms) { - return ( - plural(ms, d, "day") || - plural(ms, h, "hour") || - plural(ms, m, "minute") || - plural(ms, s, "second") || - ms + " ms" - ); - } + this._validate('slice'); - /** - * Pluralization helper. - */ + let path, val; - function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + " " + name; - } - return Math.ceil(ms / n) + " " + name + "s"; + if (1 === arguments.length) { + const arg = arguments[0]; + if (typeof arg === 'object' && !Array.isArray(arg)) { + const keys = Object.keys(arg); + const numKeys = keys.length; + for (let i = 0; i < numKeys; ++i) { + this.slice(keys[i], arg[keys[i]]); } + return this; + } + this._ensurePath('slice'); + path = this._path; + val = arguments[0]; + } else if (2 === arguments.length) { + if ('number' === typeof arguments[0]) { + this._ensurePath('slice'); + path = this._path; + val = slice(arguments); + } else { + path = arguments[0]; + val = arguments[1]; + } + } else if (3 === arguments.length) { + path = arguments[0]; + val = slice(arguments, 1); + } - /***/ - }, - - /***/ 1865: /***/ (module, exports, __nccwpck_require__) => { - /* eslint-disable node/no-deprecated-api */ - var buffer = __nccwpck_require__(4293); - var Buffer = buffer.Buffer; + const myFields = this._fields || (this._fields = {}); + myFields[path] = { $slice: val }; + return this; +}; - // 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; - } +/** + * Sets the sort order + * + * If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1. + * + * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. + * + * ####Example + * + * // these are equivalent + * query.sort({ field: 'asc', test: -1 }); + * query.sort('field -test'); + * query.sort([['field', 1], ['test', -1]]); + * + * ####Note + * + * - The array syntax `.sort([['field', 1], ['test', -1]])` can only be used with [mongodb driver >= 2.0.46](https://github.com/mongodb/node-mongodb-native/blob/2.1/HISTORY.md#2046-2015-10-15). + * - Cannot be used with `distinct()` + * + * @param {Object|String|Array} arg + * @return {Query} this + * @api public + */ - function SafeBuffer(arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length); - } +Query.prototype.sort = function(arg) { + if (!arg) return this; + let i, len, field; - // Copy static methods from Buffer - copyProps(Buffer, SafeBuffer); + this._validate('sort'); - SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === "number") { - throw new TypeError("Argument must not be a number"); - } - return Buffer(arg, encodingOrOffset, length); - }; + const type = typeof arg; - 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; - }; + // .sort([['field', 1], ['test', -1]]) + if (Array.isArray(arg)) { + len = arg.length; + for (i = 0; i < arg.length; ++i) { + if (!Array.isArray(arg[i])) { + throw new Error('Invalid sort() argument, must be array of arrays'); + } + _pushArr(this.options, arg[i][0], arg[i][1]); + } + return this; + } - SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - return Buffer(size); - }; + // .sort('field -test') + if (1 === arguments.length && 'string' == type) { + arg = arg.split(/\s+/); + len = arg.length; + for (i = 0; i < len; ++i) { + field = arg[i]; + if (!field) continue; + const ascend = '-' == field[0] ? -1 : 1; + if (ascend === -1) field = field.substring(1); + push(this.options, field, ascend); + } - SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - return buffer.SlowBuffer(size); - }; + return this; + } - /***/ - }, + // .sort({ field: 1, test: -1 }) + if (utils.isObject(arg)) { + const keys = utils.keys(arg); + for (i = 0; i < keys.length; ++i) { + field = keys[i]; + push(this.options, field, arg[field]); + } - /***/ 900: /***/ (module) => { - /** - * Helpers. - */ - - var s = 1000; - var m = s * 60; - var h = m * 60; - var d = h * 24; - var w = d * 7; - var y = d * 365.25; - - /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - - module.exports = function (val, options) { - options = options || {}; - var type = typeof val; - if (type === "string" && val.length > 0) { - return parse(val); - } else if (type === "number" && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - "val is not a non-empty string or a valid number. val=" + - JSON.stringify(val) - ); - }; + return this; + } - /** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - - function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = - /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || "ms").toLowerCase(); - switch (type) { - case "years": - case "year": - case "yrs": - case "yr": - case "y": - return n * y; - case "weeks": - case "week": - case "w": - return n * w; - case "days": - case "day": - case "d": - return n * d; - case "hours": - case "hour": - case "hrs": - case "hr": - case "h": - return n * h; - case "minutes": - case "minute": - case "mins": - case "min": - case "m": - return n * m; - case "seconds": - case "second": - case "secs": - case "sec": - case "s": - return n * s; - case "milliseconds": - case "millisecond": - case "msecs": - case "msec": - case "ms": - return n; - default: - return undefined; - } - } + if (typeof Map !== 'undefined' && arg instanceof Map) { + _pushMap(this.options, arg); + return this; + } + throw new TypeError('Invalid sort() argument. Must be a string, object, or array.'); +}; - /** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +/*! + * @ignore + */ - function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + "d"; - } - if (msAbs >= h) { - return Math.round(ms / h) + "h"; - } - if (msAbs >= m) { - return Math.round(ms / m) + "m"; - } - if (msAbs >= s) { - return Math.round(ms / s) + "s"; - } - return ms + "ms"; - } +const _validSortValue = { + 1: 1, + '-1': -1, + asc: 1, + ascending: 1, + desc: -1, + descending: -1 +}; + +function push(opts, field, value) { + if (Array.isArray(opts.sort)) { + throw new TypeError('Can\'t mix sort syntaxes. Use either array or object:' + + '\n- `.sort([[\'field\', 1], [\'test\', -1]])`' + + '\n- `.sort({ field: 1, test: -1 })`'); + } - /** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + let s; + if (value && value.$meta) { + s = opts.sort || (opts.sort = {}); + s[field] = { $meta: value.$meta }; + return; + } - function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, "day"); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, "hour"); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, "minute"); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, "second"); - } - return ms + " ms"; - } + s = opts.sort || (opts.sort = {}); + let val = String(value || 1).toLowerCase(); + val = _validSortValue[val]; + if (!val) throw new TypeError('Invalid sort value: { ' + field + ': ' + value + ' }'); - /** - * Pluralization helper. - */ + s[field] = val; +} - function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); - } +function _pushArr(opts, field, value) { + opts.sort = opts.sort || []; + if (!Array.isArray(opts.sort)) { + throw new TypeError('Can\'t mix sort syntaxes. Use either array or object:' + + '\n- `.sort([[\'field\', 1], [\'test\', -1]])`' + + '\n- `.sort({ field: 1, test: -1 })`'); + } - /***/ - }, + let val = String(value || 1).toLowerCase(); + val = _validSortValue[val]; + if (!val) throw new TypeError('Invalid sort value: [ ' + field + ', ' + value + ' ]'); - /***/ 9341: /***/ function ( - __unused_webpack_module, - exports, - __nccwpck_require__ - ) { - "use strict"; - - var __assign = - (this && this.__assign) || - function () { - __assign = - Object.assign || - function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) - if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - var __importDefault = - (this && this.__importDefault) || - function (mod) { - return mod && mod.__esModule ? mod : { default: mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.optionalRequireCwd = - exports.optionalRequire = - exports.makeOptionalRequire = - exports.tryResolve = - exports.tryRequire = - exports.setDefaultLog = - void 0; - var assert_1 = __importDefault(__nccwpck_require__(2357)); - var require_at_1 = __importDefault(__nccwpck_require__(2058)); - /* eslint-disable max-params, complexity, no-eval */ - // `require` from this module's context - // Using `eval` to avoid tripping bundlers like webpack - var xrequire = eval("require"); - /** - * Check if an error from require is really due to the module not found, - * and not because the module itself trying to require another module - * that's not found. - * - * @param err - the error - * @param name - name of the module being required - * @returns true or false - */ - function findModuleNotFound(err, name) { - // Check the first line of the error message - var msg = err.message.split("\n")[0]; - return ( - msg && - // Check for "Cannot find module 'foo'" - (msg.includes("'" + name + "'") || - // Check for "Your application tried to access foo (a peer dependency) ..." (Yarn v2 PnP) - // https://github.com/yarnpkg/berry/blob/e81dc0d29bb2f41818d9c5c1c74bab1406fb979b/packages/yarnpkg-pnp/sources/loader/makeApi.ts#L680 - msg.includes(" " + name + " ") || - // Check for "Your application tried to access foo. While ..." (Yarn v2 PnP) - // https://github.com/yarnpkg/berry/blob/e81dc0d29bb2f41818d9c5c1c74bab1406fb979b/packages/yarnpkg-pnp/sources/loader/makeApi.ts#L704 - msg.includes(" " + name + ". ") || - // Check for "Your application tried to access foo, but ..." (Yarn v2 PnP) - // https://github.com/yarnpkg/berry/blob/e81dc0d29bb2f41818d9c5c1c74bab1406fb979b/packages/yarnpkg-pnp/sources/loader/makeApi.ts#L718 - msg.includes(" " + name + ", ")) - ); - } - /** - * Default log function - * - * @param message - message to log - * @param path - path of the module to require - */ - function defaultLog(message, path) { - console.log("Just FYI: " + message + '; Path "' + path + '"'); - } - var __defaultLog = defaultLog; - function setDefaultLog(log) { - __defaultLog = log; - } - exports.setDefaultLog = setDefaultLog; - function _getOptions(optsOrMsg, requireFunction, log) { - if (requireFunction === void 0) { - requireFunction = xrequire; - } - if (typeof optsOrMsg === "object") { - var opts = __assign( - { require: requireFunction, log: log }, - optsOrMsg - ); - assert_1.default( - !( - opts.hasOwnProperty("notFound") && opts.hasOwnProperty("default") - ), - "optionalRequire: options set with both `notFound` and `default`" - ); - return opts; - } else { - return { require: requireFunction, log: log, message: optsOrMsg }; - } - } - /** - * Internal optional require implementation - * - * @param path - path to module to require - * @param optsOrMsg - options or message to log in case module not found - * @returns require or resolve result - */ - function _optionalRequire(path, opts) { - try { - return opts.resolve ? opts.require.resolve(path) : opts.require(path); - } catch (e) { - // exception that's not due to the module itself not found - if (e.code !== "MODULE_NOT_FOUND" || !findModuleNotFound(e, path)) { - // if the module we are requiring fail because it try to require a - // module that's not found, then we have to report this as failed. - if (typeof opts.fail === "function") { - return opts.fail(e); - } - throw e; - } - if (opts.message) { - var message = opts.message === true ? "" : opts.message + " - "; - var r = opts.resolve ? "resolved" : "found"; - opts.log(message + "optional module not " + r, path); - } - if (typeof opts.notFound === "function") { - return opts.notFound(e); - } - return opts.default; - } - } - /** - * try to require a module with optional handling in case it's not found or fail to require - * - * @param callerRequire - `require` from caller context - * @param path - path to module to require - * @param optsOrMsg - options or message to log in case of exceptions - * @returns require result - */ - function tryRequire(callerRequire, path, optsOrMsg) { - var opts = _getOptions(optsOrMsg, callerRequire, __defaultLog); - opts.resolve = false; - return _optionalRequire(path, opts); - } - exports.tryRequire = tryRequire; - /** - * try to resolve a module with optional handling in case it's not found or fail to require - * - * @param callerRequire - `require` from caller context - * @param path - path to module to require - * @param optsOrMsg - options or message to log in case of exceptions - * @returns resolve result - */ - function tryResolve(callerRequire, path, optsOrMsg) { - var opts = _getOptions(optsOrMsg, callerRequire, __defaultLog); - opts.resolve = true; - return _optionalRequire(path, opts); - } - exports.tryResolve = tryResolve; - /** - * Make an optional require function, using the `require` from caller's context. - * - * @param callerRequire - `require` from caller's context - * @param log - function to log if module is not found - * @returns required module - */ - function makeOptionalRequire(callerRequire, log) { - var x = function (path, optsOrMsg) { - var opts = _getOptions(optsOrMsg, callerRequire, x.log); - return _optionalRequire(path, opts); - }; - x.resolve = function (path, optsOrMsg) { - var opts = _getOptions(optsOrMsg, callerRequire, x.log); - opts.resolve = true; - return _optionalRequire(path, opts); - }; - x.log = log || __defaultLog; - return x; - } - exports.makeOptionalRequire = makeOptionalRequire; - /** - * A default optionalRequire function using `require` from optional-require's context. - * - * @remarks because `require` is from optional-require's context, you won't be able to - * do `optionalRequire("./my-module")`. - * - * You can still override the `require` using `options.require` with the one from your - * calling context. - * - */ - exports.optionalRequire = makeOptionalRequire(xrequire); - /** - * An optionalRequire function using `require` from CWD context - * - * @remarks because `require` is from CWD context, if you do `optionalRequireCwd("./my-module")` - * then it will look for `my-module` in CWD. - * - * @remarks You can still override the `require` using `options.require` with the one from your - * calling context. - */ - exports.optionalRequireCwd = makeOptionalRequire( - require_at_1.default(process.cwd()) - ); - //# sourceMappingURL=index.js.map + opts.sort.push([field, val]); +} - /***/ - }, +function _pushMap(opts, map) { + opts.sort = opts.sort || new Map(); + if (!(opts.sort instanceof Map)) { + throw new TypeError('Can\'t mix sort syntaxes. Use either array or ' + + 'object or map consistently'); + } + map.forEach(function(value, key) { + let val = String(value || 1).toLowerCase(); + val = _validSortValue[val]; + if (!val) throw new TypeError('Invalid sort value: < ' + key + ': ' + value + ' >'); - /***/ 3182: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + opts.sort.set(key, val); + }); +} - /** - * Compatibility bridge to the new typescript code. - * - */ - const lib = __nccwpck_require__(9341); - module.exports = function () { - return lib.makeOptionalRequire.apply(lib, arguments); - }; +/** + * Specifies the limit option. + * + * ####Example + * + * query.limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method limit + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D + * @api public + */ +/** + * Specifies the skip option. + * + * ####Example + * + * query.skip(100).limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method skip + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D + * @api public + */ +/** + * Specifies the maxScan option. + * + * ####Example + * + * query.maxScan(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method maxScan + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan + * @api public + */ +/** + * Specifies the batchSize option. + * + * ####Example + * + * query.batchSize(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method batchSize + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D + * @api public + */ +/** + * Specifies the `comment` option. + * + * ####Example + * + * query.comment('login query') + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method comment + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment + * @api public + */ - module.exports.tryRequire = lib.tryRequire; - module.exports.tryResolve = lib.tryResolve; - module.exports.try = lib.tryRequire; - module.exports.resolve = lib.tryResolve; - module.exports.makeOptionalRequire = lib.makeOptionalRequire; - module.exports.optionalRequire = lib.optionalRequire; - module.exports.optionalRequireCwd = lib.optionalRequireCwd; - module.exports.optionalRequireTop = lib.optionalRequireTop; - - let __defaultLog; - - Object.defineProperty(module.exports, "log", { - set(func) { - __defaultLog = func; - lib.setDefaultLog(func); - }, +/*! + * limit, skip, maxScan, batchSize, comment + * + * Sets these associated options. + * + * query.comment('feed query'); + */ - get() { - return __defaultLog; - }, - }); +['limit', 'skip', 'maxScan', 'batchSize', 'comment'].forEach(function(method) { + Query.prototype[method] = function(v) { + this._validate(method); + this.options[method] = v; + return this; + }; +}); - /***/ - }, +/** + * Specifies the maxTimeMS option. + * + * ####Example + * + * query.maxTime(100) + * query.maxTimeMS(100) + * + * @method maxTime + * @memberOf Query + * @param {Number} ms + * @see mongodb http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS + * @api public + */ - /***/ 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); - }); - } - } +Query.prototype.maxTime = Query.prototype.maxTimeMS = function(ms) { + this._validate('maxTime'); + this.options.maxTimeMS = ms; + return this; +}; - /***/ - }, +/** + * Specifies this query as a `snapshot` query. + * + * ####Example + * + * mquery().snapshot() // true + * mquery().snapshot(true) + * mquery().snapshot(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D + * @return {Query} this + * @api public + */ - /***/ 1359: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_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 = __nccwpck_require__(7810); - /**/ - - /**/ - var objectKeys = - Object.keys || - function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - } - return keys; - }; - /**/ +Query.prototype.snapshot = function() { + this._validate('snapshot'); - module.exports = Duplex; + this.options.snapshot = arguments.length + ? !!arguments[0] + : true; - /**/ - var util = Object.create(__nccwpck_require__(5898)); - util.inherits = __nccwpck_require__(4124); - /**/ + return this; +}; - var Readable = __nccwpck_require__(1433); - var Writable = __nccwpck_require__(6993); +/** + * Sets query hints. + * + * ####Example + * + * query.hint({ indexA: 1, indexB: -1}); + * query.hint('indexA_1_indexB_1'); + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object|string} val a hint object or the index name + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint + * @api public + */ - util.inherits(Duplex, Readable); +Query.prototype.hint = function() { + if (0 === arguments.length) return this; - { - // 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]; - } - } + this._validate('hint'); - function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); + const arg = arguments[0]; + if (utils.isObject(arg)) { + const hint = this.options.hint || (this.options.hint = {}); - Readable.call(this, options); - Writable.call(this, options); + // must keep object keys in order so don't use Object.keys() + for (const k in arg) { + hint[k] = arg[k]; + } - if (options && options.readable === false) this.readable = false; + return this; + } + if (typeof arg === 'string') { + this.options.hint = arg; + return this; + } - if (options && options.writable === false) this.writable = false; + throw new TypeError('Invalid hint. ' + arg); +}; - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; +/** + * Requests acknowledgement that this operation has been persisted to MongoDB's + * on-disk journal. + * This option is only valid for operations that write to the database: + * + * - `deleteOne()` + * - `deleteMany()` + * - `findOneAndDelete()` + * - `findOneAndUpdate()` + * - `remove()` + * - `update()` + * - `updateOne()` + * - `updateMany()` + * + * Defaults to the `j` value if it is specified in writeConcern options + * + * ####Example: + * + * mquery().w(2).j(true).wtimeout(2000); + * + * @method j + * @memberOf Query + * @instance + * @param {boolean} val + * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#j-option + * @return {Query} this + * @api public + */ - this.once("end", onend); - } +Query.prototype.j = function j(val) { + this.options.j = val; + return this; +}; - 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; - }, - }); +/** + * Sets the slaveOk option. _Deprecated_ in MongoDB 2.2 in favor of read preferences. + * + * ####Example: + * + * query.slaveOk() // true + * query.slaveOk(true) + * query.slaveOk(false) + * + * @deprecated use read() preferences instead if on mongodb >= 2.2 + * @param {Boolean} v defaults to true + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see read() + * @return {Query} this + * @api public + */ - // 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; +Query.prototype.slaveOk = function(v) { + this.options.slaveOk = arguments.length ? !!v : true; + return this; +}; - // no more data can be written. - // But allow more writes to happen in this tick. - pna.nextTick(onEndNT, this); - } +/** + * Sets the readPreference option for the query. + * + * ####Example: + * + * new Query().read('primary') + * new Query().read('p') // same as primary + * + * new Query().read('primaryPreferred') + * new Query().read('pp') // same as primaryPreferred + * + * new Query().read('secondary') + * new Query().read('s') // same as secondary + * + * new Query().read('secondaryPreferred') + * new Query().read('sp') // same as secondaryPreferred + * + * new Query().read('nearest') + * new Query().read('n') // same as nearest + * + * // you can also use mongodb.ReadPreference class to also specify tags + * new Query().read(mongodb.ReadPreference('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])) + * + * new Query().setReadPreference('primary') // alias of .read() + * + * ####Preferences: + * + * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. + * secondary Read from secondary if available, otherwise error. + * primaryPreferred Read from primary if available, otherwise a secondary. + * secondaryPreferred Read from a secondary if available, otherwise read from the primary. + * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. + * + * Aliases + * + * p primary + * pp primaryPreferred + * s secondary + * sp secondaryPreferred + * n nearest + * + * Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). + * + * @param {String|ReadPreference} pref one of the listed preference options or their aliases + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences + * @return {Query} this + * @api public + */ - function onEndNT(self) { - self.end(); - } +Query.prototype.read = Query.prototype.setReadPreference = function(pref) { + if (arguments.length > 1 && !Query.prototype.read.deprecationWarningIssued) { + console.error('Deprecation warning: \'tags\' argument is not supported anymore in Query.read() method. Please use mongodb.ReadPreference object instead.'); + Query.prototype.read.deprecationWarningIssued = true; + } + this.options.readPreference = utils.readPref(pref); + return this; +}; - 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; - } +/** + * Sets the readConcern option for the query. + * + * ####Example: + * + * new Query().readConcern('local') + * new Query().readConcern('l') // same as local + * + * new Query().readConcern('available') + * new Query().readConcern('a') // same as available + * + * new Query().readConcern('majority') + * new Query().readConcern('m') // same as majority + * + * new Query().readConcern('linearizable') + * new Query().readConcern('lz') // same as linearizable + * + * new Query().readConcern('snapshot') + * new Query().readConcern('s') // same as snapshot + * + * new Query().r('s') // r is alias of readConcern + * + * + * ####Read Concern Level: + * + * local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). + * available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). + * majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. + * linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. + * snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. - // 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(); + * + * + * Aliases + * + * l local + * a available + * m majority + * lz linearizable + * s snapshot + * + * Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/). + * + * @param {String} level one of the listed read concern level or their aliases + * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/ + * @return {Query} this + * @api public + */ - pna.nextTick(cb, err); - }; +Query.prototype.readConcern = Query.prototype.r = function(level) { + this.options.readConcern = utils.readConcern(level); + return this; +}; - /***/ - }, +/** + * Sets tailable option. + * + * ####Example + * + * query.tailable() <== true + * query.tailable(true) + * query.tailable(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Boolean} v defaults to true + * @see mongodb http://www.mongodb.org/display/DOCS/Tailable+Cursors + * @api public + */ - /***/ 1542: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_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 = __nccwpck_require__(4415); - - /**/ - var util = Object.create(__nccwpck_require__(5898)); - util.inherits = __nccwpck_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); - }; +Query.prototype.tailable = function() { + this._validate('tailable'); - /***/ - }, + this.options.tailable = arguments.length + ? !!arguments[0] + : true; - /***/ 1433: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_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 = __nccwpck_require__(7810); - /**/ - - module.exports = Readable; - - /**/ - var isArray = __nccwpck_require__(893); - /**/ - - /**/ - var Duplex; - /**/ - - Readable.ReadableState = ReadableState; - - /**/ - var EE = __nccwpck_require__(8614).EventEmitter; - - var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; - }; - /**/ + return this; +}; - /**/ - var Stream = __nccwpck_require__(2387); - /**/ +/** + * Sets the specified number of `mongod` servers, or tag set of `mongod` servers, + * that must acknowledge this write before this write is considered successful. + * This option is only valid for operations that write to the database: + * + * - `deleteOne()` + * - `deleteMany()` + * - `findOneAndDelete()` + * - `findOneAndUpdate()` + * - `remove()` + * - `update()` + * - `updateOne()` + * - `updateMany()` + * + * Defaults to the `w` value if it is specified in writeConcern options + * + * ####Example: + * + * mquery().writeConcern(0) + * mquery().writeConcern(1) + * mquery().writeConcern({ w: 1, j: true, wtimeout: 2000 }) + * mquery().writeConcern('majority') + * mquery().writeConcern('m') // same as majority + * mquery().writeConcern('tagSetName') // if the tag set is 'm', use .writeConcern({ w: 'm' }) instead + * mquery().w(1) // w is alias of writeConcern + * + * @method writeConcern + * @memberOf Query + * @instance + * @param {String|number|object} concern 0 for fire-and-forget, 1 for acknowledged by one server, 'majority' for majority of the replica set, or [any of the more advanced options](https://docs.mongodb.com/manual/reference/write-concern/#w-option). + * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#w-option + * @return {Query} this + * @api public + */ - /**/ +Query.prototype.writeConcern = Query.prototype.w = function writeConcern(concern) { + if ('object' === typeof concern) { + if ('undefined' !== typeof concern.j) this.options.j = concern.j; + if ('undefined' !== typeof concern.w) this.options.w = concern.w; + if ('undefined' !== typeof concern.wtimeout) this.options.wtimeout = concern.wtimeout; + } else { + this.options.w = 'm' === concern ? 'majority' : concern; + } + return this; +}; + +/** + * Specifies a time limit, in milliseconds, for the write concern. + * If `ms > 1`, it is maximum amount of time to wait for this write + * to propagate through the replica set before this operation fails. + * The default is `0`, which means no timeout. + * + * This option is only valid for operations that write to the database: + * + * - `deleteOne()` + * - `deleteMany()` + * - `findOneAndDelete()` + * - `findOneAndUpdate()` + * - `remove()` + * - `update()` + * - `updateOne()` + * - `updateMany()` + * + * Defaults to `wtimeout` value if it is specified in writeConcern + * + * ####Example: + * + * mquery().w(2).j(true).wtimeout(2000) + * + * @method wtimeout + * @memberOf Query + * @instance + * @param {number} ms number of milliseconds to wait + * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#wtimeout + * @return {Query} this + * @api public + */ - var Buffer = __nccwpck_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; - } +Query.prototype.wtimeout = Query.prototype.wTimeout = function wtimeout(ms) { + this.options.wtimeout = ms; + return this; +}; - /**/ +/** + * Merges another Query or conditions object into this one. + * + * When a Query is passed, conditions, field selection and options are merged. + * + * @param {Query|Object} source + * @return {Query} this + */ - /**/ - var util = Object.create(__nccwpck_require__(5898)); - util.inherits = __nccwpck_require__(4124); - /**/ +Query.prototype.merge = function(source) { + if (!source) + return this; - /**/ - var debugUtil = __nccwpck_require__(1669); - var debug = void 0; - if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog("stream"); - } else { - debug = function () {}; - } - /**/ + if (!Query.canMerge(source)) + throw new TypeError('Invalid argument. Expected instanceof mquery or plain object'); - var BufferList = __nccwpck_require__(7053); - var destroyImpl = __nccwpck_require__(7049); - var StringDecoder; + if (source instanceof Query) { + // if source has a feature, apply it to ourselves - util.inherits(Readable, Stream); + if (source._conditions) { + utils.merge(this._conditions, source._conditions); + } - var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; + if (source._fields) { + this._fields || (this._fields = {}); + utils.merge(this._fields, source._fields); + } - 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); + if (source.options) { + this.options || (this.options = {}); + utils.merge(this.options, source.options); + } - // 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]]; - } + if (source._update) { + this._update || (this._update = {}); + utils.mergeClone(this._update, source._update); + } - function ReadableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(1359); + if (source._distinct) { + this._distinct = source._distinct; + } - options = options || {}; + return this; + } - // 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; + // plain object + utils.merge(this._conditions, source); - // 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"; + return this; +}; - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; +/** + * Finds documents. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * query.find() + * query.find(callback) + * query.find({ name: 'Burning Lights' }, callback) + * + * @param {Object} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ - // if true, a maybeReadMore has been scheduled - this.readingMore = false; +Query.prototype.find = function(criteria, callback) { + this.op = 'find'; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) - StringDecoder = __nccwpck_require__(8536) /* .StringDecoder */.s; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } - } + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } - function Readable(options) { - Duplex = Duplex || __nccwpck_require__(1359); + if (!callback) return this; - if (!(this instanceof Readable)) return new Readable(options); + const conds = this._conditions; + const options = this._optionsForExec(); - this._readableState = new ReadableState(options, this); + if (this.$useProjection) { + options.projection = this._fieldsForExec(); + } else { + options.fields = this._fieldsForExec(); + } - // legacy - this.readable = true; + debug('find', this._collection.collectionName, conds, options); + callback = this._wrapCallback('find', callback, { + conditions: conds, + options: options + }); - if (options) { - if (typeof options.read === "function") this._read = options.read; + this._collection.find(conds, options, utils.tick(callback)); + return this; +}; - if (typeof options.destroy === "function") - this._destroy = options.destroy; - } +/** + * Returns the query cursor + * + * ####Examples + * + * query.find().cursor(); + * query.cursor({ name: 'Burning Lights' }); + * + * @param {Object} [criteria] mongodb selector + * @return {Object} cursor + * @api public + */ - Stream.call(this); - } +Query.prototype.cursor = function cursor(criteria) { + if (this.op) { + if (this.op !== 'find') { + throw new TypeError('.cursor only support .find method'); + } + } else { + this.find(criteria); + } - 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; - } + const conds = this._conditions; + const options = this._optionsForExec(); - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - }, - }); + if (this.$useProjection) { + options.projection = this._fieldsForExec(); + } else { + options.fields = this._fieldsForExec(); + } - Readable.prototype.destroy = destroyImpl.destroy; - Readable.prototype._undestroy = destroyImpl.undestroy; - Readable.prototype._destroy = function (err, cb) { - this.push(null); - cb(err); - }; + debug('findCursor', this._collection.collectionName, conds, options); + return this._collection.findCursor(conds, options); +}; - // 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; - } +/** + * Executes the query as a findOne() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * query.findOne().where('name', /^Burning/); + * + * query.findOne({ name: /^Burning/ }) + * + * query.findOne({ name: /^Burning/ }, callback); // executes + * + * query.findOne(function (err, doc) { + * if (err) return handleError(err); + * if (doc) { + * // doc may be null if no document matched + * + * } + * }); + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); - }; +Query.prototype.findOne = function(criteria, callback) { + this.op = 'findOne'; - // Unshift should *always* be something directly out of read() - Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); - }; + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } - 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; - } - } + if (!callback) return this; - return needMoreData(state); - } + const conds = this._conditions; + const options = this._optionsForExec(); - 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 (this.$useProjection) { + options.projection = this._fieldsForExec(); + } else { + options.fields = this._fieldsForExec(); + } - if (state.needReadable) emitReadable(stream); - } - maybeReadMore(stream, state); - } + debug('findOne', this._collection.collectionName, conds, options); + callback = this._wrapCallback('findOne', callback, { + conditions: conds, + options: options + }); - 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) - ); - } + this._collection.findOne(conds, options, utils.tick(callback)); - Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; - }; + return this; +}; - // backwards compatibility. - Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) - StringDecoder = __nccwpck_require__(8536) /* .StringDecoder */.s; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; - }; +/** + * Exectues the query as a count() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * query.count().where('color', 'black').exec(callback); + * + * query.count({ color: 'black' }).count(callback) + * + * query.count({ color: 'black' }, callback) + * + * query.where('color', 'black').count(function (err, count) { + * if (err) return handleError(err); + * console.log('there are %d kittens', count); + * }) + * + * @param {Object} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Count + * @api public + */ - // 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; - } +Query.prototype.count = function(criteria, callback) { + this.op = 'count'; + this._validate(); - n = howMuchToRead(n, state); + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } - // 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; - } + if (!callback) return this; - // 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; - } + const conds = this._conditions, + options = this._optionsForExec(); - 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; + debug('count', this._collection.collectionName, conds, options); + callback = this._wrapCallback('count', callback, { + conditions: conds, + options: options + }); - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } + this._collection.count(conds, options, utils.tick(callback)); + return this; +}; - if (ret !== null) this.emit("data", ret); +/** + * Declares or executes a distinct() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * distinct(criteria, field, fn) + * distinct(criteria, field) + * distinct(field, fn) + * distinct(field) + * distinct(fn) + * distinct() + * + * @param {Object|Query} [criteria] + * @param {String} [field] + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct + * @api public + */ - return ret; - }; +Query.prototype.distinct = function(criteria, field, callback) { + this.op = 'distinct'; + this._validate(); - 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; - } + if (!callback) { + switch (typeof field) { + case 'function': + callback = field; + if ('string' == typeof criteria) { + field = criteria; + criteria = undefined; } - state.ended = true; + break; + case 'undefined': + case 'string': + break; + default: + throw new TypeError('Invalid `field` argument. Must be string or function'); + } - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); - } + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = field = undefined; + break; + case 'string': + field = criteria; + criteria = undefined; + break; + } + } - // 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); - } - } + if ('string' == typeof field) { + this._distinct = field; + } - function emitReadable_(stream) { - debug("emit readable"); - stream.emit("readable"); - flow(stream); - } + if (Query.canMerge(criteria)) { + this.merge(criteria); + } - // 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); - } - } + if (!callback) { + return this; + } - 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; - } + if (!this._distinct) { + throw new Error('No value for `distinct` has been declared'); + } - // 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")); - }; + const conds = this._conditions, + options = this._optionsForExec(); - Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; + debug('distinct', this._collection.collectionName, conds, options); + callback = this._wrapCallback('distinct', callback, { + conditions: conds, + options: options + }); - 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); + this._collection.distinct(this._distinct, conds, options, utils.tick(callback)); - var doEnd = - (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; + return this; +}; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) pna.nextTick(endFn); - else src.once("end", endFn); +/** + * Declare and/or execute this query as an update() operation. By default, + * `update()` only modifies the _first_ document that matches `criteria`. + * + * _All paths passed that are not $atomic operations will become $set ops._ + * + * ####Example + * + * mquery({ _id: id }).update({ title: 'words' }, ...) + * + * becomes + * + * collection.update({ _id: id }, { $set: { title: 'words' }}, ...) + * + * ####Note + * + * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method. + * + * var q = mquery(collection).where({ _id: id }); + * q.update({ $set: { name: 'bob' }}).update(); // not executed + * + * var q = mquery(collection).where({ _id: id }); + * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe + * + * // keys that are not $atomic ops become $set. + * // this executes the same command as the previous example. + * q.update({ name: 'bob' }).where({ _id: id }).exec(); + * + * var q = mquery(collection).update(); // not executed + * + * // overwriting with empty docs + * var q.where({ _id: id }).setOptions({ overwrite: true }) + * q.update({ }, callback); // executes + * + * // multi update with overwrite to empty doc + * var q = mquery(collection).where({ _id: id }); + * q.setOptions({ multi: true, overwrite: true }) + * q.update({ }); + * q.update(callback); // executed + * + * // multi updates + * mquery() + * .collection(coll) + * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) + * // more multi updates + * mquery({ }) + * .collection(coll) + * .setOptions({ multi: true }) + * .update({ $set: { arr: [] }}, callback) + * + * // single update by default + * mquery({ email: 'address@example.com' }) + * .collection(coll) + * .update({ $inc: { counter: 1 }}, callback) + * + * // summary + * update(criteria, doc, opts, cb) // executes + * update(criteria, doc, opts) + * update(criteria, doc, cb) // executes + * update(criteria, doc) + * update(doc, cb) // executes + * update(doc) + * update(cb) // executes + * update(true) // executes (unsafe write) + * update() + * + * @param {Object} [criteria] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @api public + */ - dest.on("unpipe", onunpipe); - function onunpipe(readable, unpipeInfo) { - debug("onunpipe"); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } +Query.prototype.update = function update(criteria, doc, options, callback) { + var force; + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = undefined; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + break; + case 1: + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = options = doc = undefined; + break; + case 'boolean': + // execution with no callback (unsafe write) + force = criteria; + criteria = undefined; + break; + default: + doc = criteria; + criteria = options = undefined; + break; + } + } - 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(); - } - } + return _update(this, 'update', criteria, doc, options, force, callback); +}; - // 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); - } +/** + * Declare and/or execute this query as an `updateMany()` operation. Identical + * to `update()` except `updateMany()` will update _all_ documents that match + * `criteria`, rather than just the first one. + * + * _All paths passed that are not $atomic operations will become $set ops._ + * + * ####Example + * + * // Update every document whose `title` contains 'test' + * mquery().updateMany({ title: /test/ }, { year: 2017 }) + * + * @param {Object} [criteria] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @api public + */ - // Make sure our error handler is attached before userland ones. - prependListener(dest, "error", onerror); +Query.prototype.updateMany = function updateMany(criteria, doc, options, callback) { + let force; + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = undefined; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + break; + case 1: + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = options = doc = undefined; + break; + case 'boolean': + // execution with no callback (unsafe write) + force = criteria; + criteria = undefined; + break; + default: + doc = criteria; + criteria = options = undefined; + break; + } + } - // 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); + return _update(this, 'updateMany', criteria, doc, options, force, callback); +}; - function unpipe() { - debug("unpipe"); - src.unpipe(dest); - } +/** + * Declare and/or execute this query as an `updateOne()` operation. Identical + * to `update()` except `updateOne()` will _always_ update just one document, + * regardless of the `multi` option. + * + * _All paths passed that are not $atomic operations will become $set ops._ + * + * ####Example + * + * // Update the first document whose `title` contains 'test' + * mquery().updateMany({ title: /test/ }, { year: 2017 }) + * + * @param {Object} [criteria] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @api public + */ - // tell the dest that it's being piped to - dest.emit("pipe", src); +Query.prototype.updateOne = function updateOne(criteria, doc, options, callback) { + let force; + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = undefined; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + break; + case 1: + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = options = doc = undefined; + break; + case 'boolean': + // execution with no callback (unsafe write) + force = criteria; + criteria = undefined; + break; + default: + doc = criteria; + criteria = options = undefined; + break; + } + } - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug("pipe resume"); - src.resume(); - } + return _update(this, 'updateOne', criteria, doc, options, force, callback); +}; - return dest; - }; +/** + * Declare and/or execute this query as an `replaceOne()` operation. Similar + * to `updateOne()`, except `replaceOne()` is not allowed to use atomic + * modifiers (`$set`, `$push`, etc.). Calling `replaceOne()` will always + * replace the existing doc. + * + * ####Example + * + * // Replace the document with `_id` 1 with `{ _id: 1, year: 2017 }` + * mquery().replaceOne({ _id: 1 }, { year: 2017 }) + * + * @param {Object} [criteria] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @api public + */ - 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); - } - }; +Query.prototype.replaceOne = function replaceOne(criteria, doc, options, callback) { + let force; + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = undefined; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + break; + case 1: + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = options = doc = undefined; + break; + case 'boolean': + // execution with no callback (unsafe write) + force = criteria; + criteria = undefined; + break; + default: + doc = criteria; + criteria = options = undefined; + break; } + } - Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { hasUnpiped: false }; + this.setOptions({ overwrite: true }); + return _update(this, 'replaceOne', criteria, doc, options, force, callback); +}; - // 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; +/*! + * Internal helper for update, updateMany, updateOne + */ - if (!dest) dest = state.pipes; +function _update(query, op, criteria, doc, options, force, callback) { + query.op = op; - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit("unpipe", this, unpipeInfo); - return this; - } + if (Query.canMerge(criteria)) { + query.merge(criteria); + } - // slow case. multiple pipe destinations. + if (doc) { + query._mergeUpdate(doc); + } - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + if (utils.isObject(options)) { + // { overwrite: true } + query.setOptions(options); + } - for (var i = 0; i < len; i++) { - dests[i].emit("unpipe", this, unpipeInfo); - } - return this; - } + // we are done if we don't have callback and they are + // not forcing an unsafe write. + if (!(force || callback)) { + return query; + } - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; + if (!query._update || + !query.options.overwrite && 0 === utils.keys(query._update).length) { + callback && utils.soon(callback.bind(null, null, 0)); + return query; + } - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; + options = query._optionsForExec(); + if (!callback) options.safe = false; - dest.emit("unpipe", this, unpipeInfo); + criteria = query._conditions; + doc = query._updateForExec(); - return this; - }; + debug('update', query._collection.collectionName, criteria, doc, options); + callback = query._wrapCallback(op, callback, { + conditions: criteria, + doc: doc, + options: options + }); - // 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); - } - } - } + query._collection[op](criteria, doc, options, utils.tick(callback)); - return res; - }; - Readable.prototype.addListener = Readable.prototype.on; + return query; +} - function nReadingNextTick(self) { - debug("readable nexttick read 0"); - self.read(0); - } +/** + * Declare and/or execute this query as a remove() operation. + * + * ####Example + * + * mquery(collection).remove({ artist: 'Anne Murray' }, callback) + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the `exec()` method. + * + * // not executed + * var query = mquery(collection).remove({ name: 'Anne Murray' }) + * + * // executed + * mquery(collection).remove({ name: 'Anne Murray' }, callback) + * mquery(collection).remove({ name: 'Anne Murray' }).remove(callback) + * + * // executed without a callback (unsafe write) + * query.exec() + * + * // summary + * query.remove(conds, fn); // executes + * query.remove(conds) + * query.remove(fn) // executes + * query.remove() + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ - // 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; - }; +Query.prototype.remove = function(criteria, callback) { + this.op = 'remove'; + let force; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } else if (true === criteria) { + force = criteria; + criteria = undefined; + } - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - pna.nextTick(resume_, stream, state); - } - } + if (!(force || callback)) + return this; - function resume_(stream, state) { - if (!state.reading) { - debug("resume read 0"); - stream.read(0); - } + const options = this._optionsForExec(); + if (!callback) options.safe = false; - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit("resume"); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); - } + const conds = this._conditions; - 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; - }; + debug('remove', this._collection.collectionName, conds, options); + callback = this._wrapCallback('remove', callback, { + conditions: conds, + options: options + }); - function flow(stream) { - var state = stream._readableState; - debug("flow", state.flowing); - while (state.flowing && stream.read() !== null) {} - } + this._collection.remove(conds, options, utils.tick(callback)); - // 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; + return this; +}; - var state = this._readableState; - var paused = false; +/** + * Declare and/or execute this query as a `deleteOne()` operation. Behaves like + * `remove()`, except for ignores the `justOne` option and always deletes at + * most one document. + * + * ####Example + * + * mquery(collection).deleteOne({ artist: 'Anne Murray' }, callback) + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ - stream.on("end", function () { - debug("wrapped end"); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } +Query.prototype.deleteOne = function(criteria, callback) { + this.op = 'deleteOne'; + let force; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } else if (true === criteria) { + force = criteria; + criteria = undefined; + } - _this.push(null); - }); + if (!(force || callback)) + return this; - stream.on("data", function (chunk) { - debug("wrapped data"); - if (state.decoder) chunk = state.decoder.write(chunk); + const options = this._optionsForExec(); + if (!callback) options.safe = false; + delete options.justOne; - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) - return; - else if (!state.objectMode && (!chunk || !chunk.length)) return; + const conds = this._conditions; - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); + debug('deleteOne', this._collection.collectionName, conds, options); + callback = this._wrapCallback('deleteOne', callback, { + conditions: conds, + options: options + }); - // 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); - } - } + this._collection.deleteOne(conds, options, utils.tick(callback)); - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } + return this; +}; - // 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(); - } - }; +/** + * Declare and/or execute this query as a `deleteMany()` operation. Behaves like + * `remove()`, except for ignores the `justOne` option and always deletes + * _every_ document that matches `criteria`. + * + * ####Example + * + * mquery(collection).deleteMany({ artist: 'Anne Murray' }, callback) + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ - return this; - }; +Query.prototype.deleteMany = function(criteria, callback) { + this.op = 'deleteMany'; + let force; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } else if (true === criteria) { + force = criteria; + criteria = undefined; + } - 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; - }, - }); + if (!(force || callback)) + return this; - // 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); - } + const options = this._optionsForExec(); + if (!callback) options.safe = false; + delete options.justOne; - return ret; - } + const conds = this._conditions; - // 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; + debug('deleteOne', this._collection.collectionName, conds, options); + callback = this._wrapCallback('deleteOne', callback, { + conditions: conds, + options: options + }); + + this._collection.deleteMany(conds, options, utils.tick(callback)); + + return this; +}; + +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. + * + * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. + * + * ####Available options + * + * - `new`: bool - true to return the modified document rather than the original. defaults to true + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * + * ####Examples + * + * query.findOneAndUpdate(conditions, update, options, callback) // executes + * query.findOneAndUpdate(conditions, update, options) // returns Query + * query.findOneAndUpdate(conditions, update, callback) // executes + * query.findOneAndUpdate(conditions, update) // returns Query + * query.findOneAndUpdate(update, callback) // returns Query + * query.findOneAndUpdate(update) // returns Query + * query.findOneAndUpdate(callback) // executes + * query.findOneAndUpdate() // returns Query + * + * @param {Object|Query} [query] + * @param {Object} [doc] + * @param {Object} [options] + * @param {Function} [callback] + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @return {Query} this + * @api public + */ + +Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) { + this.op = 'findOneAndUpdate'; + this._validate(); + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = {}; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + options = undefined; + break; + case 1: + if ('function' == typeof criteria) { + callback = criteria; + criteria = options = doc = undefined; + } else { + doc = criteria; + criteria = options = undefined; } + } - function endReadable(stream) { - var state = stream._readableState; + if (Query.canMerge(criteria)) { + this.merge(criteria); + } - // 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'); + // apply doc + if (doc) { + this._mergeUpdate(doc); + } - if (!state.endEmitted) { - state.ended = true; - pna.nextTick(endReadableNT, state, stream); - } - } + options && this.setOptions(options); - 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"); - } - } + if (!callback) return this; - function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; - } + const conds = this._conditions; + const update = this._updateForExec(); + options = this._optionsForExec(); - /***/ - }, + return this._collection.findOneAndUpdate(conds, update, options, utils.tick(callback)); +}; - /***/ 4415: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_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 = __nccwpck_require__(1359); - - /**/ - var util = Object.create(__nccwpck_require__(5898)); - util.inherits = __nccwpck_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") - ); - } +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. + * + * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. + * + * ####Available options + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * + * ####Examples + * + * A.where().findOneAndRemove(conditions, options, callback) // executes + * A.where().findOneAndRemove(conditions, options) // return Query + * A.where().findOneAndRemove(conditions, callback) // executes + * A.where().findOneAndRemove(conditions) // returns Query + * A.where().findOneAndRemove(callback) // executes + * A.where().findOneAndRemove() // returns Query + * A.where().findOneAndDelete() // alias of .findOneAndRemove() + * + * @param {Object} [conditions] + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ - ts.writechunk = null; - ts.writecb = null; +Query.prototype.findOneAndRemove = Query.prototype.findOneAndDelete = function(conditions, options, callback) { + this.op = 'findOneAndRemove'; + this._validate(); - if (data != null) - // single equals check for both `null` and `undefined` - this.push(data); + if ('function' == typeof options) { + callback = options; + options = undefined; + } else if ('function' == typeof conditions) { + callback = conditions; + conditions = undefined; + } - cb(er); + // apply conditions + if (Query.canMerge(conditions)) { + this.merge(conditions); + } - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } - } + // apply options + options && this.setOptions(options); - function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); + if (!callback) return this; - Duplex.call(this, options); + options = this._optionsForExec(); + const conds = this._conditions; - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null, - }; + return this._collection.findOneAndDelete(conds, options, utils.tick(callback)); +}; - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; +/** + * Wrap callback to add tracing + * + * @param {Function} callback + * @param {Object} [queryInfo] + * @api private + */ +Query.prototype._wrapCallback = function(method, callback, queryInfo) { + const traceFunction = this._traceFunction || Query.traceFunction; - // 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 (traceFunction) { + queryInfo.collectionName = this._collection.collectionName; - if (options) { - if (typeof options.transform === "function") - this._transform = options.transform; + const traceCallback = traceFunction && + traceFunction.call(null, method, queryInfo, this); - if (typeof options.flush === "function") this._flush = options.flush; - } + const startTime = new Date().getTime(); - // When the writable side finishes, then flush out anything remaining. - this.on("prefinish", prefinish); + return function wrapperCallback(err, result) { + if (traceCallback) { + const millis = new Date().getTime() - startTime; + traceCallback.call(null, err, result, millis); } - function prefinish() { - var _this = this; - - if (typeof this._flush === "function") { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } + if (callback) { + callback.apply(null, arguments); } + }; + } - 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); - } - }; + return callback; +}; - // 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; +/** + * Add trace function that gets called when the query is executed. + * The function will be called with (method, queryInfo, query) and + * should return a callback function which will be called + * with (err, result, millis) when the query is complete. + * + * queryInfo is an object containing: { + * collectionName: , + * conditions: , + * options: , + * doc: [document to update, if applicable] + * } + * + * NOTE: Does not trace stream queries. + * + * @param {Function} traceFunction + * @return {Query} this + * @api public + */ +Query.prototype.setTraceFunction = function(traceFunction) { + this._traceFunction = traceFunction; + return this; +}; - 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; - } - }; +/** + * Executes the query + * + * ####Examples + * + * query.exec(); + * query.exec(callback); + * query.exec('update'); + * query.exec('find', callback); + * + * @param {String|Function} [operation] + * @param {Function} [callback] + * @api public + */ - Transform.prototype._destroy = function (err, cb) { - var _this2 = this; +Query.prototype.exec = function exec(op, callback) { + switch (typeof op) { + case 'function': + callback = op; + op = null; + break; + case 'string': + this.op = op; + break; + } - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - _this2.emit("close"); - }); - }; + assert.ok(this.op, 'Missing query type: (find, update, etc)'); - function done(stream, er, data) { - if (er) return stream.emit("error", er); + if ('update' == this.op || 'remove' == this.op) { + callback || (callback = true); + } - if (data != null) - // single equals check for both `null` and `undefined` - stream.push(data); + const _this = this; - // 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 ('function' == typeof callback) { + this[this.op](callback); + } else { + return new Query.Promise(function(success, error) { + _this[_this.op](function(err, val) { + if (err) error(err); + else success(val); + success = error = null; + }); + }); + } +}; - if (stream._transformState.transforming) - throw new Error("Calling transform done when still transforming"); +/** + * Returns a thunk which when called runs this.exec() + * + * The thunk receives a callback function which will be + * passed to `this.exec()` + * + * @return {Function} + * @api public + */ - return stream.push(null); - } +Query.prototype.thunk = function() { + const _this = this; + return function(cb) { + _this.exec(cb); + }; +}; - /***/ - }, +/** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + * + * @param {Function} [resolve] + * @param {Function} [reject] + * @return {Promise} + * @api public + */ - /***/ 6993: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_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 = __nccwpck_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; +Query.prototype.then = function(resolve, reject) { + const _this = this; + const promise = new Query.Promise(function(success, error) { + _this.exec(function(err, val) { + if (err) error(err); + else success(val); + success = error = null; + }); + }); + return promise.then(resolve, reject); +}; - this.next = null; - this.entry = null; - this.finish = function () { - onCorkedFinish(_this, state); - }; - } - /* */ +/** + * Returns a cursor for the given `find` query. + * + * @throws Error if operation is not a find + * @returns {Cursor} MongoDB driver cursor + */ - /**/ - var asyncWrite = - !process.browser && - ["v0.10", "v0.9."].indexOf(process.version.slice(0, 5)) > -1 - ? setImmediate - : pna.nextTick; - /**/ +Query.prototype.cursor = function() { + if ('find' != this.op) + throw new Error('cursor() is only available for find'); - /**/ - var Duplex; - /**/ + const conds = this._conditions; - Writable.WritableState = WritableState; + const options = this._optionsForExec(); + if (this.$useProjection) { + options.projection = this._fieldsForExec(); + } else { + options.fields = this._fieldsForExec(); + } - /**/ - var util = Object.create(__nccwpck_require__(5898)); - util.inherits = __nccwpck_require__(4124); - /**/ + debug('cursor', this._collection.collectionName, conds, options); - /**/ - var internalUtil = { - deprecate: __nccwpck_require__(5278), - }; - /**/ + return this._collection.findCursor(conds, options); +}; - /**/ - var Stream = __nccwpck_require__(2387); - /**/ +/** + * Determines if field selection has been made. + * + * @return {Boolean} + * @api public + */ - /**/ +Query.prototype.selected = function selected() { + return !!(this._fields && Object.keys(this._fields).length > 0); +}; - var Buffer = __nccwpck_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; - } +/** + * Determines if inclusive field selection has been made. + * + * query.selectedInclusively() // false + * query.select('name') + * query.selectedInclusively() // true + * query.selectedExlusively() // false + * + * @returns {Boolean} + */ - /**/ +Query.prototype.selectedInclusively = function selectedInclusively() { + if (!this._fields) return false; - var destroyImpl = __nccwpck_require__(7049); + const keys = Object.keys(this._fields); + if (0 === keys.length) return false; - util.inherits(Writable, Stream); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (0 === this._fields[key]) return false; + if (this._fields[key] && + typeof this._fields[key] === 'object' && + this._fields[key].$meta) { + return false; + } + } - function nop() {} + return true; +}; - function WritableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(1359); +/** + * Determines if exclusive field selection has been made. + * + * query.selectedExlusively() // false + * query.select('-name') + * query.selectedExlusively() // true + * query.selectedInclusively() // false + * + * @returns {Boolean} + */ - options = options || {}; +Query.prototype.selectedExclusively = function selectedExclusively() { + if (!this._fields) return false; - // 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; + const keys = Object.keys(this._fields); + if (0 === keys.length) return 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; + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (0 === this._fields[key]) return true; + } - // 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"; + return false; +}; - // 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; +/** + * Merges `doc` with the current update object. + * + * @param {Object} doc + */ - // a flag to see when we're in the middle of a write. - this.writing = false; +Query.prototype._mergeUpdate = function(doc) { + if (!this._update) this._update = {}; + if (doc instanceof Query) { + if (doc._update) { + utils.mergeClone(this._update, doc._update); + } + } else { + utils.mergeClone(this._update, doc); + } +}; - // when true all writes will be buffered until .uncork() call - this.corked = 0; +/** + * Returns default options. + * + * @return {Object} + * @api private + */ - // 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; +Query.prototype._optionsForExec = function() { + const options = utils.clone(this.options); + return options; +}; - // 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; +/** + * Returns fields selection for this query. + * + * @return {Object} + * @api private + */ - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; +Query.prototype._fieldsForExec = function() { + return utils.clone(this._fields); +}; - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; +/** + * Return an update document with corrected $set operations. + * + * @api private + */ - // the amount that is being written when _write is called. - this.writelen = 0; +Query.prototype._updateForExec = function() { + const update = utils.clone(this._update); + const ops = utils.keys(update); + const ret = {}; - this.bufferedRequest = null; - this.lastBufferedRequest = null; + for (const op of ops) { + if (this.options.overwrite) { + ret[op] = update[op]; + continue; + } - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + if ('$' !== op[0]) { + // fix up $set sugar + if (!ret.$set) { + if (update.$set) { + ret.$set = update.$set; + } else { + ret.$set = {}; + } + } + ret.$set[op] = update[op]; + if (!~ops.indexOf('$set')) ops.push('$set'); + } else if ('$set' === op) { + if (!ret.$set) { + ret[op] = update[op]; + } + } else { + ret[op] = update[op]; + } + } - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + this._compiledUpdate = ret; + return ret; +}; - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; +/** + * Make sure _path is set. + * + * @parmam {String} method + */ - // count buffered requests - this.bufferedRequestCount = 0; +Query.prototype._ensurePath = function(method) { + if (!this._path) { + const msg = method + '() must be used after where() ' + + 'when called with these arguments'; + throw new Error(msg); + } +}; - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); - } +/*! + * Permissions + */ - WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; - }; +Query.permissions = __nccwpck_require__(4485); - (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; - }; - } +Query._isPermitted = function(a, b) { + const denied = Query.permissions[b]; + if (!denied) return true; + return true !== denied[a]; +}; - function Writable(options) { - Duplex = Duplex || __nccwpck_require__(1359); +Query.prototype._validate = function(action) { + let fail; + let validator; - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. + if (undefined === action) { - // 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); - } + validator = Query.permissions[this.op]; + if ('function' != typeof validator) return true; - this._writableState = new WritableState(options, this); + fail = validator(this); - // legacy. - this.writable = true; + } else if (!Query._isPermitted(action, this.op)) { + fail = action; + } - if (options) { - if (typeof options.write === "function") this._write = options.write; + if (fail) { + throw new Error(fail + ' cannot be used with ' + this.op); + } +}; - if (typeof options.writev === "function") - this._writev = options.writev; +/** + * Determines if `conds` can be merged using `mquery().merge()` + * + * @param {Object} conds + * @return {Boolean} + */ - if (typeof options.destroy === "function") - this._destroy = options.destroy; +Query.canMerge = function(conds) { + return conds instanceof Query || utils.isObject(conds); +}; - if (typeof options.final === "function") this._final = options.final; - } +/** + * Set a trace function that will get called whenever a + * query is executed. + * + * See `setTraceFunction()` for details. + * + * @param {Object} conds + * @return {Boolean} + */ +Query.setGlobalTraceFunction = function(traceFunction) { + Query.traceFunction = traceFunction; +}; - Stream.call(this); - } +/*! + * Exports. + */ - // Otherwise people can pipe Writable streams, which is just wrong. - Writable.prototype.pipe = function () { - this.emit("error", new Error("Cannot pipe, not readable")); - }; +Query.utils = utils; +Query.env = __nccwpck_require__(5928); +Query.Collection = __nccwpck_require__(5680); +Query.BaseCollection = __nccwpck_require__(5257); +Query.Promise = Promise; +module.exports = exports = Query; - function writeAfterEnd(stream, cb) { - var er = new Error("write after end"); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit("error", er); - 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; - } +// TODO +// test utils - 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; - } +/***/ 4485: +/***/ ((__unused_webpack_module, exports) => { - if (isBuf) encoding = "buffer"; - else if (!encoding) encoding = state.defaultEncoding; +"use strict"; - 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); - } +const denied = exports; - return ret; - }; +denied.distinct = function(self) { + if (self._fields && Object.keys(self._fields).length > 0) { + return 'field selection and slice'; + } - Writable.prototype.cork = function () { - var state = this._writableState; + const keys = Object.keys(denied.distinct); + let err; - state.corked++; - }; + keys.every(function(option) { + if (self.options[option]) { + err = option; + return false; + } + return true; + }); + + return err; +}; +denied.distinct.select = +denied.distinct.slice = +denied.distinct.sort = +denied.distinct.limit = +denied.distinct.skip = +denied.distinct.batchSize = +denied.distinct.comment = +denied.distinct.maxScan = +denied.distinct.snapshot = +denied.distinct.hint = +denied.distinct.tailable = true; + + +// aggregation integration + + +denied.findOneAndUpdate = +denied.findOneAndRemove = function(self) { + const keys = Object.keys(denied.findOneAndUpdate); + let err; + + keys.every(function(option) { + if (self.options[option]) { + err = option; + return false; + } + return true; + }); + + return err; +}; +denied.findOneAndUpdate.limit = +denied.findOneAndUpdate.skip = +denied.findOneAndUpdate.batchSize = +denied.findOneAndUpdate.maxScan = +denied.findOneAndUpdate.snapshot = +denied.findOneAndUpdate.hint = +denied.findOneAndUpdate.tailable = +denied.findOneAndUpdate.comment = true; + + +denied.count = function(self) { + if (self._fields && Object.keys(self._fields).length > 0) { + return 'field selection and slice'; + } - Writable.prototype.uncork = function () { - var state = this._writableState; + const keys = Object.keys(denied.count); + let err; - if (state.corked) { - state.corked--; + keys.every(function(option) { + if (self.options[option]) { + err = option; + return false; + } + return true; + }); - if ( - !state.writing && - !state.corked && - !state.finished && - !state.bufferProcessing && - state.bufferedRequest - ) - clearBuffer(this, state); - } - }; + return err; +}; - 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; - }; +denied.count.slice = +denied.count.batchSize = +denied.count.comment = +denied.count.maxScan = +denied.count.snapshot = +denied.count.tailable = true; - 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; +/***/ 7483: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - state.length += len; +"use strict"; - 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); - } +/*! + * Module dependencies. + */ - return ret; - } +const RegExpClone = __nccwpck_require__(8292); - 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; - } +const specialProperties = ['__proto__', 'constructor', 'prototype']; - function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; +/** + * Clones objects + * + * @param {Object} obj the object to clone + * @param {Object} options + * @return {Object} the cloned object + * @api private + */ - 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); - } - } +const clone = exports.clone = function clone(obj, options) { + if (obj === undefined || obj === null) + return obj; - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } + if (Array.isArray(obj)) + return exports.cloneArray(obj, options); - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + if (obj.constructor) { + if (/ObjectI[dD]$/.test(obj.constructor.name)) { + return 'function' == typeof obj.clone + ? obj.clone() + : new obj.constructor(obj.id); + } - onwriteStateUpdate(state); + if (obj.constructor.name === 'ReadPreference') { + return new obj.constructor(obj.mode, clone(obj.tags, options)); + } - if (er) onwriteError(stream, state, sync, er, cb); - else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); - - if ( - !finished && - !state.corked && - !state.bufferProcessing && - state.bufferedRequest - ) { - clearBuffer(stream, state); - } + if ('Binary' == obj._bsontype && obj.buffer && obj.value) { + return 'function' == typeof obj.clone + ? obj.clone() + : new obj.constructor(obj.value(true), obj.sub_type); + } - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } - } + if ('Date' === obj.constructor.name || 'Function' === obj.constructor.name) + return new obj.constructor(+obj); - function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); - } + if ('RegExp' === obj.constructor.name) + return RegExpClone(obj); - // 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 ('Buffer' === obj.constructor.name) + return exports.cloneBuffer(obj); + } - // if there's something in the buffer waiting, then process it - function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + if (isObject(obj)) + return exports.cloneObject(obj, options); - 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; + if (obj.valueOf) + return obj.valueOf(); +}; - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; +/*! + * ignore + */ - doWrite(stream, state, true, state.length, buffer, "", holder.finish); +exports.cloneObject = function cloneObject(obj, options) { + const minimize = options && options.minimize; + const ret = {}; + let hasKeys; + let val; + const keys = Object.keys(obj); + let k; + + for (let i = 0; i < keys.length; ++i) { + k = keys[i]; + // Not technically prototype pollution because this wouldn't merge properties + // onto `Object.prototype`, but avoid properties like __proto__ as a precaution. + if (specialProperties.indexOf(k) !== -1) { + continue; + } - // 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; - } - } + val = clone(obj[k], options); - if (entry === null) state.lastBufferedRequest = null; - } + if (!minimize || ('undefined' !== typeof val)) { + hasKeys || (hasKeys = true); + ret[k] = val; + } + } - state.bufferedRequest = entry; - state.bufferProcessing = false; - } + return minimize + ? hasKeys && ret + : ret; +}; - Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error("_write() is not implemented")); - }; +exports.cloneArray = function cloneArray(arr, options) { + const ret = []; + for (let i = 0, l = arr.length; i < l; i++) + ret.push(clone(arr[i], options)); + return ret; +}; - Writable.prototype._writev = null; +/** + * process.nextTick helper. + * + * Wraps the given `callback` in a try/catch. If an error is + * caught it will be thrown on nextTick. + * + * node-mongodb-native had a habit of state corruption when + * an error was immediately thrown from within a collection + * method (find, update, etc) callback. + * + * @param {Function} [callback] + * @api private + */ - Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; +exports.tick = function tick(callback) { + if ('function' !== typeof callback) return; + return function() { + // callbacks should always be fired on the next + // turn of the event loop. A side benefit is + // errors thrown from executing the callback + // will not cause drivers state to be corrupted + // which has historically been a problem. + const args = arguments; + soon(function() { + callback.apply(this, args); + }); + }; +}; - if (typeof chunk === "function") { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === "function") { - cb = encoding; - encoding = null; - } +/** + * Merges `from` into `to` without overwriting existing properties. + * + * @param {Object} to + * @param {Object} from + * @api private + */ - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); +exports.merge = function merge(to, from) { + const keys = Object.keys(from); - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } + for (const key of keys) { + if (specialProperties.indexOf(key) !== -1) { + continue; + } + if ('undefined' === typeof to[key]) { + to[key] = from[key]; + } else { + if (exports.isObject(from[key])) { + merge(to[key], from[key]); + } else { + to[key] = from[key]; + } + } + } +}; - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); - }; +/** + * Same as merge but clones the assigned values. + * + * @param {Object} to + * @param {Object} from + * @api private + */ - 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"); - } - } - } +exports.mergeClone = function mergeClone(to, from) { + const keys = Object.keys(from); - 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; + for (const key of keys) { + if (specialProperties.indexOf(key) !== -1) { + continue; + } + if ('undefined' === typeof to[key]) { + to[key] = clone(from[key]); + } else { + if (exports.isObject(from[key])) { + mergeClone(to[key], from[key]); + } else { + to[key] = clone(from[key]); } + } + } +}; - 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; - } +/** + * Read pref helper (mongo 2.2 drivers support this) + * + * Allows using aliases instead of full preference names: + * + * p primary + * pp primaryPreferred + * s secondary + * sp secondaryPreferred + * n nearest + * + * @param {String} pref + */ - 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; - } - } +exports.readPref = function readPref(pref) { + switch (pref) { + case 'p': + pref = 'primary'; + break; + case 'pp': + pref = 'primaryPreferred'; + break; + case 's': + pref = 'secondary'; + break; + case 'sp': + pref = 'secondaryPreferred'; + break; + case 'n': + pref = 'nearest'; + break; + } - 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; - } + return pref; +}; - // 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); - }; +/** + * Read Concern helper (mongo 3.2 drivers support this) + * + * Allows using string to specify read concern level: + * + * local 3.2+ + * available 3.6+ + * majority 3.2+ + * linearizable 3.4+ + * snapshot 4.0+ + * + * @param {String|Object} concern + */ - /***/ - }, +exports.readConcern = function readConcern(concern) { + if ('string' === typeof concern) { + switch (concern) { + case 'l': + concern = 'local'; + break; + case 'a': + concern = 'available'; + break; + case 'm': + concern = 'majority'; + break; + case 'lz': + concern = 'linearizable'; + break; + case 's': + concern = 'snapshot'; + break; + } + concern = { level: concern }; + } + return concern; +}; - /***/ 7053: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +/** + * Object.prototype.toString.call helper + */ - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } +const _toString = Object.prototype.toString; +exports.toString = function(arg) { + return _toString.call(arg); +}; - var Buffer = __nccwpck_require__(110).Buffer; - var util = __nccwpck_require__(1669); +/** + * Determines if `arg` is an object. + * + * @param {Object|Array|String|Function|RegExp|any} arg + * @return {Boolean} + */ - function copyBuffer(src, target, offset) { - src.copy(target, offset); - } +const isObject = exports.isObject = function(arg) { + return '[object Object]' == exports.toString(arg); +}; - module.exports = (function () { - function BufferList() { - _classCallCheck(this, BufferList); +/** + * Determines if `arg` is an array. + * + * @param {Object} + * @return {Boolean} + * @see nodejs utils + */ - this.head = null; - this.tail = null; - this.length = 0; - } +exports.isArray = function(arg) { + return Array.isArray(arg) || + 'object' == typeof arg && '[object Array]' == exports.toString(arg); +}; - 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; - }; +/** + * Object.keys helper + */ - 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; - }; +exports.keys = Object.keys; - 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; - }; +/** + * Basic Object.create polyfill. + * Only one argument is supported. + * + * Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create + */ - BufferList.prototype.clear = function clear() { - this.head = this.tail = null; - this.length = 0; - }; +exports.create = 'function' == typeof Object.create + ? Object.create + : create; - 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; - }; +function create(proto) { + if (arguments.length > 1) { + throw new Error('Adding properties is not supported'); + } - 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; - }; + function F() {} + F.prototype = proto; + return new F; +} - return BufferList; - })(); +/** + * inheritance + */ - 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; - }; - } +exports.inherits = function(ctor, superCtor) { + ctor.prototype = exports.create(superCtor.prototype); + ctor.prototype.constructor = ctor; +}; - /***/ - }, +/** + * nextTick helper + * compat with node 0.10 which behaves differently than previous versions + */ - /***/ 7049: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +const soon = exports.soon = 'function' == typeof setImmediate + ? setImmediate + : process.nextTick; - /**/ +/** + * Clones the contents of a buffer. + * + * @param {Buffer} buff + * @return {Buffer} + */ - var pna = __nccwpck_require__(7810); - /**/ +exports.cloneBuffer = function(buff) { + const dupe = Buffer.alloc(buff.length); + buff.copy(dupe, 0, 0, buff.length); + return dupe; +}; - // undocumented cb() API, needed for core, not for public API - function destroy(err, cb) { - var _this = this; +/** + * Check if this object is an arguments object + * + * @param {Any} v + * @return {Boolean} + */ - 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; - } +exports.isArgumentsObject = function(v) { + return Object.prototype.toString.call(v) === '[object Arguments]'; +}; - // 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; - } +/***/ 3081: +/***/ ((module, exports, __nccwpck_require__) => { - 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); - } - }); +/* eslint-env browser */ - return this; - } +/** + * This is the web browser implementation of `debug()`. + */ - function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } - } +/** + * Colors. + */ - function emitErrorNT(self, err) { - self.emit("error", err); - } +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ - module.exports = { - destroy: destroy, - undestroy: undestroy, - }; +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ - /***/ - }, +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); - /***/ 2387: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - module.exports = __nccwpck_require__(2413); +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ - /***/ - }, +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} - /***/ 110: /***/ (module, exports, __nccwpck_require__) => { - /* eslint-disable node/no-deprecated-api */ - var buffer = __nccwpck_require__(4293); - var Buffer = buffer.Buffer; +module.exports = __nccwpck_require__(4553)(exports); - // 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; - } +const {formatters} = module.exports; - function SafeBuffer(arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length); - } +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ - // Copy static methods from Buffer - copyProps(Buffer, SafeBuffer); +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; - 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); - }; +/***/ 4553: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - return buffer.SlowBuffer(size); - }; - /***/ - }, +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ - /***/ 8536: /***/ ( - __unused_webpack_module, - exports, - __nccwpck_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 = __nccwpck_require__(110).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 setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __nccwpck_require__(900); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +module.exports = setup; + + +/***/ }), + +/***/ 7816: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ - 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; - } - } - } +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(3081); +} else { + module.exports = __nccwpck_require__(7879); +} - // 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; +/***/ 7879: +/***/ ((module, exports, __nccwpck_require__) => { - // Returns only complete characters in a Buffer - StringDecoder.prototype.text = utf8Text; +/** + * Module dependencies. + */ - // 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; - }; +const tty = __nccwpck_require__(3867); +const util = __nccwpck_require__(1669); - // 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"; - } - } - } - } +/** + * This is the Node.js implementation of `debug()`. + */ - // 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); - } +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); + +/** + * Colors. + */ - // 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; - } +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __nccwpck_require__(9318); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - 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); - } +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - 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; - } +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} - // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) - function simpleWrite(buf) { - return buf.toString(this.encoding); - } +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ - function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ""; - } +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ - /***/ - }, +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} - /***/ 1642: /***/ (module, exports, __nccwpck_require__) => { - var Stream = __nccwpck_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 = __nccwpck_require__(1433); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = __nccwpck_require__(6993); - exports.Duplex = __nccwpck_require__(1359); - exports.Transform = __nccwpck_require__(4415); - exports.PassThrough = __nccwpck_require__(1542); - } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - /***/ - }, +function load() { + return process.env.DEBUG; +} - /***/ 8292: /***/ (module, exports) => { - const toString = Object.prototype.toString; +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ - function isRegExp(o) { - return "object" == typeof o && "[object RegExp]" == toString.call(o); - } +function init(debug) { + debug.inspectOpts = {}; - module.exports = exports = function (regexp) { - if (!isRegExp(regexp)) { - throw new TypeError("Not a RegExp"); - } + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} - const flags = []; - if (regexp.global) flags.push("g"); - if (regexp.multiline) flags.push("m"); - if (regexp.ignoreCase) flags.push("i"); - if (regexp.dotAll) flags.push("s"); - if (regexp.unicode) flags.push("u"); - if (regexp.sticky) flags.push("y"); - const result = new RegExp(regexp.source, flags.join("")); - if (typeof regexp.lastIndex === "number") { - result.lastIndex = regexp.lastIndex; - } - return result; - }; +module.exports = __nccwpck_require__(4553)(exports); - /***/ - }, +const {formatters} = module.exports; - /***/ 545: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const Module = __nccwpck_require__(2282); - // use eval to avoid tripping bundlers - const xrequire = eval("require"); - - const createRequireFromPath = - Module.createRequire || - Module.createRequireFromPath || - ((filename, dir) => { - // https://github.com/nodejs/node/blob/1ae0511b942c01c6e0adff98643d350a395bf101/lib/internal/modules/cjs/loader.js#L748 - // https://github.com/nodejs/node/blob/1ae0511b942c01c6e0adff98643d350a395bf101/lib/internal/modules/cjs/helpers.js#L16 - const m = new Module(filename); - - m.filename = filename; - m.paths = Module._nodeModulePaths(dir); - - // don't name this require to avoid tripping bundlers - function _require(request) { - // can't use m.require because there's an internal requireDepth thing - // in the native Module implementation - return xrequire(resolve(request)); - } +/** + * Map %o to `util.inspect()`, all on a single line. + */ - function resolve(request, options) { - return Module._resolveFilename(request, m, false, options); - } +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; - _require.resolve = resolve; +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ - function paths(request) { - return Module._resolveLookupPaths(request, m, true); - } +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; - resolve.paths = paths; - _require.main = process.mainModule; - _require.extensions = Module._extensions; - _require.cache = Module._cache; - return _require; - }); +/***/ }), - module.exports = createRequireFromPath; +/***/ 900: +/***/ ((module) => { - /***/ - }, +/** + * Helpers. + */ - /***/ 2058: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; - const Path = __nccwpck_require__(5622); - const Fs = __nccwpck_require__(5747); +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ - const createRequireFromPath = __nccwpck_require__(545); +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - const cache = new Map(); +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} - function requireAt(dir, request) { - const makeIt = (xdir, checked) => { - let xRequire = requireAt.cache && requireAt.cache.get(xdir); +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - if (!xRequire) { - let stat; - try { - stat = Fs.statSync(xdir); - } catch (e) { - throw new Error( - `require-at: stat '${xdir}' failed: ${e.message}` - ); - } +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} - if (!stat || !stat.isDirectory()) { - if (checked) - throw new Error(`require-at: not a directory: '${dir}'`); - return makeIt(Path.dirname(xdir), true); - } +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - xRequire = createRequireFromPath( - Path.join(xdir, "._require-at_"), - xdir - ); +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} - requireAt.cache && requireAt.cache.set(xdir, xRequire); - } +/** + * Pluralization helper. + */ - return request ? xRequire(request) : xRequire; - }; +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} - return makeIt(Path.resolve(dir), false); - } - requireAt.cache = cache; +/***/ }), - module.exports = requireAt; +/***/ 8292: +/***/ ((module, exports) => { - /***/ - }, - /***/ 1867: /***/ (module, exports, __nccwpck_require__) => { - /*! safe-buffer. MIT License. Feross Aboukhadijeh */ - /* eslint-disable node/no-deprecated-api */ - var buffer = __nccwpck_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; - } +const toString = Object.prototype.toString; - function SafeBuffer(arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length); - } +function isRegExp (o) { + return 'object' == typeof o + && '[object RegExp]' == toString.call(o); +} - SafeBuffer.prototype = Object.create(Buffer.prototype); +module.exports = exports = function (regexp) { + if (!isRegExp(regexp)) { + throw new TypeError('Not a RegExp'); + } - // Copy static methods from Buffer - copyProps(Buffer, SafeBuffer); + const flags = []; + if (regexp.global) flags.push('g'); + if (regexp.multiline) flags.push('m'); + if (regexp.ignoreCase) flags.push('i'); + if (regexp.dotAll) flags.push('s'); + if (regexp.unicode) flags.push('u'); + if (regexp.sticky) flags.push('y'); + const result = new RegExp(regexp.source, flags.join('')); + if (typeof regexp.lastIndex === 'number') { + result.lastIndex = regexp.lastIndex; + } + return result; +} - 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, __nccwpck_require__) => { - /***/ - }, +"use strict"; - /***/ 9178: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const { - unassigned_code_points, - commonly_mapped_to_nothing, - non_ASCII_space_characters, - prohibited_characters, - bidirectional_r_al, - bidirectional_l, - } = __nccwpck_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); - } +const { + unassigned_code_points, + commonly_mapped_to_nothing, + non_ASCII_space_characters, + prohibited_characters, + bidirectional_r_al, + bidirectional_l, +} = __nccwpck_require__(8916); - return codepoints; - } +module.exports = saslprep; - /** - * 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."); - } +// 2.1. Mapping - if (input.length === 0) { - return ""; - } +/** + * non-ASCII space characters [StringPrep, C.1.2] that can be + * mapped to SPACE (U+0020) + */ +const mapping2space = non_ASCII_space_characters; - // 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)); +/** + * 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; - // 2. Normalize - const normalized_input = String.fromCodePoint - .apply(null, mapped_input) - .normalize("NFKC"); + for (let i = 0; i < size; i += 1) { + const before = input.charCodeAt(i); - const normalized_map = toCodePoints(normalized_input); + if (before >= 0xd800 && before <= 0xdbff && size > i + 1) { + const next = input.charCodeAt(i + 1); - // 3. Prohibit - const hasProhibited = normalized_map.some((character) => - prohibited_characters.get(character) - ); + if (next >= 0xdc00 && next <= 0xdfff) { + codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000); + i += 1; + continue; + } + } - if (hasProhibited) { - throw new Error( - "Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3" - ); - } + codepoints.push(before); + } - // Unassigned Code Points - if (opts.allowUnassigned !== true) { - const hasUnassigned = normalized_map.some((character) => - unassigned_code_points.get(character) - ); + return codepoints; +} - if (hasUnassigned) { - throw new Error( - "Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5" - ); - } - } +/** + * 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.'); + } - // 4. check bidi + if (input.length === 0) { + return ''; + } - const hasBidiRAL = normalized_map.some((character) => - bidirectional_r_al.get(character) - ); + // 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' + ); + } - const hasBidiL = normalized_map.some((character) => - bidirectional_l.get(character) - ); + // Unassigned Code Points + if (opts.allowUnassigned !== true) { + const hasUnassigned = normalized_map.some(character => + unassigned_code_points.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" - ); - } + if (hasUnassigned) { + throw new Error( + 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5' + ); + } + } - /** - * 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. - */ + // 4. check bidi - const isFirstBidiRAL = bidirectional_r_al.get( - getCodePoint(first(normalized_input)) - ); - const isLastBidiRAL = bidirectional_r_al.get( - getCodePoint(last(normalized_input)) - ); + const hasBidiRAL = normalized_map.some(character => + bidirectional_r_al.get(character) + ); - 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" - ); - } + const hasBidiL = normalized_map.some(character => + bidirectional_l.get(character) + ); - return normalized_input; - } + // 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' + ); + } - /***/ 8916: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; + return normalized_input; +} - const fs = __nccwpck_require__(5747); - const path = __nccwpck_require__(5622); - const bitfield = __nccwpck_require__(1453); - /* eslint-disable-next-line security/detect-non-literal-fs-filename */ - const memory = fs.readFileSync( - __nccwpck_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, - }; +/***/ }), - /***/ - }, +/***/ 8916: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /***/ 2865: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - const lib = __nccwpck_require__(9305); +"use strict"; - module.exports = lib.default; - Object.assign(module.exports, lib); - /***/ - }, +const fs = __nccwpck_require__(5747); +const path = __nccwpck_require__(5622); +const bitfield = __nccwpck_require__(1453); - /***/ 9305: /***/ function (__unused_webpack_module, exports) { - (function (global, factory) { - true ? factory(exports) : 0; - })(this, function (exports) { - "use strict"; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - 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. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics = function (d, b) { - extendStatics = - Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && - function (d, b) { - d.__proto__ = b; - }) || - function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - }; - return extendStatics(d, b); - }; +/* eslint-disable-next-line security/detect-non-literal-fs-filename */ +const memory = fs.readFileSync(__nccwpck_require__.ab + "code-points.mem"); +let offset = 0; - function __extends(d, b) { - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = - b === null - ? Object.create(b) - : ((__.prototype = b.prototype), new __()); - } +/** + * 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, +}; + + +/***/ }), + +/***/ 2865: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const lib = __nccwpck_require__(9305); + +module.exports = lib.default; +Object.assign(module.exports, lib); + + +/***/ }), + +/***/ 9305: +/***/ (function(__unused_webpack_module, exports) { + +(function (global, factory) { + true ? factory(exports) : + 0; +}(this, (function (exports) { 'use strict'; + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + 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. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + + function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } - var typeChecker = function (type) { - var typeString = "[object " + type + "]"; - return function (value) { + var typeChecker = function (type) { + var typeString = "[object " + type + "]"; + return function (value) { return getClassName(value) === typeString; - }; - }; - var getClassName = function (value) { - return Object.prototype.toString.call(value); }; - var comparable = function (value) { - if (value instanceof Date) { + }; + var getClassName = function (value) { return Object.prototype.toString.call(value); }; + var comparable = function (value) { + if (value instanceof Date) { return value.getTime(); - } else if (isArray(value)) { + } + else if (isArray(value)) { return value.map(comparable); - } else if (value && typeof value.toJSON === "function") { + } + else if (value && typeof value.toJSON === "function") { return value.toJSON(); - } - return value; - }; - var isArray = typeChecker("Array"); - var isObject = typeChecker("Object"); - var isFunction = typeChecker("Function"); - var isVanillaObject = function (value) { - return ( - value && + } + return value; + }; + var isArray = typeChecker("Array"); + var isObject = typeChecker("Object"); + var isFunction = typeChecker("Function"); + var isVanillaObject = function (value) { + return (value && (value.constructor === Object || - value.constructor === Array || - value.constructor.toString() === - "function Object() { [native code] }" || - value.constructor.toString() === - "function Array() { [native code] }") && - !value.toJSON - ); - }; - var equals = function (a, b) { - if (a == null && a == b) { + value.constructor === Array || + value.constructor.toString() === "function Object() { [native code] }" || + value.constructor.toString() === "function Array() { [native code] }") && + !value.toJSON); + }; + var equals = function (a, b) { + if (a == null && a == b) { return true; - } - if (a === b) { + } + if (a === b) { return true; - } - if ( - Object.prototype.toString.call(a) !== - Object.prototype.toString.call(b) - ) { + } + if (Object.prototype.toString.call(a) !== Object.prototype.toString.call(b)) { return false; - } - if (isArray(a)) { + } + if (isArray(a)) { if (a.length !== b.length) { - return false; + return false; } for (var i = 0, length_1 = a.length; i < length_1; i++) { - if (!equals(a[i], b[i])) return false; + if (!equals(a[i], b[i])) + return false; } return true; - } else if (isObject(a)) { + } + else if (isObject(a)) { if (Object.keys(a).length !== Object.keys(b).length) { - return false; + return false; } for (var key in a) { - if (!equals(a[key], b[key])) return false; + if (!equals(a[key], b[key])) + return false; } return true; - } - return false; - }; + } + return false; + }; - /** - * Walks through each value given the context - used for nested operations. E.g: - * { "person.address": { $eq: "blarg" }} - */ - var walkKeyPathValues = function ( - item, - keyPath, - next, - depth, - key, - owner - ) { - var currentKey = keyPath[depth]; - // if array, then try matching. Might fall through for cases like: - // { $eq: [1, 2, 3] }, [ 1, 2, 3 ]. - if (isArray(item) && isNaN(Number(currentKey))) { + /** + * Walks through each value given the context - used for nested operations. E.g: + * { "person.address": { $eq: "blarg" }} + */ + var walkKeyPathValues = function (item, keyPath, next, depth, key, owner) { + var currentKey = keyPath[depth]; + // if array, then try matching. Might fall through for cases like: + // { $eq: [1, 2, 3] }, [ 1, 2, 3 ]. + if (isArray(item) && isNaN(Number(currentKey))) { for (var i = 0, length_1 = item.length; i < length_1; i++) { - // if FALSE is returned, then terminate walker. For operations, this simply - // means that the search critera was met. - if (!walkKeyPathValues(item[i], keyPath, next, depth, i, item)) { - return false; - } + // if FALSE is returned, then terminate walker. For operations, this simply + // means that the search critera was met. + if (!walkKeyPathValues(item[i], keyPath, next, depth, i, item)) { + return false; + } } - } - if (depth === keyPath.length || item == null) { + } + if (depth === keyPath.length || item == null) { return next(item, key, owner); - } - return walkKeyPathValues( - item[currentKey], - keyPath, - next, - depth + 1, - currentKey, - item - ); - }; - var BaseOperation = /** @class */ (function () { - function BaseOperation(params, owneryQuery, options) { + } + return walkKeyPathValues(item[currentKey], keyPath, next, depth + 1, currentKey, item); + }; + var BaseOperation = /** @class */ (function () { + function BaseOperation(params, owneryQuery, options) { this.params = params; this.owneryQuery = owneryQuery; this.options = options; this.init(); - } - BaseOperation.prototype.init = function () {}; - BaseOperation.prototype.reset = function () { + } + BaseOperation.prototype.init = function () { }; + BaseOperation.prototype.reset = function () { this.done = false; this.keep = false; - }; - return BaseOperation; - })(); - var NamedBaseOperation = /** @class */ (function (_super) { - __extends(NamedBaseOperation, _super); - function NamedBaseOperation(params, owneryQuery, options, name) { + }; + return BaseOperation; + }()); + var NamedBaseOperation = /** @class */ (function (_super) { + __extends(NamedBaseOperation, _super); + function NamedBaseOperation(params, owneryQuery, options, name) { var _this = _super.call(this, params, owneryQuery, options) || this; _this.name = name; return _this; - } - return NamedBaseOperation; - })(BaseOperation); - var GroupOperation = /** @class */ (function (_super) { - __extends(GroupOperation, _super); - function GroupOperation(params, owneryQuery, options, children) { + } + return NamedBaseOperation; + }(BaseOperation)); + var GroupOperation = /** @class */ (function (_super) { + __extends(GroupOperation, _super); + function GroupOperation(params, owneryQuery, options, children) { var _this = _super.call(this, params, owneryQuery, options) || this; _this.children = children; return _this; - } - /** - */ - GroupOperation.prototype.reset = function () { + } + /** + */ + GroupOperation.prototype.reset = function () { this.keep = false; this.done = false; - for ( - var i = 0, length_2 = this.children.length; - i < length_2; - i++ - ) { - this.children[i].reset(); + for (var i = 0, length_2 = this.children.length; i < length_2; i++) { + this.children[i].reset(); } - }; - /** - */ - GroupOperation.prototype.childrenNext = function (item, key, owner) { + }; + /** + */ + GroupOperation.prototype.childrenNext = function (item, key, owner) { var done = true; var keep = true; - for ( - var i = 0, length_3 = this.children.length; - i < length_3; - i++ - ) { - var childOperation = this.children[i]; - childOperation.next(item, key, owner); - if (!childOperation.keep) { - keep = false; - } - if (childOperation.done) { + for (var i = 0, length_3 = this.children.length; i < length_3; i++) { + var childOperation = this.children[i]; + childOperation.next(item, key, owner); if (!childOperation.keep) { - break; + keep = false; + } + if (childOperation.done) { + if (!childOperation.keep) { + break; + } + } + else { + done = false; } - } else { - done = false; - } } this.done = done; this.keep = keep; - }; - return GroupOperation; - })(BaseOperation); - var NamedGroupOperation = /** @class */ (function (_super) { - __extends(NamedGroupOperation, _super); - function NamedGroupOperation( - params, - owneryQuery, - options, - children, - name - ) { - var _this = - _super.call(this, params, owneryQuery, options, children) || this; + }; + return GroupOperation; + }(BaseOperation)); + var NamedGroupOperation = /** @class */ (function (_super) { + __extends(NamedGroupOperation, _super); + function NamedGroupOperation(params, owneryQuery, options, children, name) { + var _this = _super.call(this, params, owneryQuery, options, children) || this; _this.name = name; return _this; - } - return NamedGroupOperation; - })(GroupOperation); - var QueryOperation = /** @class */ (function (_super) { - __extends(QueryOperation, _super); - function QueryOperation() { - return (_super !== null && _super.apply(this, arguments)) || this; - } - /** - */ - QueryOperation.prototype.next = function (item, key, parent) { + } + return NamedGroupOperation; + }(GroupOperation)); + var QueryOperation = /** @class */ (function (_super) { + __extends(QueryOperation, _super); + function QueryOperation() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + */ + QueryOperation.prototype.next = function (item, key, parent) { this.childrenNext(item, key, parent); - }; - return QueryOperation; - })(GroupOperation); - var NestedOperation = /** @class */ (function (_super) { - __extends(NestedOperation, _super); - function NestedOperation( - keyPath, - params, - owneryQuery, - options, - children - ) { - var _this = - _super.call(this, params, owneryQuery, options, children) || this; + }; + return QueryOperation; + }(GroupOperation)); + var NestedOperation = /** @class */ (function (_super) { + __extends(NestedOperation, _super); + function NestedOperation(keyPath, params, owneryQuery, options, children) { + var _this = _super.call(this, params, owneryQuery, options, children) || this; _this.keyPath = keyPath; /** */ _this._nextNestedValue = function (value, key, owner) { - _this.childrenNext(value, key, owner); - return !_this.done; + _this.childrenNext(value, key, owner); + return !_this.done; }; return _this; - } - /** - */ - NestedOperation.prototype.next = function (item, key, parent) { - walkKeyPathValues( - item, - this.keyPath, - this._nextNestedValue, - 0, - key, - parent - ); - }; - return NestedOperation; - })(GroupOperation); - var createTester = function (a, compare) { - if (a instanceof Function) { + } + /** + */ + NestedOperation.prototype.next = function (item, key, parent) { + walkKeyPathValues(item, this.keyPath, this._nextNestedValue, 0, key, parent); + }; + return NestedOperation; + }(GroupOperation)); + var createTester = function (a, compare) { + if (a instanceof Function) { return a; - } - if (a instanceof RegExp) { + } + if (a instanceof RegExp) { return function (b) { - var result = typeof b === "string" && a.test(b); - a.lastIndex = 0; - return result; + var result = typeof b === "string" && a.test(b); + a.lastIndex = 0; + return result; }; - } - var comparableA = comparable(a); - return function (b) { - return compare(comparableA, comparable(b)); - }; - }; - var EqualsOperation = /** @class */ (function (_super) { - __extends(EqualsOperation, _super); - function EqualsOperation() { - return (_super !== null && _super.apply(this, arguments)) || this; - } - EqualsOperation.prototype.init = function () { + } + var comparableA = comparable(a); + return function (b) { return compare(comparableA, comparable(b)); }; + }; + var EqualsOperation = /** @class */ (function (_super) { + __extends(EqualsOperation, _super); + function EqualsOperation() { + return _super !== null && _super.apply(this, arguments) || this; + } + EqualsOperation.prototype.init = function () { this._test = createTester(this.params, this.options.compare); - }; - EqualsOperation.prototype.next = function (item, key, parent) { + }; + EqualsOperation.prototype.next = function (item, key, parent) { if (!Array.isArray(parent) || parent.hasOwnProperty(key)) { - if (this._test(item, key, parent)) { - this.done = true; - this.keep = true; - } + if (this._test(item, key, parent)) { + this.done = true; + this.keep = true; + } } - }; - return EqualsOperation; - })(BaseOperation); - var createEqualsOperation = function (params, owneryQuery, options) { - return new EqualsOperation(params, owneryQuery, options); }; - var NopeOperation = /** @class */ (function (_super) { - __extends(NopeOperation, _super); - function NopeOperation() { - return (_super !== null && _super.apply(this, arguments)) || this; - } - NopeOperation.prototype.next = function () { + return EqualsOperation; + }(BaseOperation)); + var createEqualsOperation = function (params, owneryQuery, options) { return new EqualsOperation(params, owneryQuery, options); }; + var NopeOperation = /** @class */ (function (_super) { + __extends(NopeOperation, _super); + function NopeOperation() { + return _super !== null && _super.apply(this, arguments) || this; + } + NopeOperation.prototype.next = function () { this.done = true; this.keep = false; - }; - return NopeOperation; - })(BaseOperation); - var numericalOperationCreator = function (createNumericalOperation) { - return function (params, owneryQuery, options, name) { - if (params == null) { - return new NopeOperation(params, owneryQuery, options); - } - return createNumericalOperation(params, owneryQuery, options, name); - }; }; - var numericalOperation = function (createTester) { - return numericalOperationCreator(function ( - params, - owneryQuery, - options - ) { + return NopeOperation; + }(BaseOperation)); + var numericalOperationCreator = function (createNumericalOperation) { return function (params, owneryQuery, options, name) { + if (params == null) { + return new NopeOperation(params, owneryQuery, options); + } + return createNumericalOperation(params, owneryQuery, options, name); + }; }; + var numericalOperation = function (createTester) { + return numericalOperationCreator(function (params, owneryQuery, options) { var typeofParams = typeof comparable(params); var test = createTester(params); - return new EqualsOperation( - function (b) { + return new EqualsOperation(function (b) { return typeof comparable(b) === typeofParams && test(b); - }, - owneryQuery, - options - ); - }); - }; - var createNamedOperation = function ( - name, - params, - parentQuery, - options - ) { - var operationCreator = options.operations[name]; - if (!operationCreator) { + }, owneryQuery, options); + }); + }; + var createNamedOperation = function (name, params, parentQuery, options) { + var operationCreator = options.operations[name]; + if (!operationCreator) { throw new Error("Unsupported operation: " + name); - } - return operationCreator(params, parentQuery, options, name); - }; - var containsOperation = function (query) { - for (var key in query) { - if (key.charAt(0) === "$") return true; - } - return false; - }; - var createNestedOperation = function ( - keyPath, - nestedQuery, - owneryQuery, - options - ) { - if (containsOperation(nestedQuery)) { - var _a = createQueryOperations(nestedQuery, options), - selfOperations = _a[0], - nestedOperations = _a[1]; + } + return operationCreator(params, parentQuery, options, name); + }; + var containsOperation = function (query) { + for (var key in query) { + if (key.charAt(0) === "$") + return true; + } + return false; + }; + var createNestedOperation = function (keyPath, nestedQuery, owneryQuery, options) { + if (containsOperation(nestedQuery)) { + var _a = createQueryOperations(nestedQuery, options), selfOperations = _a[0], nestedOperations = _a[1]; if (nestedOperations.length) { - throw new Error( - "Property queries must contain only operations, or exact objects." - ); + throw new Error("Property queries must contain only operations, or exact objects."); } - return new NestedOperation( - keyPath, - nestedQuery, - owneryQuery, - options, - selfOperations - ); - } - return new NestedOperation( - keyPath, - nestedQuery, - owneryQuery, - options, - [new EqualsOperation(nestedQuery, owneryQuery, options)] - ); - }; - var createQueryOperation = function (query, owneryQuery, _a) { - if (owneryQuery === void 0) { - owneryQuery = null; - } - var _b = _a === void 0 ? {} : _a, - compare = _b.compare, - operations = _b.operations; - var options = { + return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, selfOperations); + } + return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, [ + new EqualsOperation(nestedQuery, owneryQuery, options) + ]); + }; + var createQueryOperation = function (query, owneryQuery, _a) { + if (owneryQuery === void 0) { owneryQuery = null; } + var _b = _a === void 0 ? {} : _a, compare = _b.compare, operations = _b.operations; + var options = { compare: compare || equals, - operations: Object.assign({}, operations || {}), - }; - var _c = createQueryOperations(query, options), - selfOperations = _c[0], - nestedOperations = _c[1]; - var ops = []; - if (selfOperations.length) { - ops.push( - new NestedOperation( - [], - query, - owneryQuery, - options, - selfOperations - ) - ); - } - ops.push.apply(ops, nestedOperations); - if (ops.length === 1) { - return ops[0]; - } - return new QueryOperation(query, owneryQuery, options, ops); + operations: Object.assign({}, operations || {}) }; - var createQueryOperations = function (query, options) { - var selfOperations = []; - var nestedOperations = []; - if (!isVanillaObject(query)) { + var _c = createQueryOperations(query, options), selfOperations = _c[0], nestedOperations = _c[1]; + var ops = []; + if (selfOperations.length) { + ops.push(new NestedOperation([], query, owneryQuery, options, selfOperations)); + } + ops.push.apply(ops, nestedOperations); + if (ops.length === 1) { + return ops[0]; + } + return new QueryOperation(query, owneryQuery, options, ops); + }; + var createQueryOperations = function (query, options) { + var selfOperations = []; + var nestedOperations = []; + if (!isVanillaObject(query)) { selfOperations.push(new EqualsOperation(query, query, options)); return [selfOperations, nestedOperations]; - } - for (var key in query) { + } + for (var key in query) { if (key.charAt(0) === "$") { - var op = createNamedOperation(key, query[key], query, options); - // probably just a flag for another operation (like $options) - if (op != null) { - selfOperations.push(op); - } - } else { - nestedOperations.push( - createNestedOperation( - key.split("."), - query[key], - query, - options - ) - ); + var op = createNamedOperation(key, query[key], query, options); + // probably just a flag for another operation (like $options) + if (op != null) { + selfOperations.push(op); + } } - } - return [selfOperations, nestedOperations]; - }; - var createOperationTester = function (operation) { - return function (item, key, owner) { - operation.reset(); - operation.next(item, key, owner); - return operation.keep; - }; - }; - var createQueryTester = function (query, options) { - if (options === void 0) { - options = {}; - } - return createOperationTester( - createQueryOperation(query, null, options) - ); - }; + else { + nestedOperations.push(createNestedOperation(key.split("."), query[key], query, options)); + } + } + return [selfOperations, nestedOperations]; + }; + var createOperationTester = function (operation) { return function (item, key, owner) { + operation.reset(); + operation.next(item, key, owner); + return operation.keep; + }; }; + var createQueryTester = function (query, options) { + if (options === void 0) { options = {}; } + return createOperationTester(createQueryOperation(query, null, options)); + }; - var $Ne = /** @class */ (function (_super) { - __extends($Ne, _super); - function $Ne() { - return (_super !== null && _super.apply(this, arguments)) || this; - } - $Ne.prototype.init = function () { + var $Ne = /** @class */ (function (_super) { + __extends($Ne, _super); + function $Ne() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Ne.prototype.init = function () { this._test = createTester(this.params, this.options.compare); - }; - $Ne.prototype.reset = function () { + }; + $Ne.prototype.reset = function () { _super.prototype.reset.call(this); this.keep = true; - }; - $Ne.prototype.next = function (item) { + }; + $Ne.prototype.next = function (item) { if (this._test(item)) { - this.done = true; - this.keep = false; + this.done = true; + this.keep = false; } - }; - return $Ne; - })(NamedBaseOperation); - // https://docs.mongodb.com/manual/reference/operator/query/elemMatch/ - var $ElemMatch = /** @class */ (function (_super) { - __extends($ElemMatch, _super); - function $ElemMatch() { - return (_super !== null && _super.apply(this, arguments)) || this; - } - $ElemMatch.prototype.init = function () { - this._queryOperation = createQueryOperation( - this.params, - this.owneryQuery, - this.options - ); - }; - $ElemMatch.prototype.reset = function () { + }; + return $Ne; + }(NamedBaseOperation)); + // https://docs.mongodb.com/manual/reference/operator/query/elemMatch/ + var $ElemMatch = /** @class */ (function (_super) { + __extends($ElemMatch, _super); + function $ElemMatch() { + return _super !== null && _super.apply(this, arguments) || this; + } + $ElemMatch.prototype.init = function () { + this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options); + }; + $ElemMatch.prototype.reset = function () { _super.prototype.reset.call(this); this._queryOperation.reset(); - }; - $ElemMatch.prototype.next = function (item) { + }; + $ElemMatch.prototype.next = function (item) { if (isArray(item)) { - for (var i = 0, length_1 = item.length; i < length_1; i++) { - // reset query operation since item being tested needs to pass _all_ query - // operations for it to be a success - this._queryOperation.reset(); - // check item - this._queryOperation.next(item[i], i, item); - this.keep = this.keep || this._queryOperation.keep; - } - this.done = true; - } else { - this.done = false; - this.keep = false; + for (var i = 0, length_1 = item.length; i < length_1; i++) { + // reset query operation since item being tested needs to pass _all_ query + // operations for it to be a success + this._queryOperation.reset(); + // check item + this._queryOperation.next(item[i], i, item); + this.keep = this.keep || this._queryOperation.keep; + } + this.done = true; } - }; - return $ElemMatch; - })(NamedBaseOperation); - var $Not = /** @class */ (function (_super) { - __extends($Not, _super); - function $Not() { - return (_super !== null && _super.apply(this, arguments)) || this; - } - $Not.prototype.init = function () { - this._queryOperation = createQueryOperation( - this.params, - this.owneryQuery, - this.options - ); - }; - $Not.prototype.reset = function () { + else { + this.done = false; + this.keep = false; + } + }; + return $ElemMatch; + }(NamedBaseOperation)); + var $Not = /** @class */ (function (_super) { + __extends($Not, _super); + function $Not() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Not.prototype.init = function () { + this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options); + }; + $Not.prototype.reset = function () { this._queryOperation.reset(); - }; - $Not.prototype.next = function (item, key, owner) { + }; + $Not.prototype.next = function (item, key, owner) { this._queryOperation.next(item, key, owner); this.done = this._queryOperation.done; this.keep = !this._queryOperation.keep; - }; - return $Not; - })(NamedBaseOperation); - var $Size = /** @class */ (function (_super) { - __extends($Size, _super); - function $Size() { - return (_super !== null && _super.apply(this, arguments)) || this; - } - $Size.prototype.init = function () {}; - $Size.prototype.next = function (item) { + }; + return $Not; + }(NamedBaseOperation)); + var $Size = /** @class */ (function (_super) { + __extends($Size, _super); + function $Size() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Size.prototype.init = function () { }; + $Size.prototype.next = function (item) { if (isArray(item) && item.length === this.params) { - this.done = true; - this.keep = true; + this.done = true; + this.keep = true; } // if (parent && parent.length === this.params) { // this.done = true; // this.keep = true; // } - }; - return $Size; - })(NamedBaseOperation); - var $Or = /** @class */ (function (_super) { - __extends($Or, _super); - function $Or() { - return (_super !== null && _super.apply(this, arguments)) || this; - } - $Or.prototype.init = function () { + }; + return $Size; + }(NamedBaseOperation)); + var $Or = /** @class */ (function (_super) { + __extends($Or, _super); + function $Or() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Or.prototype.init = function () { var _this = this; this._ops = this.params.map(function (op) { - return createQueryOperation(op, null, _this.options); + return createQueryOperation(op, null, _this.options); }); - }; - $Or.prototype.reset = function () { + }; + $Or.prototype.reset = function () { this.done = false; this.keep = false; for (var i = 0, length_2 = this._ops.length; i < length_2; i++) { - this._ops[i].reset(); + this._ops[i].reset(); } - }; - $Or.prototype.next = function (item, key, owner) { + }; + $Or.prototype.next = function (item, key, owner) { var done = false; var success = false; for (var i = 0, length_3 = this._ops.length; i < length_3; i++) { - var op = this._ops[i]; - op.next(item, key, owner); - if (op.keep) { - done = true; - success = op.keep; - break; - } + var op = this._ops[i]; + op.next(item, key, owner); + if (op.keep) { + done = true; + success = op.keep; + break; + } } this.keep = success; this.done = done; - }; - return $Or; - })(NamedBaseOperation); - var $Nor = /** @class */ (function (_super) { - __extends($Nor, _super); - function $Nor() { - return (_super !== null && _super.apply(this, arguments)) || this; - } - $Nor.prototype.next = function (item, key, owner) { + }; + return $Or; + }(NamedBaseOperation)); + var $Nor = /** @class */ (function (_super) { + __extends($Nor, _super); + function $Nor() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Nor.prototype.next = function (item, key, owner) { _super.prototype.next.call(this, item, key, owner); this.keep = !this.keep; - }; - return $Nor; - })($Or); - var $In = /** @class */ (function (_super) { - __extends($In, _super); - function $In() { - return (_super !== null && _super.apply(this, arguments)) || this; - } - $In.prototype.init = function () { + }; + return $Nor; + }($Or)); + var $In = /** @class */ (function (_super) { + __extends($In, _super); + function $In() { + return _super !== null && _super.apply(this, arguments) || this; + } + $In.prototype.init = function () { var _this = this; this._testers = this.params.map(function (value) { - if (containsOperation(value)) { - throw new Error( - "cannot nest $ under " + _this.constructor.name.toLowerCase() - ); - } - return createTester(value, _this.options.compare); + if (containsOperation(value)) { + throw new Error("cannot nest $ under " + _this.constructor.name.toLowerCase()); + } + return createTester(value, _this.options.compare); }); - }; - $In.prototype.next = function (item, key, owner) { + }; + $In.prototype.next = function (item, key, owner) { var done = false; var success = false; - for ( - var i = 0, length_4 = this._testers.length; - i < length_4; - i++ - ) { - var test = this._testers[i]; - if (test(item)) { - done = true; - success = true; - break; - } + for (var i = 0, length_4 = this._testers.length; i < length_4; i++) { + var test = this._testers[i]; + if (test(item)) { + done = true; + success = true; + break; + } } this.keep = success; this.done = done; - }; - return $In; - })(NamedBaseOperation); - var $Nin = /** @class */ (function (_super) { - __extends($Nin, _super); - function $Nin() { - return (_super !== null && _super.apply(this, arguments)) || this; - } - $Nin.prototype.next = function (item, key, owner) { + }; + return $In; + }(NamedBaseOperation)); + var $Nin = /** @class */ (function (_super) { + __extends($Nin, _super); + function $Nin() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Nin.prototype.next = function (item, key, owner) { _super.prototype.next.call(this, item, key, owner); this.keep = !this.keep; - }; - return $Nin; - })($In); - var $Exists = /** @class */ (function (_super) { - __extends($Exists, _super); - function $Exists() { - return (_super !== null && _super.apply(this, arguments)) || this; - } - $Exists.prototype.next = function (item, key, owner) { + }; + return $Nin; + }($In)); + var $Exists = /** @class */ (function (_super) { + __extends($Exists, _super); + function $Exists() { + return _super !== null && _super.apply(this, arguments) || this; + } + $Exists.prototype.next = function (item, key, owner) { if (owner.hasOwnProperty(key) === this.params) { - this.done = true; - this.keep = true; + this.done = true; + this.keep = true; } - }; - return $Exists; - })(NamedBaseOperation); - var $And = /** @class */ (function (_super) { - __extends($And, _super); - function $And(params, owneryQuery, options, name) { - return ( - _super.call( - this, - params, - owneryQuery, - options, - params.map(function (query) { - return createQueryOperation(query, owneryQuery, options); - }), - name - ) || this - ); - } - $And.prototype.next = function (item, key, owner) { - this.childrenNext(item, key, owner); - }; - return $And; - })(NamedGroupOperation); - var $eq = function (params, owneryQuery, options) { - return new EqualsOperation(params, owneryQuery, options); - }; - var $ne = function (params, owneryQuery, options, name) { - return new $Ne(params, owneryQuery, options, name); - }; - var $or = function (params, owneryQuery, options, name) { - return new $Or(params, owneryQuery, options, name); - }; - var $nor = function (params, owneryQuery, options, name) { - return new $Nor(params, owneryQuery, options, name); - }; - var $elemMatch = function (params, owneryQuery, options, name) { - return new $ElemMatch(params, owneryQuery, options, name); - }; - var $nin = function (params, owneryQuery, options, name) { - return new $Nin(params, owneryQuery, options, name); - }; - var $in = function (params, owneryQuery, options, name) { - return new $In(params, owneryQuery, options, name); - }; - var $lt = numericalOperation(function (params) { - return function (b) { - return b < params; - }; - }); - var $lte = numericalOperation(function (params) { - return function (b) { - return b <= params; - }; - }); - var $gt = numericalOperation(function (params) { - return function (b) { - return b > params; - }; - }); - var $gte = numericalOperation(function (params) { - return function (b) { - return b >= params; - }; - }); - var $mod = function (_a, owneryQuery, options) { - var mod = _a[0], - equalsValue = _a[1]; - return new EqualsOperation( - function (b) { - return comparable(b) % mod === equalsValue; - }, - owneryQuery, - options - ); - }; - var $exists = function (params, owneryQuery, options, name) { - return new $Exists(params, owneryQuery, options, name); }; - var $regex = function (pattern, owneryQuery, options) { - return new EqualsOperation( - new RegExp(pattern, owneryQuery.$options), - owneryQuery, - options - ); - }; - var $not = function (params, owneryQuery, options, name) { - return new $Not(params, owneryQuery, options, name); - }; - var typeAliases = { - number: function (v) { - return typeof v === "number"; - }, - string: function (v) { - return typeof v === "string"; - }, - bool: function (v) { - return typeof v === "boolean"; - }, - array: function (v) { - return Array.isArray(v); - }, - null: function (v) { - return v === null; - }, - timestamp: function (v) { - return v instanceof Date; - }, + return $Exists; + }(NamedBaseOperation)); + var $And = /** @class */ (function (_super) { + __extends($And, _super); + function $And(params, owneryQuery, options, name) { + return _super.call(this, params, owneryQuery, options, params.map(function (query) { return createQueryOperation(query, owneryQuery, options); }), name) || this; + } + $And.prototype.next = function (item, key, owner) { + this.childrenNext(item, key, owner); }; - var $type = function (clazz, owneryQuery, options) { - return new EqualsOperation( - function (b) { - if (typeof clazz === "string") { + return $And; + }(NamedGroupOperation)); + var $eq = function (params, owneryQuery, options) { + return new EqualsOperation(params, owneryQuery, options); + }; + var $ne = function (params, owneryQuery, options, name) { return new $Ne(params, owneryQuery, options, name); }; + var $or = function (params, owneryQuery, options, name) { return new $Or(params, owneryQuery, options, name); }; + var $nor = function (params, owneryQuery, options, name) { return new $Nor(params, owneryQuery, options, name); }; + var $elemMatch = function (params, owneryQuery, options, name) { return new $ElemMatch(params, owneryQuery, options, name); }; + var $nin = function (params, owneryQuery, options, name) { return new $Nin(params, owneryQuery, options, name); }; + var $in = function (params, owneryQuery, options, name) { return new $In(params, owneryQuery, options, name); }; + var $lt = numericalOperation(function (params) { return function (b) { return b < params; }; }); + var $lte = numericalOperation(function (params) { return function (b) { return b <= params; }; }); + var $gt = numericalOperation(function (params) { return function (b) { return b > params; }; }); + var $gte = numericalOperation(function (params) { return function (b) { return b >= params; }; }); + var $mod = function (_a, owneryQuery, options) { + var mod = _a[0], equalsValue = _a[1]; + return new EqualsOperation(function (b) { return comparable(b) % mod === equalsValue; }, owneryQuery, options); + }; + var $exists = function (params, owneryQuery, options, name) { return new $Exists(params, owneryQuery, options, name); }; + var $regex = function (pattern, owneryQuery, options) { + return new EqualsOperation(new RegExp(pattern, owneryQuery.$options), owneryQuery, options); + }; + var $not = function (params, owneryQuery, options, name) { return new $Not(params, owneryQuery, options, name); }; + var typeAliases = { + number: function (v) { return typeof v === "number"; }, + string: function (v) { return typeof v === "string"; }, + bool: function (v) { return typeof v === "boolean"; }, + array: function (v) { return Array.isArray(v); }, + null: function (v) { return v === null; }, + timestamp: function (v) { return v instanceof Date; } + }; + var $type = function (clazz, owneryQuery, options) { + return new EqualsOperation(function (b) { + if (typeof clazz === "string") { if (!typeAliases[clazz]) { - throw new Error("Type alias does not exist"); + throw new Error("Type alias does not exist"); } return typeAliases[clazz](b); - } - return b != null - ? b instanceof clazz || b.constructor === clazz - : false; - }, - owneryQuery, - options - ); - }; - var $and = function (params, ownerQuery, options, name) { - return new $And(params, ownerQuery, options, name); - }; - var $all = $and; - var $size = function (params, ownerQuery, options) { - return new $Size(params, ownerQuery, options, "$size"); - }; - var $options = function () { - return null; - }; - var $where = function (params, ownerQuery, options) { - var test; - if (isFunction(params)) { + } + return b != null ? b instanceof clazz || b.constructor === clazz : false; + }, owneryQuery, options); + }; + var $and = function (params, ownerQuery, options, name) { return new $And(params, ownerQuery, options, name); }; + var $all = $and; + var $size = function (params, ownerQuery, options) { return new $Size(params, ownerQuery, options, "$size"); }; + var $options = function () { return null; }; + var $where = function (params, ownerQuery, options) { + var test; + if (isFunction(params)) { test = params; - } else if (!process.env.CSP_ENABLED) { + } + else if (!process.env.CSP_ENABLED) { test = new Function("obj", "return " + params); - } else { - throw new Error( - 'In CSP mode, sift does not support strings in "$where" condition' - ); - } - return new EqualsOperation( - function (b) { - return test.bind(b)(b); - }, - ownerQuery, - options - ); - }; + } + else { + throw new Error("In CSP mode, sift does not support strings in \"$where\" condition"); + } + return new EqualsOperation(function (b) { return test.bind(b)(b); }, ownerQuery, options); + }; - var defaultOperations = /*#__PURE__*/ Object.freeze({ - __proto__: null, - $Size: $Size, - $eq: $eq, - $ne: $ne, - $or: $or, - $nor: $nor, - $elemMatch: $elemMatch, - $nin: $nin, - $in: $in, - $lt: $lt, - $lte: $lte, - $gt: $gt, - $gte: $gte, - $mod: $mod, - $exists: $exists, - $regex: $regex, - $not: $not, - $type: $type, - $and: $and, - $all: $all, - $size: $size, - $options: $options, - $where: $where, - }); + var defaultOperations = /*#__PURE__*/Object.freeze({ + __proto__: null, + $Size: $Size, + $eq: $eq, + $ne: $ne, + $or: $or, + $nor: $nor, + $elemMatch: $elemMatch, + $nin: $nin, + $in: $in, + $lt: $lt, + $lte: $lte, + $gt: $gt, + $gte: $gte, + $mod: $mod, + $exists: $exists, + $regex: $regex, + $not: $not, + $type: $type, + $and: $and, + $all: $all, + $size: $size, + $options: $options, + $where: $where + }); - var createDefaultQueryOperation = function (query, ownerQuery, _a) { - var _b = _a === void 0 ? {} : _a, - compare = _b.compare, - operations = _b.operations; - return createQueryOperation(query, ownerQuery, { + var createDefaultQueryOperation = function (query, ownerQuery, _a) { + var _b = _a === void 0 ? {} : _a, compare = _b.compare, operations = _b.operations; + return createQueryOperation(query, ownerQuery, { compare: compare, - operations: Object.assign({}, defaultOperations, operations || {}), - }); - }; - var createDefaultQueryTester = function (query, options) { - if (options === void 0) { - options = {}; - } - var op = createDefaultQueryOperation(query, null, options); - return createOperationTester(op); - }; - - exports.$Size = $Size; - exports.$all = $all; - exports.$and = $and; - exports.$elemMatch = $elemMatch; - exports.$eq = $eq; - exports.$exists = $exists; - exports.$gt = $gt; - exports.$gte = $gte; - exports.$in = $in; - exports.$lt = $lt; - exports.$lte = $lte; - exports.$mod = $mod; - exports.$ne = $ne; - exports.$nin = $nin; - exports.$nor = $nor; - exports.$not = $not; - exports.$options = $options; - exports.$or = $or; - exports.$regex = $regex; - exports.$size = $size; - exports.$type = $type; - exports.$where = $where; - exports.EqualsOperation = EqualsOperation; - exports.createDefaultQueryOperation = createDefaultQueryOperation; - exports.createEqualsOperation = createEqualsOperation; - exports.createOperationTester = createOperationTester; - exports.createQueryOperation = createQueryOperation; - exports.createQueryTester = createQueryTester; - exports.default = createDefaultQueryTester; - - Object.defineProperty(exports, "__esModule", { value: true }); - }); - //# sourceMappingURL=index.js.map - - /***/ - }, - - /***/ 9889: /***/ (module) => { - /** - * An Array.prototype.slice.call(arguments) alternative - * - * @param {Object} args something with a length - * @param {Number} slice - * @param {Number} sliceEnd - * @api public - */ - - module.exports = function (args, slice, sliceEnd) { - var ret = []; - var len = args.length; - - if (0 === len) return ret; + operations: Object.assign({}, defaultOperations, operations || {}) + }); + }; + var createDefaultQueryTester = function (query, options) { + if (options === void 0) { options = {}; } + var op = createDefaultQueryOperation(query, null, options); + return createOperationTester(op); + }; - var start = slice < 0 ? Math.max(0, slice + len) : slice || 0; + exports.$Size = $Size; + exports.$all = $all; + exports.$and = $and; + exports.$elemMatch = $elemMatch; + exports.$eq = $eq; + exports.$exists = $exists; + exports.$gt = $gt; + exports.$gte = $gte; + exports.$in = $in; + exports.$lt = $lt; + exports.$lte = $lte; + exports.$mod = $mod; + exports.$ne = $ne; + exports.$nin = $nin; + exports.$nor = $nor; + exports.$not = $not; + exports.$options = $options; + exports.$or = $or; + exports.$regex = $regex; + exports.$size = $size; + exports.$type = $type; + exports.$where = $where; + exports.EqualsOperation = EqualsOperation; + exports.createDefaultQueryOperation = createDefaultQueryOperation; + exports.createEqualsOperation = createEqualsOperation; + exports.createOperationTester = createOperationTester; + exports.createQueryOperation = createQueryOperation; + exports.createQueryTester = createQueryTester; + exports.default = createDefaultQueryTester; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 9889: +/***/ ((module) => { + + +/** + * An Array.prototype.slice.call(arguments) alternative + * + * @param {Object} args something with a length + * @param {Number} slice + * @param {Number} sliceEnd + * @api public + */ - if (sliceEnd !== undefined) { - len = sliceEnd < 0 ? sliceEnd + len : sliceEnd; - } +module.exports = function (args, slice, sliceEnd) { + var ret = []; + var len = args.length; - while (len-- > start) { - ret[len - start] = args[len]; - } + if (0 === len) return ret; - return ret; - }; + var start = slice < 0 + ? Math.max(0, slice + len) + : slice || 0; - /***/ - }, + if (sliceEnd !== undefined) { + len = sliceEnd < 0 + ? sliceEnd + len + : sliceEnd + } - /***/ 1453: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - var pager = __nccwpck_require__(7147); + while (len-- > start) { + ret[len - start] = args[len]; + } - module.exports = Bitfield; + return ret; +} - 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"); +/***/ 1453: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this._trackUpdates = !!opts.trackUpdates; - this._pageMask = this.pageSize - 1; +var pager = __nccwpck_require__(7147) - 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; - } - } +module.exports = Bitfield - Bitfield.prototype.get = function (i) { - var o = i & 7; - var j = (i - o) / 8; +function Bitfield (opts) { + if (!(this instanceof Bitfield)) return new Bitfield(opts) + if (!opts) opts = {} + if (Buffer.isBuffer(opts)) opts = {buffer: opts} - return !!(this.getByte(j) & (128 >> o)); - }; + this.pageOffset = opts.pageOffset || 0 + this.pageSize = opts.pageSize || 1024 + this.pages = opts.pages || pager(this.pageSize) - Bitfield.prototype.getByte = function (i) { - var o = i & this._pageMask; - var j = (i - o) / this.pageSize; - var page = this.pages.get(j, true); + this.byteLength = this.pages.length * this.pageSize + this.length = 8 * this.byteLength - return page ? page.buffer[o + this.pageOffset] : 0; - }; + if (!powerOfTwo(this.pageSize)) throw new Error('The page size should be a power of two') - Bitfield.prototype.set = function (i, v) { - var o = i & 7; - var j = (i - o) / 8; - var b = this.getByte(j); + this._trackUpdates = !!opts.trackUpdates + this._pageMask = this.pageSize - 1 - return this.setByte(j, v ? b | (128 >> o) : b & (255 ^ (128 >> o))); - }; + 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.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 - ); - } +Bitfield.prototype.get = function (i) { + var o = i & 7 + var j = (i - o) / 8 - return all; - }; + return !!(this.getByte(j) & (128 >> o)) +} - Bitfield.prototype.setByte = function (i, b) { - var o = i & this._pageMask; - var j = (i - o) / this.pageSize; - var page = this.pages.get(j, false); +Bitfield.prototype.getByte = function (i) { + var o = i & this._pageMask + var j = (i - o) / this.pageSize + var page = this.pages.get(j, true) - o += this.pageOffset; + return page ? page.buffer[o + this.pageOffset] : 0 +} - if (page.buffer[o] === b) return false; - page.buffer[o] = b; +Bitfield.prototype.set = function (i, v) { + var o = i & 7 + var j = (i - o) / 8 + var b = this.getByte(j) - if (i >= this.byteLength) { - this.byteLength = i + 1; - this.length = this.byteLength * 8; - } + return this.setByte(j, v ? b | (128 >> o) : b & (255 ^ (128 >> o))) +} - if (this._trackUpdates) this.pages.updated(page); +Bitfield.prototype.toBuffer = function () { + var all = alloc(this.pages.length * this.pageSize) - return true; - }; + 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) + } - function alloc(n) { - if (Buffer.alloc) return Buffer.alloc(n); - var b = new Buffer(n); - b.fill(0); - return b; - } + return all +} - function powerOfTwo(x) { - return !(x & (x - 1)); - } +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 - /***/ 9318: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - "use strict"; - - const os = __nccwpck_require__(2087); - const tty = __nccwpck_require__(3867); - const hasFlag = __nccwpck_require__(1621); - - const { env } = process; - - let forceColor; - if ( - hasFlag("no-color") || - hasFlag("no-colors") || - hasFlag("color=false") || - hasFlag("color=never") - ) { - forceColor = 0; - } else if ( - hasFlag("color") || - hasFlag("colors") || - hasFlag("color=true") || - hasFlag("color=always") - ) { - forceColor = 1; - } - - if ("FORCE_COLOR" in env) { - if (env.FORCE_COLOR === "true") { - forceColor = 1; - } else if (env.FORCE_COLOR === "false") { - forceColor = 0; - } else { - forceColor = - env.FORCE_COLOR.length === 0 - ? 1 - : Math.min(parseInt(env.FORCE_COLOR, 10), 3); - } - } + if (page.buffer[o] === b) return false + page.buffer[o] = b - function translateLevel(level) { - if (level === 0) { - return false; - } + if (i >= this.byteLength) { + this.byteLength = i + 1 + this.length = this.byteLength * 8 + } - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3, - }; - } + 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)) +} + + +/***/ }), + +/***/ 9318: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const os = __nccwpck_require__(2087); +const tty = __nccwpck_require__(3867); +const hasFlag = __nccwpck_require__(1621); + +const {env} = process; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + forceColor = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = 1; +} + +if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + if (env.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // 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(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', 'GITHUB_ACTIONS', 'BUILDKITE'].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; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) +}; + + +/***/ }), + +/***/ 1977: +/***/ ((module, __webpack_exports__, __nccwpck_require__) => { + +"use strict"; +__nccwpck_require__.a(module, async (__webpack_handle_async_dependencies__) => { +__nccwpck_require__.r(__webpack_exports__); +/* harmony import */ var mongoose__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(4740); +/* harmony import */ var mongoose__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__nccwpck_require__.n(mongoose__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _lib_api_mongoose_connection__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(1038); + + +await (0,_lib_api_mongoose_connection__WEBPACK_IMPORTED_MODULE_1__/* .connectToAppDb */ .K6)(); +await mongoose__WEBPACK_IMPORTED_MODULE_0___default().connection.db.dropDatabase(); +await (0,_lib_api_mongoose_connection__WEBPACK_IMPORTED_MODULE_1__/* .closeDbConnection */ .$n)(); + +__webpack_handle_async_dependencies__(); +}, 1); + +/***/ }), + +/***/ 1038: +/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => { + +"use strict"; + +// EXPORTS +__nccwpck_require__.d(__webpack_exports__, { + "$n": () => (/* binding */ closeDbConnection), + "K6": () => (/* binding */ connectToAppDb) +}); + +// UNUSED EXPORTS: connectToDb + +// EXTERNAL MODULE: ./node_modules/debug/src/index.js +var src = __nccwpck_require__(8237); +var src_default = /*#__PURE__*/__nccwpck_require__.n(src); +;// CONCATENATED MODULE: ./src/lib/debuggers.ts - function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; - } +const debugMongo = src_default()("vn:mongo"); +const debugAccount = src_default()("vn:account"); - if ( - hasFlag("color=16m") || - hasFlag("color=full") || - hasFlag("color=truecolor") - ) { - return 3; - } +// EXTERNAL MODULE: ./node_modules/mongoose/index.js +var mongoose = __nccwpck_require__(4740); +var mongoose_default = /*#__PURE__*/__nccwpck_require__.n(mongoose); +;// CONCATENATED MODULE: ./src/lib/api/mongoose/connection.ts - if (hasFlag("color=256")) { - return 2; - } - if (haveStream && !streamIsTTY && forceColor === undefined) { - return 0; +const globalNode = { + mongooseCache: undefined, + ...global, +}; +let mongooseCache = globalNode.mongooseCache; // shared promise, so "then" chains are called correctly for all code trying to connect (avoids race conditions) +if (!mongooseCache) { + globalNode.mongooseCache = { connectPromise: null }; + mongooseCache = globalNode.mongooseCache; +} +/** + * Connect to any mongo database + * + * NOTE: do not use directly, prefer using "connectToMainDb" + * @param mongoUri + * @param options + */ +const connectToDb = async (mongoUri, options) => { + if (mongooseCache === null || mongooseCache === void 0 ? void 0 : mongooseCache.connectPromise) { + debugMongo("Running connectToDb, already connected or connecting to Mongo, waiting for promise"); + await mongooseCache.connectPromise; + } + if (![1, 2].includes((mongoose_default()).connection.readyState)) { + debugMongo("Call mongoose connect"); + mongooseCache.connectPromise = mongoose_default().connect(mongoUri, { + ...(options || {}), + }); + // Wait for connection + await (mongooseCache === null || mongooseCache === void 0 ? void 0 : mongooseCache.connectPromise); + } +}; +/** + * Connect to the application main database + * + * Mongo URI is provided throught the MONGO_URI environment variable + */ +const connectToAppDb = async () => { + const mongoUri = process.env.MONGO_URI; + if (!mongoUri) + throw new Error("MONGO_URI env variable is not defined"); + const isLocalMongo = mongoUri.match(/localhost/); + try { + await connectToDb(mongoUri, { + // fail the seed early during development + serverSelectionTimeoutMS: isLocalMongo ? 3000 : undefined, + }); + } + catch (err) { + console.error(`\nCould not connect to Mongo database on URI ${mongoUri}.`); + if (isLocalMongo) { + console.error("Did you forget to run 'yarn run start:mongo'?\n"); } + console.error(err); + // rethrow + throw err; + } +}; +async function closeDbConnection() { + try { + await mongoose_default().connection.close(); + } + catch (err) { + // Catch locally error + console.error("Could not close mongoose connection"); + console.error(err); + throw err; + } +} - const min = forceColor || 0; - if (env.TERM === "dumb") { - return min; - } +/***/ }), - if (process.platform === "win32") { - // 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(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } +/***/ 9845: +/***/ ((module) => { - return 1; - } - - if ("CI" in env) { - if ( - [ - "TRAVIS", - "CIRCLECI", - "APPVEYOR", - "GITLAB_CI", - "GITHUB_ACTIONS", - "BUILDKITE", - ].some((sign) => sign in env) || - env.CI_NAME === "codeship" - ) { - return 1; - } +module.exports = eval("require")("bson-ext"); - 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; - } +/***/ 6330: +/***/ ((module) => { - if ("TERM_PROGRAM" in env) { - const version = parseInt( - (env.TERM_PROGRAM_VERSION || "").split(".")[0], - 10 - ); +module.exports = eval("require")("kerberos"); - 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; - } +/***/ 5764: +/***/ ((module) => { - if ("COLORTERM" in env) { - return 1; - } +module.exports = eval("require")("mongodb-client-encryption"); - return min; - } - function getSupportLevel(stream) { - const level = supportsColor(stream, stream && stream.isTTY); - return translateLevel(level); - } +/***/ }), - module.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))), - }; +/***/ 4399: +/***/ ((module) => { - /***/ - }, +module.exports = eval("require")("snappy"); - /***/ 5278: /***/ ( - module, - __unused_webpack_exports, - __nccwpck_require__ - ) => { - /** - * For Node.js, simply re-export the core `util.deprecate` function. - */ - module.exports = __nccwpck_require__(1669).deprecate; +/***/ }), - /***/ - }, +/***/ 8968: +/***/ ((module) => { - /***/ 1977: /***/ (module, __webpack_exports__, __nccwpck_require__) => { - "use strict"; - __nccwpck_require__.a( - module, - async (__webpack_handle_async_dependencies__) => { - __nccwpck_require__.r(__webpack_exports__); - /* harmony import */ var mongoose__WEBPACK_IMPORTED_MODULE_0__ = - __nccwpck_require__(4740); - /* harmony import */ var mongoose__WEBPACK_IMPORTED_MODULE_0___default = - /*#__PURE__*/ __nccwpck_require__.n( - mongoose__WEBPACK_IMPORTED_MODULE_0__ - ); - /* harmony import */ var _api_mongoose_connection__WEBPACK_IMPORTED_MODULE_1__ = - __nccwpck_require__(841); +module.exports = eval("require")("snappy/package.json"); - await (0, - _api_mongoose_connection__WEBPACK_IMPORTED_MODULE_1__ /* .connectToAppDb */.K6)(); - await mongoose__WEBPACK_IMPORTED_MODULE_0___default().connection.db.dropDatabase(); - await (0, - _api_mongoose_connection__WEBPACK_IMPORTED_MODULE_1__ /* .closeDbConnection */.$n)(); - __webpack_handle_async_dependencies__(); - }, - 1 - ); +/***/ }), - /***/ - }, +/***/ 4650: +/***/ ((module) => { - /***/ 841: /***/ ( - __unused_webpack_module, - __webpack_exports__, - __nccwpck_require__ - ) => { - "use strict"; - - // EXPORTS - __nccwpck_require__.d(__webpack_exports__, { - $n: () => /* binding */ closeDbConnection, - K6: () => /* binding */ connectToAppDb, - }); +"use strict"; +module.exports = JSON.parse('[[[0,44],4],[[45,46],2],[47,4],[[48,57],2],[[58,64],4],[65,1,"a"],[66,1,"b"],[67,1,"c"],[68,1,"d"],[69,1,"e"],[70,1,"f"],[71,1,"g"],[72,1,"h"],[73,1,"i"],[74,1,"j"],[75,1,"k"],[76,1,"l"],[77,1,"m"],[78,1,"n"],[79,1,"o"],[80,1,"p"],[81,1,"q"],[82,1,"r"],[83,1,"s"],[84,1,"t"],[85,1,"u"],[86,1,"v"],[87,1,"w"],[88,1,"x"],[89,1,"y"],[90,1,"z"],[[91,96],4],[[97,122],2],[[123,127],4],[[128,159],3],[160,5," "],[[161,167],2],[168,5," ̈"],[169,2],[170,1,"a"],[[171,172],2],[173,7],[174,2],[175,5," ̄"],[[176,177],2],[178,1,"2"],[179,1,"3"],[180,5," ́"],[181,1,"μ"],[182,2],[183,2],[184,5," ̧"],[185,1,"1"],[186,1,"o"],[187,2],[188,1,"1⁄4"],[189,1,"1⁄2"],[190,1,"3⁄4"],[191,2],[192,1,"à"],[193,1,"á"],[194,1,"â"],[195,1,"ã"],[196,1,"ä"],[197,1,"å"],[198,1,"æ"],[199,1,"ç"],[200,1,"è"],[201,1,"é"],[202,1,"ê"],[203,1,"ë"],[204,1,"ì"],[205,1,"í"],[206,1,"î"],[207,1,"ï"],[208,1,"ð"],[209,1,"ñ"],[210,1,"ò"],[211,1,"ó"],[212,1,"ô"],[213,1,"õ"],[214,1,"ö"],[215,2],[216,1,"ø"],[217,1,"ù"],[218,1,"ú"],[219,1,"û"],[220,1,"ü"],[221,1,"ý"],[222,1,"þ"],[223,6,"ss"],[[224,246],2],[247,2],[[248,255],2],[256,1,"ā"],[257,2],[258,1,"ă"],[259,2],[260,1,"ą"],[261,2],[262,1,"ć"],[263,2],[264,1,"ĉ"],[265,2],[266,1,"ċ"],[267,2],[268,1,"č"],[269,2],[270,1,"ď"],[271,2],[272,1,"đ"],[273,2],[274,1,"ē"],[275,2],[276,1,"ĕ"],[277,2],[278,1,"ė"],[279,2],[280,1,"ę"],[281,2],[282,1,"ě"],[283,2],[284,1,"ĝ"],[285,2],[286,1,"ğ"],[287,2],[288,1,"ġ"],[289,2],[290,1,"ģ"],[291,2],[292,1,"ĥ"],[293,2],[294,1,"ħ"],[295,2],[296,1,"ĩ"],[297,2],[298,1,"ī"],[299,2],[300,1,"ĭ"],[301,2],[302,1,"į"],[303,2],[304,1,"i̇"],[305,2],[[306,307],1,"ij"],[308,1,"ĵ"],[309,2],[310,1,"ķ"],[[311,312],2],[313,1,"ĺ"],[314,2],[315,1,"ļ"],[316,2],[317,1,"ľ"],[318,2],[[319,320],1,"l·"],[321,1,"ł"],[322,2],[323,1,"ń"],[324,2],[325,1,"ņ"],[326,2],[327,1,"ň"],[328,2],[329,1,"ʼn"],[330,1,"ŋ"],[331,2],[332,1,"ō"],[333,2],[334,1,"ŏ"],[335,2],[336,1,"ő"],[337,2],[338,1,"œ"],[339,2],[340,1,"ŕ"],[341,2],[342,1,"ŗ"],[343,2],[344,1,"ř"],[345,2],[346,1,"ś"],[347,2],[348,1,"ŝ"],[349,2],[350,1,"ş"],[351,2],[352,1,"š"],[353,2],[354,1,"ţ"],[355,2],[356,1,"ť"],[357,2],[358,1,"ŧ"],[359,2],[360,1,"ũ"],[361,2],[362,1,"ū"],[363,2],[364,1,"ŭ"],[365,2],[366,1,"ů"],[367,2],[368,1,"ű"],[369,2],[370,1,"ų"],[371,2],[372,1,"ŵ"],[373,2],[374,1,"ŷ"],[375,2],[376,1,"ÿ"],[377,1,"ź"],[378,2],[379,1,"ż"],[380,2],[381,1,"ž"],[382,2],[383,1,"s"],[384,2],[385,1,"ɓ"],[386,1,"ƃ"],[387,2],[388,1,"ƅ"],[389,2],[390,1,"ɔ"],[391,1,"ƈ"],[392,2],[393,1,"ɖ"],[394,1,"ɗ"],[395,1,"ƌ"],[[396,397],2],[398,1,"ǝ"],[399,1,"ə"],[400,1,"ɛ"],[401,1,"ƒ"],[402,2],[403,1,"ɠ"],[404,1,"ɣ"],[405,2],[406,1,"ɩ"],[407,1,"ɨ"],[408,1,"ƙ"],[[409,411],2],[412,1,"ɯ"],[413,1,"ɲ"],[414,2],[415,1,"ɵ"],[416,1,"ơ"],[417,2],[418,1,"ƣ"],[419,2],[420,1,"ƥ"],[421,2],[422,1,"ʀ"],[423,1,"ƨ"],[424,2],[425,1,"ʃ"],[[426,427],2],[428,1,"ƭ"],[429,2],[430,1,"ʈ"],[431,1,"ư"],[432,2],[433,1,"ʊ"],[434,1,"ʋ"],[435,1,"ƴ"],[436,2],[437,1,"ƶ"],[438,2],[439,1,"ʒ"],[440,1,"ƹ"],[[441,443],2],[444,1,"ƽ"],[[445,451],2],[[452,454],1,"dž"],[[455,457],1,"lj"],[[458,460],1,"nj"],[461,1,"ǎ"],[462,2],[463,1,"ǐ"],[464,2],[465,1,"ǒ"],[466,2],[467,1,"ǔ"],[468,2],[469,1,"ǖ"],[470,2],[471,1,"ǘ"],[472,2],[473,1,"ǚ"],[474,2],[475,1,"ǜ"],[[476,477],2],[478,1,"ǟ"],[479,2],[480,1,"ǡ"],[481,2],[482,1,"ǣ"],[483,2],[484,1,"ǥ"],[485,2],[486,1,"ǧ"],[487,2],[488,1,"ǩ"],[489,2],[490,1,"ǫ"],[491,2],[492,1,"ǭ"],[493,2],[494,1,"ǯ"],[[495,496],2],[[497,499],1,"dz"],[500,1,"ǵ"],[501,2],[502,1,"ƕ"],[503,1,"ƿ"],[504,1,"ǹ"],[505,2],[506,1,"ǻ"],[507,2],[508,1,"ǽ"],[509,2],[510,1,"ǿ"],[511,2],[512,1,"ȁ"],[513,2],[514,1,"ȃ"],[515,2],[516,1,"ȅ"],[517,2],[518,1,"ȇ"],[519,2],[520,1,"ȉ"],[521,2],[522,1,"ȋ"],[523,2],[524,1,"ȍ"],[525,2],[526,1,"ȏ"],[527,2],[528,1,"ȑ"],[529,2],[530,1,"ȓ"],[531,2],[532,1,"ȕ"],[533,2],[534,1,"ȗ"],[535,2],[536,1,"ș"],[537,2],[538,1,"ț"],[539,2],[540,1,"ȝ"],[541,2],[542,1,"ȟ"],[543,2],[544,1,"ƞ"],[545,2],[546,1,"ȣ"],[547,2],[548,1,"ȥ"],[549,2],[550,1,"ȧ"],[551,2],[552,1,"ȩ"],[553,2],[554,1,"ȫ"],[555,2],[556,1,"ȭ"],[557,2],[558,1,"ȯ"],[559,2],[560,1,"ȱ"],[561,2],[562,1,"ȳ"],[563,2],[[564,566],2],[[567,569],2],[570,1,"ⱥ"],[571,1,"ȼ"],[572,2],[573,1,"ƚ"],[574,1,"ⱦ"],[[575,576],2],[577,1,"ɂ"],[578,2],[579,1,"ƀ"],[580,1,"ʉ"],[581,1,"ʌ"],[582,1,"ɇ"],[583,2],[584,1,"ɉ"],[585,2],[586,1,"ɋ"],[587,2],[588,1,"ɍ"],[589,2],[590,1,"ɏ"],[591,2],[[592,680],2],[[681,685],2],[[686,687],2],[688,1,"h"],[689,1,"ɦ"],[690,1,"j"],[691,1,"r"],[692,1,"ɹ"],[693,1,"ɻ"],[694,1,"ʁ"],[695,1,"w"],[696,1,"y"],[[697,705],2],[[706,709],2],[[710,721],2],[[722,727],2],[728,5," ̆"],[729,5," ̇"],[730,5," ̊"],[731,5," ̨"],[732,5," ̃"],[733,5," ̋"],[734,2],[735,2],[736,1,"ɣ"],[737,1,"l"],[738,1,"s"],[739,1,"x"],[740,1,"ʕ"],[[741,745],2],[[746,747],2],[748,2],[749,2],[750,2],[[751,767],2],[[768,831],2],[832,1,"̀"],[833,1,"́"],[834,2],[835,1,"̓"],[836,1,"̈́"],[837,1,"ι"],[[838,846],2],[847,7],[[848,855],2],[[856,860],2],[[861,863],2],[[864,865],2],[866,2],[[867,879],2],[880,1,"ͱ"],[881,2],[882,1,"ͳ"],[883,2],[884,1,"ʹ"],[885,2],[886,1,"ͷ"],[887,2],[[888,889],3],[890,5," ι"],[[891,893],2],[894,5,";"],[895,1,"ϳ"],[[896,899],3],[900,5," ́"],[901,5," ̈́"],[902,1,"ά"],[903,1,"·"],[904,1,"έ"],[905,1,"ή"],[906,1,"ί"],[907,3],[908,1,"ό"],[909,3],[910,1,"ύ"],[911,1,"ώ"],[912,2],[913,1,"α"],[914,1,"β"],[915,1,"γ"],[916,1,"δ"],[917,1,"ε"],[918,1,"ζ"],[919,1,"η"],[920,1,"θ"],[921,1,"ι"],[922,1,"κ"],[923,1,"λ"],[924,1,"μ"],[925,1,"ν"],[926,1,"ξ"],[927,1,"ο"],[928,1,"π"],[929,1,"ρ"],[930,3],[931,1,"σ"],[932,1,"τ"],[933,1,"υ"],[934,1,"φ"],[935,1,"χ"],[936,1,"ψ"],[937,1,"ω"],[938,1,"ϊ"],[939,1,"ϋ"],[[940,961],2],[962,6,"σ"],[[963,974],2],[975,1,"ϗ"],[976,1,"β"],[977,1,"θ"],[978,1,"υ"],[979,1,"ύ"],[980,1,"ϋ"],[981,1,"φ"],[982,1,"π"],[983,2],[984,1,"ϙ"],[985,2],[986,1,"ϛ"],[987,2],[988,1,"ϝ"],[989,2],[990,1,"ϟ"],[991,2],[992,1,"ϡ"],[993,2],[994,1,"ϣ"],[995,2],[996,1,"ϥ"],[997,2],[998,1,"ϧ"],[999,2],[1000,1,"ϩ"],[1001,2],[1002,1,"ϫ"],[1003,2],[1004,1,"ϭ"],[1005,2],[1006,1,"ϯ"],[1007,2],[1008,1,"κ"],[1009,1,"ρ"],[1010,1,"σ"],[1011,2],[1012,1,"θ"],[1013,1,"ε"],[1014,2],[1015,1,"ϸ"],[1016,2],[1017,1,"σ"],[1018,1,"ϻ"],[1019,2],[1020,2],[1021,1,"ͻ"],[1022,1,"ͼ"],[1023,1,"ͽ"],[1024,1,"ѐ"],[1025,1,"ё"],[1026,1,"ђ"],[1027,1,"ѓ"],[1028,1,"є"],[1029,1,"ѕ"],[1030,1,"і"],[1031,1,"ї"],[1032,1,"ј"],[1033,1,"љ"],[1034,1,"њ"],[1035,1,"ћ"],[1036,1,"ќ"],[1037,1,"ѝ"],[1038,1,"ў"],[1039,1,"џ"],[1040,1,"а"],[1041,1,"б"],[1042,1,"в"],[1043,1,"г"],[1044,1,"д"],[1045,1,"е"],[1046,1,"ж"],[1047,1,"з"],[1048,1,"и"],[1049,1,"й"],[1050,1,"к"],[1051,1,"л"],[1052,1,"м"],[1053,1,"н"],[1054,1,"о"],[1055,1,"п"],[1056,1,"р"],[1057,1,"с"],[1058,1,"т"],[1059,1,"у"],[1060,1,"ф"],[1061,1,"х"],[1062,1,"ц"],[1063,1,"ч"],[1064,1,"ш"],[1065,1,"щ"],[1066,1,"ъ"],[1067,1,"ы"],[1068,1,"ь"],[1069,1,"э"],[1070,1,"ю"],[1071,1,"я"],[[1072,1103],2],[1104,2],[[1105,1116],2],[1117,2],[[1118,1119],2],[1120,1,"ѡ"],[1121,2],[1122,1,"ѣ"],[1123,2],[1124,1,"ѥ"],[1125,2],[1126,1,"ѧ"],[1127,2],[1128,1,"ѩ"],[1129,2],[1130,1,"ѫ"],[1131,2],[1132,1,"ѭ"],[1133,2],[1134,1,"ѯ"],[1135,2],[1136,1,"ѱ"],[1137,2],[1138,1,"ѳ"],[1139,2],[1140,1,"ѵ"],[1141,2],[1142,1,"ѷ"],[1143,2],[1144,1,"ѹ"],[1145,2],[1146,1,"ѻ"],[1147,2],[1148,1,"ѽ"],[1149,2],[1150,1,"ѿ"],[1151,2],[1152,1,"ҁ"],[1153,2],[1154,2],[[1155,1158],2],[1159,2],[[1160,1161],2],[1162,1,"ҋ"],[1163,2],[1164,1,"ҍ"],[1165,2],[1166,1,"ҏ"],[1167,2],[1168,1,"ґ"],[1169,2],[1170,1,"ғ"],[1171,2],[1172,1,"ҕ"],[1173,2],[1174,1,"җ"],[1175,2],[1176,1,"ҙ"],[1177,2],[1178,1,"қ"],[1179,2],[1180,1,"ҝ"],[1181,2],[1182,1,"ҟ"],[1183,2],[1184,1,"ҡ"],[1185,2],[1186,1,"ң"],[1187,2],[1188,1,"ҥ"],[1189,2],[1190,1,"ҧ"],[1191,2],[1192,1,"ҩ"],[1193,2],[1194,1,"ҫ"],[1195,2],[1196,1,"ҭ"],[1197,2],[1198,1,"ү"],[1199,2],[1200,1,"ұ"],[1201,2],[1202,1,"ҳ"],[1203,2],[1204,1,"ҵ"],[1205,2],[1206,1,"ҷ"],[1207,2],[1208,1,"ҹ"],[1209,2],[1210,1,"һ"],[1211,2],[1212,1,"ҽ"],[1213,2],[1214,1,"ҿ"],[1215,2],[1216,3],[1217,1,"ӂ"],[1218,2],[1219,1,"ӄ"],[1220,2],[1221,1,"ӆ"],[1222,2],[1223,1,"ӈ"],[1224,2],[1225,1,"ӊ"],[1226,2],[1227,1,"ӌ"],[1228,2],[1229,1,"ӎ"],[1230,2],[1231,2],[1232,1,"ӑ"],[1233,2],[1234,1,"ӓ"],[1235,2],[1236,1,"ӕ"],[1237,2],[1238,1,"ӗ"],[1239,2],[1240,1,"ә"],[1241,2],[1242,1,"ӛ"],[1243,2],[1244,1,"ӝ"],[1245,2],[1246,1,"ӟ"],[1247,2],[1248,1,"ӡ"],[1249,2],[1250,1,"ӣ"],[1251,2],[1252,1,"ӥ"],[1253,2],[1254,1,"ӧ"],[1255,2],[1256,1,"ө"],[1257,2],[1258,1,"ӫ"],[1259,2],[1260,1,"ӭ"],[1261,2],[1262,1,"ӯ"],[1263,2],[1264,1,"ӱ"],[1265,2],[1266,1,"ӳ"],[1267,2],[1268,1,"ӵ"],[1269,2],[1270,1,"ӷ"],[1271,2],[1272,1,"ӹ"],[1273,2],[1274,1,"ӻ"],[1275,2],[1276,1,"ӽ"],[1277,2],[1278,1,"ӿ"],[1279,2],[1280,1,"ԁ"],[1281,2],[1282,1,"ԃ"],[1283,2],[1284,1,"ԅ"],[1285,2],[1286,1,"ԇ"],[1287,2],[1288,1,"ԉ"],[1289,2],[1290,1,"ԋ"],[1291,2],[1292,1,"ԍ"],[1293,2],[1294,1,"ԏ"],[1295,2],[1296,1,"ԑ"],[1297,2],[1298,1,"ԓ"],[1299,2],[1300,1,"ԕ"],[1301,2],[1302,1,"ԗ"],[1303,2],[1304,1,"ԙ"],[1305,2],[1306,1,"ԛ"],[1307,2],[1308,1,"ԝ"],[1309,2],[1310,1,"ԟ"],[1311,2],[1312,1,"ԡ"],[1313,2],[1314,1,"ԣ"],[1315,2],[1316,1,"ԥ"],[1317,2],[1318,1,"ԧ"],[1319,2],[1320,1,"ԩ"],[1321,2],[1322,1,"ԫ"],[1323,2],[1324,1,"ԭ"],[1325,2],[1326,1,"ԯ"],[1327,2],[1328,3],[1329,1,"ա"],[1330,1,"բ"],[1331,1,"գ"],[1332,1,"դ"],[1333,1,"ե"],[1334,1,"զ"],[1335,1,"է"],[1336,1,"ը"],[1337,1,"թ"],[1338,1,"ժ"],[1339,1,"ի"],[1340,1,"լ"],[1341,1,"խ"],[1342,1,"ծ"],[1343,1,"կ"],[1344,1,"հ"],[1345,1,"ձ"],[1346,1,"ղ"],[1347,1,"ճ"],[1348,1,"մ"],[1349,1,"յ"],[1350,1,"ն"],[1351,1,"շ"],[1352,1,"ո"],[1353,1,"չ"],[1354,1,"պ"],[1355,1,"ջ"],[1356,1,"ռ"],[1357,1,"ս"],[1358,1,"վ"],[1359,1,"տ"],[1360,1,"ր"],[1361,1,"ց"],[1362,1,"ւ"],[1363,1,"փ"],[1364,1,"ք"],[1365,1,"օ"],[1366,1,"ֆ"],[[1367,1368],3],[1369,2],[[1370,1375],2],[1376,2],[[1377,1414],2],[1415,1,"եւ"],[1416,2],[1417,2],[1418,2],[[1419,1420],3],[[1421,1422],2],[1423,2],[1424,3],[[1425,1441],2],[1442,2],[[1443,1455],2],[[1456,1465],2],[1466,2],[[1467,1469],2],[1470,2],[1471,2],[1472,2],[[1473,1474],2],[1475,2],[1476,2],[1477,2],[1478,2],[1479,2],[[1480,1487],3],[[1488,1514],2],[[1515,1518],3],[1519,2],[[1520,1524],2],[[1525,1535],3],[[1536,1539],3],[1540,3],[1541,3],[[1542,1546],2],[1547,2],[1548,2],[[1549,1551],2],[[1552,1557],2],[[1558,1562],2],[1563,2],[1564,3],[1565,2],[1566,2],[1567,2],[1568,2],[[1569,1594],2],[[1595,1599],2],[1600,2],[[1601,1618],2],[[1619,1621],2],[[1622,1624],2],[[1625,1630],2],[1631,2],[[1632,1641],2],[[1642,1645],2],[[1646,1647],2],[[1648,1652],2],[1653,1,"اٴ"],[1654,1,"وٴ"],[1655,1,"ۇٴ"],[1656,1,"يٴ"],[[1657,1719],2],[[1720,1721],2],[[1722,1726],2],[1727,2],[[1728,1742],2],[1743,2],[[1744,1747],2],[1748,2],[[1749,1756],2],[1757,3],[1758,2],[[1759,1768],2],[1769,2],[[1770,1773],2],[[1774,1775],2],[[1776,1785],2],[[1786,1790],2],[1791,2],[[1792,1805],2],[1806,3],[1807,3],[[1808,1836],2],[[1837,1839],2],[[1840,1866],2],[[1867,1868],3],[[1869,1871],2],[[1872,1901],2],[[1902,1919],2],[[1920,1968],2],[1969,2],[[1970,1983],3],[[1984,2037],2],[[2038,2042],2],[[2043,2044],3],[2045,2],[[2046,2047],2],[[2048,2093],2],[[2094,2095],3],[[2096,2110],2],[2111,3],[[2112,2139],2],[[2140,2141],3],[2142,2],[2143,3],[[2144,2154],2],[[2155,2159],3],[[2160,2183],2],[2184,2],[[2185,2190],2],[2191,3],[[2192,2193],3],[[2194,2199],3],[[2200,2207],2],[2208,2],[2209,2],[[2210,2220],2],[[2221,2226],2],[[2227,2228],2],[2229,2],[[2230,2237],2],[[2238,2247],2],[[2248,2258],2],[2259,2],[[2260,2273],2],[2274,3],[2275,2],[[2276,2302],2],[2303,2],[2304,2],[[2305,2307],2],[2308,2],[[2309,2361],2],[[2362,2363],2],[[2364,2381],2],[2382,2],[2383,2],[[2384,2388],2],[2389,2],[[2390,2391],2],[2392,1,"क़"],[2393,1,"ख़"],[2394,1,"ग़"],[2395,1,"ज़"],[2396,1,"ड़"],[2397,1,"ढ़"],[2398,1,"फ़"],[2399,1,"य़"],[[2400,2403],2],[[2404,2405],2],[[2406,2415],2],[2416,2],[[2417,2418],2],[[2419,2423],2],[2424,2],[[2425,2426],2],[[2427,2428],2],[2429,2],[[2430,2431],2],[2432,2],[[2433,2435],2],[2436,3],[[2437,2444],2],[[2445,2446],3],[[2447,2448],2],[[2449,2450],3],[[2451,2472],2],[2473,3],[[2474,2480],2],[2481,3],[2482,2],[[2483,2485],3],[[2486,2489],2],[[2490,2491],3],[2492,2],[2493,2],[[2494,2500],2],[[2501,2502],3],[[2503,2504],2],[[2505,2506],3],[[2507,2509],2],[2510,2],[[2511,2518],3],[2519,2],[[2520,2523],3],[2524,1,"ড়"],[2525,1,"ঢ়"],[2526,3],[2527,1,"য়"],[[2528,2531],2],[[2532,2533],3],[[2534,2545],2],[[2546,2554],2],[2555,2],[2556,2],[2557,2],[2558,2],[[2559,2560],3],[2561,2],[2562,2],[2563,2],[2564,3],[[2565,2570],2],[[2571,2574],3],[[2575,2576],2],[[2577,2578],3],[[2579,2600],2],[2601,3],[[2602,2608],2],[2609,3],[2610,2],[2611,1,"ਲ਼"],[2612,3],[2613,2],[2614,1,"ਸ਼"],[2615,3],[[2616,2617],2],[[2618,2619],3],[2620,2],[2621,3],[[2622,2626],2],[[2627,2630],3],[[2631,2632],2],[[2633,2634],3],[[2635,2637],2],[[2638,2640],3],[2641,2],[[2642,2648],3],[2649,1,"ਖ਼"],[2650,1,"ਗ਼"],[2651,1,"ਜ਼"],[2652,2],[2653,3],[2654,1,"ਫ਼"],[[2655,2661],3],[[2662,2676],2],[2677,2],[2678,2],[[2679,2688],3],[[2689,2691],2],[2692,3],[[2693,2699],2],[2700,2],[2701,2],[2702,3],[[2703,2705],2],[2706,3],[[2707,2728],2],[2729,3],[[2730,2736],2],[2737,3],[[2738,2739],2],[2740,3],[[2741,2745],2],[[2746,2747],3],[[2748,2757],2],[2758,3],[[2759,2761],2],[2762,3],[[2763,2765],2],[[2766,2767],3],[2768,2],[[2769,2783],3],[2784,2],[[2785,2787],2],[[2788,2789],3],[[2790,2799],2],[2800,2],[2801,2],[[2802,2808],3],[2809,2],[[2810,2815],2],[2816,3],[[2817,2819],2],[2820,3],[[2821,2828],2],[[2829,2830],3],[[2831,2832],2],[[2833,2834],3],[[2835,2856],2],[2857,3],[[2858,2864],2],[2865,3],[[2866,2867],2],[2868,3],[2869,2],[[2870,2873],2],[[2874,2875],3],[[2876,2883],2],[2884,2],[[2885,2886],3],[[2887,2888],2],[[2889,2890],3],[[2891,2893],2],[[2894,2900],3],[2901,2],[[2902,2903],2],[[2904,2907],3],[2908,1,"ଡ଼"],[2909,1,"ଢ଼"],[2910,3],[[2911,2913],2],[[2914,2915],2],[[2916,2917],3],[[2918,2927],2],[2928,2],[2929,2],[[2930,2935],2],[[2936,2945],3],[[2946,2947],2],[2948,3],[[2949,2954],2],[[2955,2957],3],[[2958,2960],2],[2961,3],[[2962,2965],2],[[2966,2968],3],[[2969,2970],2],[2971,3],[2972,2],[2973,3],[[2974,2975],2],[[2976,2978],3],[[2979,2980],2],[[2981,2983],3],[[2984,2986],2],[[2987,2989],3],[[2990,2997],2],[2998,2],[[2999,3001],2],[[3002,3005],3],[[3006,3010],2],[[3011,3013],3],[[3014,3016],2],[3017,3],[[3018,3021],2],[[3022,3023],3],[3024,2],[[3025,3030],3],[3031,2],[[3032,3045],3],[3046,2],[[3047,3055],2],[[3056,3058],2],[[3059,3066],2],[[3067,3071],3],[3072,2],[[3073,3075],2],[3076,2],[[3077,3084],2],[3085,3],[[3086,3088],2],[3089,3],[[3090,3112],2],[3113,3],[[3114,3123],2],[3124,2],[[3125,3129],2],[[3130,3131],3],[3132,2],[3133,2],[[3134,3140],2],[3141,3],[[3142,3144],2],[3145,3],[[3146,3149],2],[[3150,3156],3],[[3157,3158],2],[3159,3],[[3160,3161],2],[3162,2],[[3163,3164],3],[3165,2],[[3166,3167],3],[[3168,3169],2],[[3170,3171],2],[[3172,3173],3],[[3174,3183],2],[[3184,3190],3],[3191,2],[[3192,3199],2],[3200,2],[3201,2],[[3202,3203],2],[3204,2],[[3205,3212],2],[3213,3],[[3214,3216],2],[3217,3],[[3218,3240],2],[3241,3],[[3242,3251],2],[3252,3],[[3253,3257],2],[[3258,3259],3],[[3260,3261],2],[[3262,3268],2],[3269,3],[[3270,3272],2],[3273,3],[[3274,3277],2],[[3278,3284],3],[[3285,3286],2],[[3287,3292],3],[3293,2],[3294,2],[3295,3],[[3296,3297],2],[[3298,3299],2],[[3300,3301],3],[[3302,3311],2],[3312,3],[[3313,3314],2],[[3315,3327],3],[3328,2],[3329,2],[[3330,3331],2],[3332,2],[[3333,3340],2],[3341,3],[[3342,3344],2],[3345,3],[[3346,3368],2],[3369,2],[[3370,3385],2],[3386,2],[[3387,3388],2],[3389,2],[[3390,3395],2],[3396,2],[3397,3],[[3398,3400],2],[3401,3],[[3402,3405],2],[3406,2],[3407,2],[[3408,3411],3],[[3412,3414],2],[3415,2],[[3416,3422],2],[3423,2],[[3424,3425],2],[[3426,3427],2],[[3428,3429],3],[[3430,3439],2],[[3440,3445],2],[[3446,3448],2],[3449,2],[[3450,3455],2],[3456,3],[3457,2],[[3458,3459],2],[3460,3],[[3461,3478],2],[[3479,3481],3],[[3482,3505],2],[3506,3],[[3507,3515],2],[3516,3],[3517,2],[[3518,3519],3],[[3520,3526],2],[[3527,3529],3],[3530,2],[[3531,3534],3],[[3535,3540],2],[3541,3],[3542,2],[3543,3],[[3544,3551],2],[[3552,3557],3],[[3558,3567],2],[[3568,3569],3],[[3570,3571],2],[3572,2],[[3573,3584],3],[[3585,3634],2],[3635,1,"ํา"],[[3636,3642],2],[[3643,3646],3],[3647,2],[[3648,3662],2],[3663,2],[[3664,3673],2],[[3674,3675],2],[[3676,3712],3],[[3713,3714],2],[3715,3],[3716,2],[3717,3],[3718,2],[[3719,3720],2],[3721,2],[3722,2],[3723,3],[3724,2],[3725,2],[[3726,3731],2],[[3732,3735],2],[3736,2],[[3737,3743],2],[3744,2],[[3745,3747],2],[3748,3],[3749,2],[3750,3],[3751,2],[[3752,3753],2],[[3754,3755],2],[3756,2],[[3757,3762],2],[3763,1,"ໍາ"],[[3764,3769],2],[3770,2],[[3771,3773],2],[[3774,3775],3],[[3776,3780],2],[3781,3],[3782,2],[3783,3],[[3784,3789],2],[[3790,3791],3],[[3792,3801],2],[[3802,3803],3],[3804,1,"ຫນ"],[3805,1,"ຫມ"],[[3806,3807],2],[[3808,3839],3],[3840,2],[[3841,3850],2],[3851,2],[3852,1,"་"],[[3853,3863],2],[[3864,3865],2],[[3866,3871],2],[[3872,3881],2],[[3882,3892],2],[3893,2],[3894,2],[3895,2],[3896,2],[3897,2],[[3898,3901],2],[[3902,3906],2],[3907,1,"གྷ"],[[3908,3911],2],[3912,3],[[3913,3916],2],[3917,1,"ཌྷ"],[[3918,3921],2],[3922,1,"དྷ"],[[3923,3926],2],[3927,1,"བྷ"],[[3928,3931],2],[3932,1,"ཛྷ"],[[3933,3944],2],[3945,1,"ཀྵ"],[3946,2],[[3947,3948],2],[[3949,3952],3],[[3953,3954],2],[3955,1,"ཱི"],[3956,2],[3957,1,"ཱུ"],[3958,1,"ྲྀ"],[3959,1,"ྲཱྀ"],[3960,1,"ླྀ"],[3961,1,"ླཱྀ"],[[3962,3968],2],[3969,1,"ཱྀ"],[[3970,3972],2],[3973,2],[[3974,3979],2],[[3980,3983],2],[[3984,3986],2],[3987,1,"ྒྷ"],[[3988,3989],2],[3990,2],[3991,2],[3992,3],[[3993,3996],2],[3997,1,"ྜྷ"],[[3998,4001],2],[4002,1,"ྡྷ"],[[4003,4006],2],[4007,1,"ྦྷ"],[[4008,4011],2],[4012,1,"ྫྷ"],[4013,2],[[4014,4016],2],[[4017,4023],2],[4024,2],[4025,1,"ྐྵ"],[[4026,4028],2],[4029,3],[[4030,4037],2],[4038,2],[[4039,4044],2],[4045,3],[4046,2],[4047,2],[[4048,4049],2],[[4050,4052],2],[[4053,4056],2],[[4057,4058],2],[[4059,4095],3],[[4096,4129],2],[4130,2],[[4131,4135],2],[4136,2],[[4137,4138],2],[4139,2],[[4140,4146],2],[[4147,4149],2],[[4150,4153],2],[[4154,4159],2],[[4160,4169],2],[[4170,4175],2],[[4176,4185],2],[[4186,4249],2],[[4250,4253],2],[[4254,4255],2],[[4256,4293],3],[4294,3],[4295,1,"ⴧ"],[[4296,4300],3],[4301,1,"ⴭ"],[[4302,4303],3],[[4304,4342],2],[[4343,4344],2],[[4345,4346],2],[4347,2],[4348,1,"ნ"],[[4349,4351],2],[[4352,4441],2],[[4442,4446],2],[[4447,4448],3],[[4449,4514],2],[[4515,4519],2],[[4520,4601],2],[[4602,4607],2],[[4608,4614],2],[4615,2],[[4616,4678],2],[4679,2],[4680,2],[4681,3],[[4682,4685],2],[[4686,4687],3],[[4688,4694],2],[4695,3],[4696,2],[4697,3],[[4698,4701],2],[[4702,4703],3],[[4704,4742],2],[4743,2],[4744,2],[4745,3],[[4746,4749],2],[[4750,4751],3],[[4752,4782],2],[4783,2],[4784,2],[4785,3],[[4786,4789],2],[[4790,4791],3],[[4792,4798],2],[4799,3],[4800,2],[4801,3],[[4802,4805],2],[[4806,4807],3],[[4808,4814],2],[4815,2],[[4816,4822],2],[4823,3],[[4824,4846],2],[4847,2],[[4848,4878],2],[4879,2],[4880,2],[4881,3],[[4882,4885],2],[[4886,4887],3],[[4888,4894],2],[4895,2],[[4896,4934],2],[4935,2],[[4936,4954],2],[[4955,4956],3],[[4957,4958],2],[4959,2],[4960,2],[[4961,4988],2],[[4989,4991],3],[[4992,5007],2],[[5008,5017],2],[[5018,5023],3],[[5024,5108],2],[5109,2],[[5110,5111],3],[5112,1,"Ᏸ"],[5113,1,"Ᏹ"],[5114,1,"Ᏺ"],[5115,1,"Ᏻ"],[5116,1,"Ᏼ"],[5117,1,"Ᏽ"],[[5118,5119],3],[5120,2],[[5121,5740],2],[[5741,5742],2],[[5743,5750],2],[[5751,5759],2],[5760,3],[[5761,5786],2],[[5787,5788],2],[[5789,5791],3],[[5792,5866],2],[[5867,5872],2],[[5873,5880],2],[[5881,5887],3],[[5888,5900],2],[5901,2],[[5902,5908],2],[5909,2],[[5910,5918],3],[5919,2],[[5920,5940],2],[[5941,5942],2],[[5943,5951],3],[[5952,5971],2],[[5972,5983],3],[[5984,5996],2],[5997,3],[[5998,6000],2],[6001,3],[[6002,6003],2],[[6004,6015],3],[[6016,6067],2],[[6068,6069],3],[[6070,6099],2],[[6100,6102],2],[6103,2],[[6104,6107],2],[6108,2],[6109,2],[[6110,6111],3],[[6112,6121],2],[[6122,6127],3],[[6128,6137],2],[[6138,6143],3],[[6144,6149],2],[6150,3],[[6151,6154],2],[[6155,6157],7],[6158,3],[6159,7],[[6160,6169],2],[[6170,6175],3],[[6176,6263],2],[6264,2],[[6265,6271],3],[[6272,6313],2],[6314,2],[[6315,6319],3],[[6320,6389],2],[[6390,6399],3],[[6400,6428],2],[[6429,6430],2],[6431,3],[[6432,6443],2],[[6444,6447],3],[[6448,6459],2],[[6460,6463],3],[6464,2],[[6465,6467],3],[[6468,6469],2],[[6470,6509],2],[[6510,6511],3],[[6512,6516],2],[[6517,6527],3],[[6528,6569],2],[[6570,6571],2],[[6572,6575],3],[[6576,6601],2],[[6602,6607],3],[[6608,6617],2],[6618,2],[[6619,6621],3],[[6622,6623],2],[[6624,6655],2],[[6656,6683],2],[[6684,6685],3],[[6686,6687],2],[[6688,6750],2],[6751,3],[[6752,6780],2],[[6781,6782],3],[[6783,6793],2],[[6794,6799],3],[[6800,6809],2],[[6810,6815],3],[[6816,6822],2],[6823,2],[[6824,6829],2],[[6830,6831],3],[[6832,6845],2],[6846,2],[[6847,6848],2],[[6849,6862],2],[[6863,6911],3],[[6912,6987],2],[6988,2],[[6989,6991],3],[[6992,7001],2],[[7002,7018],2],[[7019,7027],2],[[7028,7036],2],[[7037,7038],2],[7039,3],[[7040,7082],2],[[7083,7085],2],[[7086,7097],2],[[7098,7103],2],[[7104,7155],2],[[7156,7163],3],[[7164,7167],2],[[7168,7223],2],[[7224,7226],3],[[7227,7231],2],[[7232,7241],2],[[7242,7244],3],[[7245,7293],2],[[7294,7295],2],[7296,1,"в"],[7297,1,"д"],[7298,1,"о"],[7299,1,"с"],[[7300,7301],1,"т"],[7302,1,"ъ"],[7303,1,"ѣ"],[7304,1,"ꙋ"],[[7305,7311],3],[7312,1,"ა"],[7313,1,"ბ"],[7314,1,"გ"],[7315,1,"დ"],[7316,1,"ე"],[7317,1,"ვ"],[7318,1,"ზ"],[7319,1,"თ"],[7320,1,"ი"],[7321,1,"კ"],[7322,1,"ლ"],[7323,1,"მ"],[7324,1,"ნ"],[7325,1,"ო"],[7326,1,"პ"],[7327,1,"ჟ"],[7328,1,"რ"],[7329,1,"ს"],[7330,1,"ტ"],[7331,1,"უ"],[7332,1,"ფ"],[7333,1,"ქ"],[7334,1,"ღ"],[7335,1,"ყ"],[7336,1,"შ"],[7337,1,"ჩ"],[7338,1,"ც"],[7339,1,"ძ"],[7340,1,"წ"],[7341,1,"ჭ"],[7342,1,"ხ"],[7343,1,"ჯ"],[7344,1,"ჰ"],[7345,1,"ჱ"],[7346,1,"ჲ"],[7347,1,"ჳ"],[7348,1,"ჴ"],[7349,1,"ჵ"],[7350,1,"ჶ"],[7351,1,"ჷ"],[7352,1,"ჸ"],[7353,1,"ჹ"],[7354,1,"ჺ"],[[7355,7356],3],[7357,1,"ჽ"],[7358,1,"ჾ"],[7359,1,"ჿ"],[[7360,7367],2],[[7368,7375],3],[[7376,7378],2],[7379,2],[[7380,7410],2],[[7411,7414],2],[7415,2],[[7416,7417],2],[7418,2],[[7419,7423],3],[[7424,7467],2],[7468,1,"a"],[7469,1,"æ"],[7470,1,"b"],[7471,2],[7472,1,"d"],[7473,1,"e"],[7474,1,"ǝ"],[7475,1,"g"],[7476,1,"h"],[7477,1,"i"],[7478,1,"j"],[7479,1,"k"],[7480,1,"l"],[7481,1,"m"],[7482,1,"n"],[7483,2],[7484,1,"o"],[7485,1,"ȣ"],[7486,1,"p"],[7487,1,"r"],[7488,1,"t"],[7489,1,"u"],[7490,1,"w"],[7491,1,"a"],[7492,1,"ɐ"],[7493,1,"ɑ"],[7494,1,"ᴂ"],[7495,1,"b"],[7496,1,"d"],[7497,1,"e"],[7498,1,"ə"],[7499,1,"ɛ"],[7500,1,"ɜ"],[7501,1,"g"],[7502,2],[7503,1,"k"],[7504,1,"m"],[7505,1,"ŋ"],[7506,1,"o"],[7507,1,"ɔ"],[7508,1,"ᴖ"],[7509,1,"ᴗ"],[7510,1,"p"],[7511,1,"t"],[7512,1,"u"],[7513,1,"ᴝ"],[7514,1,"ɯ"],[7515,1,"v"],[7516,1,"ᴥ"],[7517,1,"β"],[7518,1,"γ"],[7519,1,"δ"],[7520,1,"φ"],[7521,1,"χ"],[7522,1,"i"],[7523,1,"r"],[7524,1,"u"],[7525,1,"v"],[7526,1,"β"],[7527,1,"γ"],[7528,1,"ρ"],[7529,1,"φ"],[7530,1,"χ"],[7531,2],[[7532,7543],2],[7544,1,"н"],[[7545,7578],2],[7579,1,"ɒ"],[7580,1,"c"],[7581,1,"ɕ"],[7582,1,"ð"],[7583,1,"ɜ"],[7584,1,"f"],[7585,1,"ɟ"],[7586,1,"ɡ"],[7587,1,"ɥ"],[7588,1,"ɨ"],[7589,1,"ɩ"],[7590,1,"ɪ"],[7591,1,"ᵻ"],[7592,1,"ʝ"],[7593,1,"ɭ"],[7594,1,"ᶅ"],[7595,1,"ʟ"],[7596,1,"ɱ"],[7597,1,"ɰ"],[7598,1,"ɲ"],[7599,1,"ɳ"],[7600,1,"ɴ"],[7601,1,"ɵ"],[7602,1,"ɸ"],[7603,1,"ʂ"],[7604,1,"ʃ"],[7605,1,"ƫ"],[7606,1,"ʉ"],[7607,1,"ʊ"],[7608,1,"ᴜ"],[7609,1,"ʋ"],[7610,1,"ʌ"],[7611,1,"z"],[7612,1,"ʐ"],[7613,1,"ʑ"],[7614,1,"ʒ"],[7615,1,"θ"],[[7616,7619],2],[[7620,7626],2],[[7627,7654],2],[[7655,7669],2],[[7670,7673],2],[7674,2],[7675,2],[7676,2],[7677,2],[[7678,7679],2],[7680,1,"ḁ"],[7681,2],[7682,1,"ḃ"],[7683,2],[7684,1,"ḅ"],[7685,2],[7686,1,"ḇ"],[7687,2],[7688,1,"ḉ"],[7689,2],[7690,1,"ḋ"],[7691,2],[7692,1,"ḍ"],[7693,2],[7694,1,"ḏ"],[7695,2],[7696,1,"ḑ"],[7697,2],[7698,1,"ḓ"],[7699,2],[7700,1,"ḕ"],[7701,2],[7702,1,"ḗ"],[7703,2],[7704,1,"ḙ"],[7705,2],[7706,1,"ḛ"],[7707,2],[7708,1,"ḝ"],[7709,2],[7710,1,"ḟ"],[7711,2],[7712,1,"ḡ"],[7713,2],[7714,1,"ḣ"],[7715,2],[7716,1,"ḥ"],[7717,2],[7718,1,"ḧ"],[7719,2],[7720,1,"ḩ"],[7721,2],[7722,1,"ḫ"],[7723,2],[7724,1,"ḭ"],[7725,2],[7726,1,"ḯ"],[7727,2],[7728,1,"ḱ"],[7729,2],[7730,1,"ḳ"],[7731,2],[7732,1,"ḵ"],[7733,2],[7734,1,"ḷ"],[7735,2],[7736,1,"ḹ"],[7737,2],[7738,1,"ḻ"],[7739,2],[7740,1,"ḽ"],[7741,2],[7742,1,"ḿ"],[7743,2],[7744,1,"ṁ"],[7745,2],[7746,1,"ṃ"],[7747,2],[7748,1,"ṅ"],[7749,2],[7750,1,"ṇ"],[7751,2],[7752,1,"ṉ"],[7753,2],[7754,1,"ṋ"],[7755,2],[7756,1,"ṍ"],[7757,2],[7758,1,"ṏ"],[7759,2],[7760,1,"ṑ"],[7761,2],[7762,1,"ṓ"],[7763,2],[7764,1,"ṕ"],[7765,2],[7766,1,"ṗ"],[7767,2],[7768,1,"ṙ"],[7769,2],[7770,1,"ṛ"],[7771,2],[7772,1,"ṝ"],[7773,2],[7774,1,"ṟ"],[7775,2],[7776,1,"ṡ"],[7777,2],[7778,1,"ṣ"],[7779,2],[7780,1,"ṥ"],[7781,2],[7782,1,"ṧ"],[7783,2],[7784,1,"ṩ"],[7785,2],[7786,1,"ṫ"],[7787,2],[7788,1,"ṭ"],[7789,2],[7790,1,"ṯ"],[7791,2],[7792,1,"ṱ"],[7793,2],[7794,1,"ṳ"],[7795,2],[7796,1,"ṵ"],[7797,2],[7798,1,"ṷ"],[7799,2],[7800,1,"ṹ"],[7801,2],[7802,1,"ṻ"],[7803,2],[7804,1,"ṽ"],[7805,2],[7806,1,"ṿ"],[7807,2],[7808,1,"ẁ"],[7809,2],[7810,1,"ẃ"],[7811,2],[7812,1,"ẅ"],[7813,2],[7814,1,"ẇ"],[7815,2],[7816,1,"ẉ"],[7817,2],[7818,1,"ẋ"],[7819,2],[7820,1,"ẍ"],[7821,2],[7822,1,"ẏ"],[7823,2],[7824,1,"ẑ"],[7825,2],[7826,1,"ẓ"],[7827,2],[7828,1,"ẕ"],[[7829,7833],2],[7834,1,"aʾ"],[7835,1,"ṡ"],[[7836,7837],2],[7838,1,"ss"],[7839,2],[7840,1,"ạ"],[7841,2],[7842,1,"ả"],[7843,2],[7844,1,"ấ"],[7845,2],[7846,1,"ầ"],[7847,2],[7848,1,"ẩ"],[7849,2],[7850,1,"ẫ"],[7851,2],[7852,1,"ậ"],[7853,2],[7854,1,"ắ"],[7855,2],[7856,1,"ằ"],[7857,2],[7858,1,"ẳ"],[7859,2],[7860,1,"ẵ"],[7861,2],[7862,1,"ặ"],[7863,2],[7864,1,"ẹ"],[7865,2],[7866,1,"ẻ"],[7867,2],[7868,1,"ẽ"],[7869,2],[7870,1,"ế"],[7871,2],[7872,1,"ề"],[7873,2],[7874,1,"ể"],[7875,2],[7876,1,"ễ"],[7877,2],[7878,1,"ệ"],[7879,2],[7880,1,"ỉ"],[7881,2],[7882,1,"ị"],[7883,2],[7884,1,"ọ"],[7885,2],[7886,1,"ỏ"],[7887,2],[7888,1,"ố"],[7889,2],[7890,1,"ồ"],[7891,2],[7892,1,"ổ"],[7893,2],[7894,1,"ỗ"],[7895,2],[7896,1,"ộ"],[7897,2],[7898,1,"ớ"],[7899,2],[7900,1,"ờ"],[7901,2],[7902,1,"ở"],[7903,2],[7904,1,"ỡ"],[7905,2],[7906,1,"ợ"],[7907,2],[7908,1,"ụ"],[7909,2],[7910,1,"ủ"],[7911,2],[7912,1,"ứ"],[7913,2],[7914,1,"ừ"],[7915,2],[7916,1,"ử"],[7917,2],[7918,1,"ữ"],[7919,2],[7920,1,"ự"],[7921,2],[7922,1,"ỳ"],[7923,2],[7924,1,"ỵ"],[7925,2],[7926,1,"ỷ"],[7927,2],[7928,1,"ỹ"],[7929,2],[7930,1,"ỻ"],[7931,2],[7932,1,"ỽ"],[7933,2],[7934,1,"ỿ"],[7935,2],[[7936,7943],2],[7944,1,"ἀ"],[7945,1,"ἁ"],[7946,1,"ἂ"],[7947,1,"ἃ"],[7948,1,"ἄ"],[7949,1,"ἅ"],[7950,1,"ἆ"],[7951,1,"ἇ"],[[7952,7957],2],[[7958,7959],3],[7960,1,"ἐ"],[7961,1,"ἑ"],[7962,1,"ἒ"],[7963,1,"ἓ"],[7964,1,"ἔ"],[7965,1,"ἕ"],[[7966,7967],3],[[7968,7975],2],[7976,1,"ἠ"],[7977,1,"ἡ"],[7978,1,"ἢ"],[7979,1,"ἣ"],[7980,1,"ἤ"],[7981,1,"ἥ"],[7982,1,"ἦ"],[7983,1,"ἧ"],[[7984,7991],2],[7992,1,"ἰ"],[7993,1,"ἱ"],[7994,1,"ἲ"],[7995,1,"ἳ"],[7996,1,"ἴ"],[7997,1,"ἵ"],[7998,1,"ἶ"],[7999,1,"ἷ"],[[8000,8005],2],[[8006,8007],3],[8008,1,"ὀ"],[8009,1,"ὁ"],[8010,1,"ὂ"],[8011,1,"ὃ"],[8012,1,"ὄ"],[8013,1,"ὅ"],[[8014,8015],3],[[8016,8023],2],[8024,3],[8025,1,"ὑ"],[8026,3],[8027,1,"ὓ"],[8028,3],[8029,1,"ὕ"],[8030,3],[8031,1,"ὗ"],[[8032,8039],2],[8040,1,"ὠ"],[8041,1,"ὡ"],[8042,1,"ὢ"],[8043,1,"ὣ"],[8044,1,"ὤ"],[8045,1,"ὥ"],[8046,1,"ὦ"],[8047,1,"ὧ"],[8048,2],[8049,1,"ά"],[8050,2],[8051,1,"έ"],[8052,2],[8053,1,"ή"],[8054,2],[8055,1,"ί"],[8056,2],[8057,1,"ό"],[8058,2],[8059,1,"ύ"],[8060,2],[8061,1,"ώ"],[[8062,8063],3],[8064,1,"ἀι"],[8065,1,"ἁι"],[8066,1,"ἂι"],[8067,1,"ἃι"],[8068,1,"ἄι"],[8069,1,"ἅι"],[8070,1,"ἆι"],[8071,1,"ἇι"],[8072,1,"ἀι"],[8073,1,"ἁι"],[8074,1,"ἂι"],[8075,1,"ἃι"],[8076,1,"ἄι"],[8077,1,"ἅι"],[8078,1,"ἆι"],[8079,1,"ἇι"],[8080,1,"ἠι"],[8081,1,"ἡι"],[8082,1,"ἢι"],[8083,1,"ἣι"],[8084,1,"ἤι"],[8085,1,"ἥι"],[8086,1,"ἦι"],[8087,1,"ἧι"],[8088,1,"ἠι"],[8089,1,"ἡι"],[8090,1,"ἢι"],[8091,1,"ἣι"],[8092,1,"ἤι"],[8093,1,"ἥι"],[8094,1,"ἦι"],[8095,1,"ἧι"],[8096,1,"ὠι"],[8097,1,"ὡι"],[8098,1,"ὢι"],[8099,1,"ὣι"],[8100,1,"ὤι"],[8101,1,"ὥι"],[8102,1,"ὦι"],[8103,1,"ὧι"],[8104,1,"ὠι"],[8105,1,"ὡι"],[8106,1,"ὢι"],[8107,1,"ὣι"],[8108,1,"ὤι"],[8109,1,"ὥι"],[8110,1,"ὦι"],[8111,1,"ὧι"],[[8112,8113],2],[8114,1,"ὰι"],[8115,1,"αι"],[8116,1,"άι"],[8117,3],[8118,2],[8119,1,"ᾶι"],[8120,1,"ᾰ"],[8121,1,"ᾱ"],[8122,1,"ὰ"],[8123,1,"ά"],[8124,1,"αι"],[8125,5," ̓"],[8126,1,"ι"],[8127,5," ̓"],[8128,5," ͂"],[8129,5," ̈͂"],[8130,1,"ὴι"],[8131,1,"ηι"],[8132,1,"ήι"],[8133,3],[8134,2],[8135,1,"ῆι"],[8136,1,"ὲ"],[8137,1,"έ"],[8138,1,"ὴ"],[8139,1,"ή"],[8140,1,"ηι"],[8141,5," ̓̀"],[8142,5," ̓́"],[8143,5," ̓͂"],[[8144,8146],2],[8147,1,"ΐ"],[[8148,8149],3],[[8150,8151],2],[8152,1,"ῐ"],[8153,1,"ῑ"],[8154,1,"ὶ"],[8155,1,"ί"],[8156,3],[8157,5," ̔̀"],[8158,5," ̔́"],[8159,5," ̔͂"],[[8160,8162],2],[8163,1,"ΰ"],[[8164,8167],2],[8168,1,"ῠ"],[8169,1,"ῡ"],[8170,1,"ὺ"],[8171,1,"ύ"],[8172,1,"ῥ"],[8173,5," ̈̀"],[8174,5," ̈́"],[8175,5,"`"],[[8176,8177],3],[8178,1,"ὼι"],[8179,1,"ωι"],[8180,1,"ώι"],[8181,3],[8182,2],[8183,1,"ῶι"],[8184,1,"ὸ"],[8185,1,"ό"],[8186,1,"ὼ"],[8187,1,"ώ"],[8188,1,"ωι"],[8189,5," ́"],[8190,5," ̔"],[8191,3],[[8192,8202],5," "],[8203,7],[[8204,8205],6,""],[[8206,8207],3],[8208,2],[8209,1,"‐"],[[8210,8214],2],[8215,5," ̳"],[[8216,8227],2],[[8228,8230],3],[8231,2],[[8232,8238],3],[8239,5," "],[[8240,8242],2],[8243,1,"′′"],[8244,1,"′′′"],[8245,2],[8246,1,"‵‵"],[8247,1,"‵‵‵"],[[8248,8251],2],[8252,5,"!!"],[8253,2],[8254,5," ̅"],[[8255,8262],2],[8263,5,"??"],[8264,5,"?!"],[8265,5,"!?"],[[8266,8269],2],[[8270,8274],2],[[8275,8276],2],[[8277,8278],2],[8279,1,"′′′′"],[[8280,8286],2],[8287,5," "],[8288,7],[[8289,8291],3],[8292,7],[8293,3],[[8294,8297],3],[[8298,8303],3],[8304,1,"0"],[8305,1,"i"],[[8306,8307],3],[8308,1,"4"],[8309,1,"5"],[8310,1,"6"],[8311,1,"7"],[8312,1,"8"],[8313,1,"9"],[8314,5,"+"],[8315,1,"−"],[8316,5,"="],[8317,5,"("],[8318,5,")"],[8319,1,"n"],[8320,1,"0"],[8321,1,"1"],[8322,1,"2"],[8323,1,"3"],[8324,1,"4"],[8325,1,"5"],[8326,1,"6"],[8327,1,"7"],[8328,1,"8"],[8329,1,"9"],[8330,5,"+"],[8331,1,"−"],[8332,5,"="],[8333,5,"("],[8334,5,")"],[8335,3],[8336,1,"a"],[8337,1,"e"],[8338,1,"o"],[8339,1,"x"],[8340,1,"ə"],[8341,1,"h"],[8342,1,"k"],[8343,1,"l"],[8344,1,"m"],[8345,1,"n"],[8346,1,"p"],[8347,1,"s"],[8348,1,"t"],[[8349,8351],3],[[8352,8359],2],[8360,1,"rs"],[[8361,8362],2],[8363,2],[8364,2],[[8365,8367],2],[[8368,8369],2],[[8370,8373],2],[[8374,8376],2],[8377,2],[8378,2],[[8379,8381],2],[8382,2],[8383,2],[8384,2],[[8385,8399],3],[[8400,8417],2],[[8418,8419],2],[[8420,8426],2],[8427,2],[[8428,8431],2],[8432,2],[[8433,8447],3],[8448,5,"a/c"],[8449,5,"a/s"],[8450,1,"c"],[8451,1,"°c"],[8452,2],[8453,5,"c/o"],[8454,5,"c/u"],[8455,1,"ɛ"],[8456,2],[8457,1,"°f"],[8458,1,"g"],[[8459,8462],1,"h"],[8463,1,"ħ"],[[8464,8465],1,"i"],[[8466,8467],1,"l"],[8468,2],[8469,1,"n"],[8470,1,"no"],[[8471,8472],2],[8473,1,"p"],[8474,1,"q"],[[8475,8477],1,"r"],[[8478,8479],2],[8480,1,"sm"],[8481,1,"tel"],[8482,1,"tm"],[8483,2],[8484,1,"z"],[8485,2],[8486,1,"ω"],[8487,2],[8488,1,"z"],[8489,2],[8490,1,"k"],[8491,1,"å"],[8492,1,"b"],[8493,1,"c"],[8494,2],[[8495,8496],1,"e"],[8497,1,"f"],[8498,3],[8499,1,"m"],[8500,1,"o"],[8501,1,"א"],[8502,1,"ב"],[8503,1,"ג"],[8504,1,"ד"],[8505,1,"i"],[8506,2],[8507,1,"fax"],[8508,1,"π"],[[8509,8510],1,"γ"],[8511,1,"π"],[8512,1,"∑"],[[8513,8516],2],[[8517,8518],1,"d"],[8519,1,"e"],[8520,1,"i"],[8521,1,"j"],[[8522,8523],2],[8524,2],[8525,2],[8526,2],[8527,2],[8528,1,"1⁄7"],[8529,1,"1⁄9"],[8530,1,"1⁄10"],[8531,1,"1⁄3"],[8532,1,"2⁄3"],[8533,1,"1⁄5"],[8534,1,"2⁄5"],[8535,1,"3⁄5"],[8536,1,"4⁄5"],[8537,1,"1⁄6"],[8538,1,"5⁄6"],[8539,1,"1⁄8"],[8540,1,"3⁄8"],[8541,1,"5⁄8"],[8542,1,"7⁄8"],[8543,1,"1⁄"],[8544,1,"i"],[8545,1,"ii"],[8546,1,"iii"],[8547,1,"iv"],[8548,1,"v"],[8549,1,"vi"],[8550,1,"vii"],[8551,1,"viii"],[8552,1,"ix"],[8553,1,"x"],[8554,1,"xi"],[8555,1,"xii"],[8556,1,"l"],[8557,1,"c"],[8558,1,"d"],[8559,1,"m"],[8560,1,"i"],[8561,1,"ii"],[8562,1,"iii"],[8563,1,"iv"],[8564,1,"v"],[8565,1,"vi"],[8566,1,"vii"],[8567,1,"viii"],[8568,1,"ix"],[8569,1,"x"],[8570,1,"xi"],[8571,1,"xii"],[8572,1,"l"],[8573,1,"c"],[8574,1,"d"],[8575,1,"m"],[[8576,8578],2],[8579,3],[8580,2],[[8581,8584],2],[8585,1,"0⁄3"],[[8586,8587],2],[[8588,8591],3],[[8592,8682],2],[[8683,8691],2],[[8692,8703],2],[[8704,8747],2],[8748,1,"∫∫"],[8749,1,"∫∫∫"],[8750,2],[8751,1,"∮∮"],[8752,1,"∮∮∮"],[[8753,8799],2],[8800,4],[[8801,8813],2],[[8814,8815],4],[[8816,8945],2],[[8946,8959],2],[8960,2],[8961,2],[[8962,9000],2],[9001,1,"〈"],[9002,1,"〉"],[[9003,9082],2],[9083,2],[9084,2],[[9085,9114],2],[[9115,9166],2],[[9167,9168],2],[[9169,9179],2],[[9180,9191],2],[9192,2],[[9193,9203],2],[[9204,9210],2],[[9211,9214],2],[9215,2],[[9216,9252],2],[[9253,9254],2],[[9255,9279],3],[[9280,9290],2],[[9291,9311],3],[9312,1,"1"],[9313,1,"2"],[9314,1,"3"],[9315,1,"4"],[9316,1,"5"],[9317,1,"6"],[9318,1,"7"],[9319,1,"8"],[9320,1,"9"],[9321,1,"10"],[9322,1,"11"],[9323,1,"12"],[9324,1,"13"],[9325,1,"14"],[9326,1,"15"],[9327,1,"16"],[9328,1,"17"],[9329,1,"18"],[9330,1,"19"],[9331,1,"20"],[9332,5,"(1)"],[9333,5,"(2)"],[9334,5,"(3)"],[9335,5,"(4)"],[9336,5,"(5)"],[9337,5,"(6)"],[9338,5,"(7)"],[9339,5,"(8)"],[9340,5,"(9)"],[9341,5,"(10)"],[9342,5,"(11)"],[9343,5,"(12)"],[9344,5,"(13)"],[9345,5,"(14)"],[9346,5,"(15)"],[9347,5,"(16)"],[9348,5,"(17)"],[9349,5,"(18)"],[9350,5,"(19)"],[9351,5,"(20)"],[[9352,9371],3],[9372,5,"(a)"],[9373,5,"(b)"],[9374,5,"(c)"],[9375,5,"(d)"],[9376,5,"(e)"],[9377,5,"(f)"],[9378,5,"(g)"],[9379,5,"(h)"],[9380,5,"(i)"],[9381,5,"(j)"],[9382,5,"(k)"],[9383,5,"(l)"],[9384,5,"(m)"],[9385,5,"(n)"],[9386,5,"(o)"],[9387,5,"(p)"],[9388,5,"(q)"],[9389,5,"(r)"],[9390,5,"(s)"],[9391,5,"(t)"],[9392,5,"(u)"],[9393,5,"(v)"],[9394,5,"(w)"],[9395,5,"(x)"],[9396,5,"(y)"],[9397,5,"(z)"],[9398,1,"a"],[9399,1,"b"],[9400,1,"c"],[9401,1,"d"],[9402,1,"e"],[9403,1,"f"],[9404,1,"g"],[9405,1,"h"],[9406,1,"i"],[9407,1,"j"],[9408,1,"k"],[9409,1,"l"],[9410,1,"m"],[9411,1,"n"],[9412,1,"o"],[9413,1,"p"],[9414,1,"q"],[9415,1,"r"],[9416,1,"s"],[9417,1,"t"],[9418,1,"u"],[9419,1,"v"],[9420,1,"w"],[9421,1,"x"],[9422,1,"y"],[9423,1,"z"],[9424,1,"a"],[9425,1,"b"],[9426,1,"c"],[9427,1,"d"],[9428,1,"e"],[9429,1,"f"],[9430,1,"g"],[9431,1,"h"],[9432,1,"i"],[9433,1,"j"],[9434,1,"k"],[9435,1,"l"],[9436,1,"m"],[9437,1,"n"],[9438,1,"o"],[9439,1,"p"],[9440,1,"q"],[9441,1,"r"],[9442,1,"s"],[9443,1,"t"],[9444,1,"u"],[9445,1,"v"],[9446,1,"w"],[9447,1,"x"],[9448,1,"y"],[9449,1,"z"],[9450,1,"0"],[[9451,9470],2],[9471,2],[[9472,9621],2],[[9622,9631],2],[[9632,9711],2],[[9712,9719],2],[[9720,9727],2],[[9728,9747],2],[[9748,9749],2],[[9750,9751],2],[9752,2],[9753,2],[[9754,9839],2],[[9840,9841],2],[[9842,9853],2],[[9854,9855],2],[[9856,9865],2],[[9866,9873],2],[[9874,9884],2],[9885,2],[[9886,9887],2],[[9888,9889],2],[[9890,9905],2],[9906,2],[[9907,9916],2],[[9917,9919],2],[[9920,9923],2],[[9924,9933],2],[9934,2],[[9935,9953],2],[9954,2],[9955,2],[[9956,9959],2],[[9960,9983],2],[9984,2],[[9985,9988],2],[9989,2],[[9990,9993],2],[[9994,9995],2],[[9996,10023],2],[10024,2],[[10025,10059],2],[10060,2],[10061,2],[10062,2],[[10063,10066],2],[[10067,10069],2],[10070,2],[10071,2],[[10072,10078],2],[[10079,10080],2],[[10081,10087],2],[[10088,10101],2],[[10102,10132],2],[[10133,10135],2],[[10136,10159],2],[10160,2],[[10161,10174],2],[10175,2],[[10176,10182],2],[[10183,10186],2],[10187,2],[10188,2],[10189,2],[[10190,10191],2],[[10192,10219],2],[[10220,10223],2],[[10224,10239],2],[[10240,10495],2],[[10496,10763],2],[10764,1,"∫∫∫∫"],[[10765,10867],2],[10868,5,"::="],[10869,5,"=="],[10870,5,"==="],[[10871,10971],2],[10972,1,"⫝̸"],[[10973,11007],2],[[11008,11021],2],[[11022,11027],2],[[11028,11034],2],[[11035,11039],2],[[11040,11043],2],[[11044,11084],2],[[11085,11087],2],[[11088,11092],2],[[11093,11097],2],[[11098,11123],2],[[11124,11125],3],[[11126,11157],2],[11158,3],[11159,2],[[11160,11193],2],[[11194,11196],2],[[11197,11208],2],[11209,2],[[11210,11217],2],[11218,2],[[11219,11243],2],[[11244,11247],2],[[11248,11262],2],[11263,2],[11264,1,"ⰰ"],[11265,1,"ⰱ"],[11266,1,"ⰲ"],[11267,1,"ⰳ"],[11268,1,"ⰴ"],[11269,1,"ⰵ"],[11270,1,"ⰶ"],[11271,1,"ⰷ"],[11272,1,"ⰸ"],[11273,1,"ⰹ"],[11274,1,"ⰺ"],[11275,1,"ⰻ"],[11276,1,"ⰼ"],[11277,1,"ⰽ"],[11278,1,"ⰾ"],[11279,1,"ⰿ"],[11280,1,"ⱀ"],[11281,1,"ⱁ"],[11282,1,"ⱂ"],[11283,1,"ⱃ"],[11284,1,"ⱄ"],[11285,1,"ⱅ"],[11286,1,"ⱆ"],[11287,1,"ⱇ"],[11288,1,"ⱈ"],[11289,1,"ⱉ"],[11290,1,"ⱊ"],[11291,1,"ⱋ"],[11292,1,"ⱌ"],[11293,1,"ⱍ"],[11294,1,"ⱎ"],[11295,1,"ⱏ"],[11296,1,"ⱐ"],[11297,1,"ⱑ"],[11298,1,"ⱒ"],[11299,1,"ⱓ"],[11300,1,"ⱔ"],[11301,1,"ⱕ"],[11302,1,"ⱖ"],[11303,1,"ⱗ"],[11304,1,"ⱘ"],[11305,1,"ⱙ"],[11306,1,"ⱚ"],[11307,1,"ⱛ"],[11308,1,"ⱜ"],[11309,1,"ⱝ"],[11310,1,"ⱞ"],[11311,1,"ⱟ"],[[11312,11358],2],[11359,2],[11360,1,"ⱡ"],[11361,2],[11362,1,"ɫ"],[11363,1,"ᵽ"],[11364,1,"ɽ"],[[11365,11366],2],[11367,1,"ⱨ"],[11368,2],[11369,1,"ⱪ"],[11370,2],[11371,1,"ⱬ"],[11372,2],[11373,1,"ɑ"],[11374,1,"ɱ"],[11375,1,"ɐ"],[11376,1,"ɒ"],[11377,2],[11378,1,"ⱳ"],[11379,2],[11380,2],[11381,1,"ⱶ"],[[11382,11383],2],[[11384,11387],2],[11388,1,"j"],[11389,1,"v"],[11390,1,"ȿ"],[11391,1,"ɀ"],[11392,1,"ⲁ"],[11393,2],[11394,1,"ⲃ"],[11395,2],[11396,1,"ⲅ"],[11397,2],[11398,1,"ⲇ"],[11399,2],[11400,1,"ⲉ"],[11401,2],[11402,1,"ⲋ"],[11403,2],[11404,1,"ⲍ"],[11405,2],[11406,1,"ⲏ"],[11407,2],[11408,1,"ⲑ"],[11409,2],[11410,1,"ⲓ"],[11411,2],[11412,1,"ⲕ"],[11413,2],[11414,1,"ⲗ"],[11415,2],[11416,1,"ⲙ"],[11417,2],[11418,1,"ⲛ"],[11419,2],[11420,1,"ⲝ"],[11421,2],[11422,1,"ⲟ"],[11423,2],[11424,1,"ⲡ"],[11425,2],[11426,1,"ⲣ"],[11427,2],[11428,1,"ⲥ"],[11429,2],[11430,1,"ⲧ"],[11431,2],[11432,1,"ⲩ"],[11433,2],[11434,1,"ⲫ"],[11435,2],[11436,1,"ⲭ"],[11437,2],[11438,1,"ⲯ"],[11439,2],[11440,1,"ⲱ"],[11441,2],[11442,1,"ⲳ"],[11443,2],[11444,1,"ⲵ"],[11445,2],[11446,1,"ⲷ"],[11447,2],[11448,1,"ⲹ"],[11449,2],[11450,1,"ⲻ"],[11451,2],[11452,1,"ⲽ"],[11453,2],[11454,1,"ⲿ"],[11455,2],[11456,1,"ⳁ"],[11457,2],[11458,1,"ⳃ"],[11459,2],[11460,1,"ⳅ"],[11461,2],[11462,1,"ⳇ"],[11463,2],[11464,1,"ⳉ"],[11465,2],[11466,1,"ⳋ"],[11467,2],[11468,1,"ⳍ"],[11469,2],[11470,1,"ⳏ"],[11471,2],[11472,1,"ⳑ"],[11473,2],[11474,1,"ⳓ"],[11475,2],[11476,1,"ⳕ"],[11477,2],[11478,1,"ⳗ"],[11479,2],[11480,1,"ⳙ"],[11481,2],[11482,1,"ⳛ"],[11483,2],[11484,1,"ⳝ"],[11485,2],[11486,1,"ⳟ"],[11487,2],[11488,1,"ⳡ"],[11489,2],[11490,1,"ⳣ"],[[11491,11492],2],[[11493,11498],2],[11499,1,"ⳬ"],[11500,2],[11501,1,"ⳮ"],[[11502,11505],2],[11506,1,"ⳳ"],[11507,2],[[11508,11512],3],[[11513,11519],2],[[11520,11557],2],[11558,3],[11559,2],[[11560,11564],3],[11565,2],[[11566,11567],3],[[11568,11621],2],[[11622,11623],2],[[11624,11630],3],[11631,1,"ⵡ"],[11632,2],[[11633,11646],3],[11647,2],[[11648,11670],2],[[11671,11679],3],[[11680,11686],2],[11687,3],[[11688,11694],2],[11695,3],[[11696,11702],2],[11703,3],[[11704,11710],2],[11711,3],[[11712,11718],2],[11719,3],[[11720,11726],2],[11727,3],[[11728,11734],2],[11735,3],[[11736,11742],2],[11743,3],[[11744,11775],2],[[11776,11799],2],[[11800,11803],2],[[11804,11805],2],[[11806,11822],2],[11823,2],[11824,2],[11825,2],[[11826,11835],2],[[11836,11842],2],[[11843,11844],2],[[11845,11849],2],[[11850,11854],2],[11855,2],[[11856,11858],2],[[11859,11869],2],[[11870,11903],3],[[11904,11929],2],[11930,3],[[11931,11934],2],[11935,1,"母"],[[11936,12018],2],[12019,1,"龟"],[[12020,12031],3],[12032,1,"一"],[12033,1,"丨"],[12034,1,"丶"],[12035,1,"丿"],[12036,1,"乙"],[12037,1,"亅"],[12038,1,"二"],[12039,1,"亠"],[12040,1,"人"],[12041,1,"儿"],[12042,1,"入"],[12043,1,"八"],[12044,1,"冂"],[12045,1,"冖"],[12046,1,"冫"],[12047,1,"几"],[12048,1,"凵"],[12049,1,"刀"],[12050,1,"力"],[12051,1,"勹"],[12052,1,"匕"],[12053,1,"匚"],[12054,1,"匸"],[12055,1,"十"],[12056,1,"卜"],[12057,1,"卩"],[12058,1,"厂"],[12059,1,"厶"],[12060,1,"又"],[12061,1,"口"],[12062,1,"囗"],[12063,1,"土"],[12064,1,"士"],[12065,1,"夂"],[12066,1,"夊"],[12067,1,"夕"],[12068,1,"大"],[12069,1,"女"],[12070,1,"子"],[12071,1,"宀"],[12072,1,"寸"],[12073,1,"小"],[12074,1,"尢"],[12075,1,"尸"],[12076,1,"屮"],[12077,1,"山"],[12078,1,"巛"],[12079,1,"工"],[12080,1,"己"],[12081,1,"巾"],[12082,1,"干"],[12083,1,"幺"],[12084,1,"广"],[12085,1,"廴"],[12086,1,"廾"],[12087,1,"弋"],[12088,1,"弓"],[12089,1,"彐"],[12090,1,"彡"],[12091,1,"彳"],[12092,1,"心"],[12093,1,"戈"],[12094,1,"戶"],[12095,1,"手"],[12096,1,"支"],[12097,1,"攴"],[12098,1,"文"],[12099,1,"斗"],[12100,1,"斤"],[12101,1,"方"],[12102,1,"无"],[12103,1,"日"],[12104,1,"曰"],[12105,1,"月"],[12106,1,"木"],[12107,1,"欠"],[12108,1,"止"],[12109,1,"歹"],[12110,1,"殳"],[12111,1,"毋"],[12112,1,"比"],[12113,1,"毛"],[12114,1,"氏"],[12115,1,"气"],[12116,1,"水"],[12117,1,"火"],[12118,1,"爪"],[12119,1,"父"],[12120,1,"爻"],[12121,1,"爿"],[12122,1,"片"],[12123,1,"牙"],[12124,1,"牛"],[12125,1,"犬"],[12126,1,"玄"],[12127,1,"玉"],[12128,1,"瓜"],[12129,1,"瓦"],[12130,1,"甘"],[12131,1,"生"],[12132,1,"用"],[12133,1,"田"],[12134,1,"疋"],[12135,1,"疒"],[12136,1,"癶"],[12137,1,"白"],[12138,1,"皮"],[12139,1,"皿"],[12140,1,"目"],[12141,1,"矛"],[12142,1,"矢"],[12143,1,"石"],[12144,1,"示"],[12145,1,"禸"],[12146,1,"禾"],[12147,1,"穴"],[12148,1,"立"],[12149,1,"竹"],[12150,1,"米"],[12151,1,"糸"],[12152,1,"缶"],[12153,1,"网"],[12154,1,"羊"],[12155,1,"羽"],[12156,1,"老"],[12157,1,"而"],[12158,1,"耒"],[12159,1,"耳"],[12160,1,"聿"],[12161,1,"肉"],[12162,1,"臣"],[12163,1,"自"],[12164,1,"至"],[12165,1,"臼"],[12166,1,"舌"],[12167,1,"舛"],[12168,1,"舟"],[12169,1,"艮"],[12170,1,"色"],[12171,1,"艸"],[12172,1,"虍"],[12173,1,"虫"],[12174,1,"血"],[12175,1,"行"],[12176,1,"衣"],[12177,1,"襾"],[12178,1,"見"],[12179,1,"角"],[12180,1,"言"],[12181,1,"谷"],[12182,1,"豆"],[12183,1,"豕"],[12184,1,"豸"],[12185,1,"貝"],[12186,1,"赤"],[12187,1,"走"],[12188,1,"足"],[12189,1,"身"],[12190,1,"車"],[12191,1,"辛"],[12192,1,"辰"],[12193,1,"辵"],[12194,1,"邑"],[12195,1,"酉"],[12196,1,"釆"],[12197,1,"里"],[12198,1,"金"],[12199,1,"長"],[12200,1,"門"],[12201,1,"阜"],[12202,1,"隶"],[12203,1,"隹"],[12204,1,"雨"],[12205,1,"靑"],[12206,1,"非"],[12207,1,"面"],[12208,1,"革"],[12209,1,"韋"],[12210,1,"韭"],[12211,1,"音"],[12212,1,"頁"],[12213,1,"風"],[12214,1,"飛"],[12215,1,"食"],[12216,1,"首"],[12217,1,"香"],[12218,1,"馬"],[12219,1,"骨"],[12220,1,"高"],[12221,1,"髟"],[12222,1,"鬥"],[12223,1,"鬯"],[12224,1,"鬲"],[12225,1,"鬼"],[12226,1,"魚"],[12227,1,"鳥"],[12228,1,"鹵"],[12229,1,"鹿"],[12230,1,"麥"],[12231,1,"麻"],[12232,1,"黃"],[12233,1,"黍"],[12234,1,"黑"],[12235,1,"黹"],[12236,1,"黽"],[12237,1,"鼎"],[12238,1,"鼓"],[12239,1,"鼠"],[12240,1,"鼻"],[12241,1,"齊"],[12242,1,"齒"],[12243,1,"龍"],[12244,1,"龜"],[12245,1,"龠"],[[12246,12271],3],[[12272,12283],3],[[12284,12287],3],[12288,5," "],[12289,2],[12290,1,"."],[[12291,12292],2],[[12293,12295],2],[[12296,12329],2],[[12330,12333],2],[[12334,12341],2],[12342,1,"〒"],[12343,2],[12344,1,"十"],[12345,1,"卄"],[12346,1,"卅"],[12347,2],[12348,2],[12349,2],[12350,2],[12351,2],[12352,3],[[12353,12436],2],[[12437,12438],2],[[12439,12440],3],[[12441,12442],2],[12443,5," ゙"],[12444,5," ゚"],[[12445,12446],2],[12447,1,"より"],[12448,2],[[12449,12542],2],[12543,1,"コト"],[[12544,12548],3],[[12549,12588],2],[12589,2],[12590,2],[12591,2],[12592,3],[12593,1,"ᄀ"],[12594,1,"ᄁ"],[12595,1,"ᆪ"],[12596,1,"ᄂ"],[12597,1,"ᆬ"],[12598,1,"ᆭ"],[12599,1,"ᄃ"],[12600,1,"ᄄ"],[12601,1,"ᄅ"],[12602,1,"ᆰ"],[12603,1,"ᆱ"],[12604,1,"ᆲ"],[12605,1,"ᆳ"],[12606,1,"ᆴ"],[12607,1,"ᆵ"],[12608,1,"ᄚ"],[12609,1,"ᄆ"],[12610,1,"ᄇ"],[12611,1,"ᄈ"],[12612,1,"ᄡ"],[12613,1,"ᄉ"],[12614,1,"ᄊ"],[12615,1,"ᄋ"],[12616,1,"ᄌ"],[12617,1,"ᄍ"],[12618,1,"ᄎ"],[12619,1,"ᄏ"],[12620,1,"ᄐ"],[12621,1,"ᄑ"],[12622,1,"ᄒ"],[12623,1,"ᅡ"],[12624,1,"ᅢ"],[12625,1,"ᅣ"],[12626,1,"ᅤ"],[12627,1,"ᅥ"],[12628,1,"ᅦ"],[12629,1,"ᅧ"],[12630,1,"ᅨ"],[12631,1,"ᅩ"],[12632,1,"ᅪ"],[12633,1,"ᅫ"],[12634,1,"ᅬ"],[12635,1,"ᅭ"],[12636,1,"ᅮ"],[12637,1,"ᅯ"],[12638,1,"ᅰ"],[12639,1,"ᅱ"],[12640,1,"ᅲ"],[12641,1,"ᅳ"],[12642,1,"ᅴ"],[12643,1,"ᅵ"],[12644,3],[12645,1,"ᄔ"],[12646,1,"ᄕ"],[12647,1,"ᇇ"],[12648,1,"ᇈ"],[12649,1,"ᇌ"],[12650,1,"ᇎ"],[12651,1,"ᇓ"],[12652,1,"ᇗ"],[12653,1,"ᇙ"],[12654,1,"ᄜ"],[12655,1,"ᇝ"],[12656,1,"ᇟ"],[12657,1,"ᄝ"],[12658,1,"ᄞ"],[12659,1,"ᄠ"],[12660,1,"ᄢ"],[12661,1,"ᄣ"],[12662,1,"ᄧ"],[12663,1,"ᄩ"],[12664,1,"ᄫ"],[12665,1,"ᄬ"],[12666,1,"ᄭ"],[12667,1,"ᄮ"],[12668,1,"ᄯ"],[12669,1,"ᄲ"],[12670,1,"ᄶ"],[12671,1,"ᅀ"],[12672,1,"ᅇ"],[12673,1,"ᅌ"],[12674,1,"ᇱ"],[12675,1,"ᇲ"],[12676,1,"ᅗ"],[12677,1,"ᅘ"],[12678,1,"ᅙ"],[12679,1,"ᆄ"],[12680,1,"ᆅ"],[12681,1,"ᆈ"],[12682,1,"ᆑ"],[12683,1,"ᆒ"],[12684,1,"ᆔ"],[12685,1,"ᆞ"],[12686,1,"ᆡ"],[12687,3],[[12688,12689],2],[12690,1,"一"],[12691,1,"二"],[12692,1,"三"],[12693,1,"四"],[12694,1,"上"],[12695,1,"中"],[12696,1,"下"],[12697,1,"甲"],[12698,1,"乙"],[12699,1,"丙"],[12700,1,"丁"],[12701,1,"天"],[12702,1,"地"],[12703,1,"人"],[[12704,12727],2],[[12728,12730],2],[[12731,12735],2],[[12736,12751],2],[[12752,12771],2],[[12772,12783],3],[[12784,12799],2],[12800,5,"(ᄀ)"],[12801,5,"(ᄂ)"],[12802,5,"(ᄃ)"],[12803,5,"(ᄅ)"],[12804,5,"(ᄆ)"],[12805,5,"(ᄇ)"],[12806,5,"(ᄉ)"],[12807,5,"(ᄋ)"],[12808,5,"(ᄌ)"],[12809,5,"(ᄎ)"],[12810,5,"(ᄏ)"],[12811,5,"(ᄐ)"],[12812,5,"(ᄑ)"],[12813,5,"(ᄒ)"],[12814,5,"(가)"],[12815,5,"(나)"],[12816,5,"(다)"],[12817,5,"(라)"],[12818,5,"(마)"],[12819,5,"(바)"],[12820,5,"(사)"],[12821,5,"(아)"],[12822,5,"(자)"],[12823,5,"(차)"],[12824,5,"(카)"],[12825,5,"(타)"],[12826,5,"(파)"],[12827,5,"(하)"],[12828,5,"(주)"],[12829,5,"(오전)"],[12830,5,"(오후)"],[12831,3],[12832,5,"(一)"],[12833,5,"(二)"],[12834,5,"(三)"],[12835,5,"(四)"],[12836,5,"(五)"],[12837,5,"(六)"],[12838,5,"(七)"],[12839,5,"(八)"],[12840,5,"(九)"],[12841,5,"(十)"],[12842,5,"(月)"],[12843,5,"(火)"],[12844,5,"(水)"],[12845,5,"(木)"],[12846,5,"(金)"],[12847,5,"(土)"],[12848,5,"(日)"],[12849,5,"(株)"],[12850,5,"(有)"],[12851,5,"(社)"],[12852,5,"(名)"],[12853,5,"(特)"],[12854,5,"(財)"],[12855,5,"(祝)"],[12856,5,"(労)"],[12857,5,"(代)"],[12858,5,"(呼)"],[12859,5,"(学)"],[12860,5,"(監)"],[12861,5,"(企)"],[12862,5,"(資)"],[12863,5,"(協)"],[12864,5,"(祭)"],[12865,5,"(休)"],[12866,5,"(自)"],[12867,5,"(至)"],[12868,1,"問"],[12869,1,"幼"],[12870,1,"文"],[12871,1,"箏"],[[12872,12879],2],[12880,1,"pte"],[12881,1,"21"],[12882,1,"22"],[12883,1,"23"],[12884,1,"24"],[12885,1,"25"],[12886,1,"26"],[12887,1,"27"],[12888,1,"28"],[12889,1,"29"],[12890,1,"30"],[12891,1,"31"],[12892,1,"32"],[12893,1,"33"],[12894,1,"34"],[12895,1,"35"],[12896,1,"ᄀ"],[12897,1,"ᄂ"],[12898,1,"ᄃ"],[12899,1,"ᄅ"],[12900,1,"ᄆ"],[12901,1,"ᄇ"],[12902,1,"ᄉ"],[12903,1,"ᄋ"],[12904,1,"ᄌ"],[12905,1,"ᄎ"],[12906,1,"ᄏ"],[12907,1,"ᄐ"],[12908,1,"ᄑ"],[12909,1,"ᄒ"],[12910,1,"가"],[12911,1,"나"],[12912,1,"다"],[12913,1,"라"],[12914,1,"마"],[12915,1,"바"],[12916,1,"사"],[12917,1,"아"],[12918,1,"자"],[12919,1,"차"],[12920,1,"카"],[12921,1,"타"],[12922,1,"파"],[12923,1,"하"],[12924,1,"참고"],[12925,1,"주의"],[12926,1,"우"],[12927,2],[12928,1,"一"],[12929,1,"二"],[12930,1,"三"],[12931,1,"四"],[12932,1,"五"],[12933,1,"六"],[12934,1,"七"],[12935,1,"八"],[12936,1,"九"],[12937,1,"十"],[12938,1,"月"],[12939,1,"火"],[12940,1,"水"],[12941,1,"木"],[12942,1,"金"],[12943,1,"土"],[12944,1,"日"],[12945,1,"株"],[12946,1,"有"],[12947,1,"社"],[12948,1,"名"],[12949,1,"特"],[12950,1,"財"],[12951,1,"祝"],[12952,1,"労"],[12953,1,"秘"],[12954,1,"男"],[12955,1,"女"],[12956,1,"適"],[12957,1,"優"],[12958,1,"印"],[12959,1,"注"],[12960,1,"項"],[12961,1,"休"],[12962,1,"写"],[12963,1,"正"],[12964,1,"上"],[12965,1,"中"],[12966,1,"下"],[12967,1,"左"],[12968,1,"右"],[12969,1,"医"],[12970,1,"宗"],[12971,1,"学"],[12972,1,"監"],[12973,1,"企"],[12974,1,"資"],[12975,1,"協"],[12976,1,"夜"],[12977,1,"36"],[12978,1,"37"],[12979,1,"38"],[12980,1,"39"],[12981,1,"40"],[12982,1,"41"],[12983,1,"42"],[12984,1,"43"],[12985,1,"44"],[12986,1,"45"],[12987,1,"46"],[12988,1,"47"],[12989,1,"48"],[12990,1,"49"],[12991,1,"50"],[12992,1,"1月"],[12993,1,"2月"],[12994,1,"3月"],[12995,1,"4月"],[12996,1,"5月"],[12997,1,"6月"],[12998,1,"7月"],[12999,1,"8月"],[13000,1,"9月"],[13001,1,"10月"],[13002,1,"11月"],[13003,1,"12月"],[13004,1,"hg"],[13005,1,"erg"],[13006,1,"ev"],[13007,1,"ltd"],[13008,1,"ア"],[13009,1,"イ"],[13010,1,"ウ"],[13011,1,"エ"],[13012,1,"オ"],[13013,1,"カ"],[13014,1,"キ"],[13015,1,"ク"],[13016,1,"ケ"],[13017,1,"コ"],[13018,1,"サ"],[13019,1,"シ"],[13020,1,"ス"],[13021,1,"セ"],[13022,1,"ソ"],[13023,1,"タ"],[13024,1,"チ"],[13025,1,"ツ"],[13026,1,"テ"],[13027,1,"ト"],[13028,1,"ナ"],[13029,1,"ニ"],[13030,1,"ヌ"],[13031,1,"ネ"],[13032,1,"ノ"],[13033,1,"ハ"],[13034,1,"ヒ"],[13035,1,"フ"],[13036,1,"ヘ"],[13037,1,"ホ"],[13038,1,"マ"],[13039,1,"ミ"],[13040,1,"ム"],[13041,1,"メ"],[13042,1,"モ"],[13043,1,"ヤ"],[13044,1,"ユ"],[13045,1,"ヨ"],[13046,1,"ラ"],[13047,1,"リ"],[13048,1,"ル"],[13049,1,"レ"],[13050,1,"ロ"],[13051,1,"ワ"],[13052,1,"ヰ"],[13053,1,"ヱ"],[13054,1,"ヲ"],[13055,1,"令和"],[13056,1,"アパート"],[13057,1,"アルファ"],[13058,1,"アンペア"],[13059,1,"アール"],[13060,1,"イニング"],[13061,1,"インチ"],[13062,1,"ウォン"],[13063,1,"エスクード"],[13064,1,"エーカー"],[13065,1,"オンス"],[13066,1,"オーム"],[13067,1,"カイリ"],[13068,1,"カラット"],[13069,1,"カロリー"],[13070,1,"ガロン"],[13071,1,"ガンマ"],[13072,1,"ギガ"],[13073,1,"ギニー"],[13074,1,"キュリー"],[13075,1,"ギルダー"],[13076,1,"キロ"],[13077,1,"キログラム"],[13078,1,"キロメートル"],[13079,1,"キロワット"],[13080,1,"グラム"],[13081,1,"グラムトン"],[13082,1,"クルゼイロ"],[13083,1,"クローネ"],[13084,1,"ケース"],[13085,1,"コルナ"],[13086,1,"コーポ"],[13087,1,"サイクル"],[13088,1,"サンチーム"],[13089,1,"シリング"],[13090,1,"センチ"],[13091,1,"セント"],[13092,1,"ダース"],[13093,1,"デシ"],[13094,1,"ドル"],[13095,1,"トン"],[13096,1,"ナノ"],[13097,1,"ノット"],[13098,1,"ハイツ"],[13099,1,"パーセント"],[13100,1,"パーツ"],[13101,1,"バーレル"],[13102,1,"ピアストル"],[13103,1,"ピクル"],[13104,1,"ピコ"],[13105,1,"ビル"],[13106,1,"ファラッド"],[13107,1,"フィート"],[13108,1,"ブッシェル"],[13109,1,"フラン"],[13110,1,"ヘクタール"],[13111,1,"ペソ"],[13112,1,"ペニヒ"],[13113,1,"ヘルツ"],[13114,1,"ペンス"],[13115,1,"ページ"],[13116,1,"ベータ"],[13117,1,"ポイント"],[13118,1,"ボルト"],[13119,1,"ホン"],[13120,1,"ポンド"],[13121,1,"ホール"],[13122,1,"ホーン"],[13123,1,"マイクロ"],[13124,1,"マイル"],[13125,1,"マッハ"],[13126,1,"マルク"],[13127,1,"マンション"],[13128,1,"ミクロン"],[13129,1,"ミリ"],[13130,1,"ミリバール"],[13131,1,"メガ"],[13132,1,"メガトン"],[13133,1,"メートル"],[13134,1,"ヤード"],[13135,1,"ヤール"],[13136,1,"ユアン"],[13137,1,"リットル"],[13138,1,"リラ"],[13139,1,"ルピー"],[13140,1,"ルーブル"],[13141,1,"レム"],[13142,1,"レントゲン"],[13143,1,"ワット"],[13144,1,"0点"],[13145,1,"1点"],[13146,1,"2点"],[13147,1,"3点"],[13148,1,"4点"],[13149,1,"5点"],[13150,1,"6点"],[13151,1,"7点"],[13152,1,"8点"],[13153,1,"9点"],[13154,1,"10点"],[13155,1,"11点"],[13156,1,"12点"],[13157,1,"13点"],[13158,1,"14点"],[13159,1,"15点"],[13160,1,"16点"],[13161,1,"17点"],[13162,1,"18点"],[13163,1,"19点"],[13164,1,"20点"],[13165,1,"21点"],[13166,1,"22点"],[13167,1,"23点"],[13168,1,"24点"],[13169,1,"hpa"],[13170,1,"da"],[13171,1,"au"],[13172,1,"bar"],[13173,1,"ov"],[13174,1,"pc"],[13175,1,"dm"],[13176,1,"dm2"],[13177,1,"dm3"],[13178,1,"iu"],[13179,1,"平成"],[13180,1,"昭和"],[13181,1,"大正"],[13182,1,"明治"],[13183,1,"株式会社"],[13184,1,"pa"],[13185,1,"na"],[13186,1,"μa"],[13187,1,"ma"],[13188,1,"ka"],[13189,1,"kb"],[13190,1,"mb"],[13191,1,"gb"],[13192,1,"cal"],[13193,1,"kcal"],[13194,1,"pf"],[13195,1,"nf"],[13196,1,"μf"],[13197,1,"μg"],[13198,1,"mg"],[13199,1,"kg"],[13200,1,"hz"],[13201,1,"khz"],[13202,1,"mhz"],[13203,1,"ghz"],[13204,1,"thz"],[13205,1,"μl"],[13206,1,"ml"],[13207,1,"dl"],[13208,1,"kl"],[13209,1,"fm"],[13210,1,"nm"],[13211,1,"μm"],[13212,1,"mm"],[13213,1,"cm"],[13214,1,"km"],[13215,1,"mm2"],[13216,1,"cm2"],[13217,1,"m2"],[13218,1,"km2"],[13219,1,"mm3"],[13220,1,"cm3"],[13221,1,"m3"],[13222,1,"km3"],[13223,1,"m∕s"],[13224,1,"m∕s2"],[13225,1,"pa"],[13226,1,"kpa"],[13227,1,"mpa"],[13228,1,"gpa"],[13229,1,"rad"],[13230,1,"rad∕s"],[13231,1,"rad∕s2"],[13232,1,"ps"],[13233,1,"ns"],[13234,1,"μs"],[13235,1,"ms"],[13236,1,"pv"],[13237,1,"nv"],[13238,1,"μv"],[13239,1,"mv"],[13240,1,"kv"],[13241,1,"mv"],[13242,1,"pw"],[13243,1,"nw"],[13244,1,"μw"],[13245,1,"mw"],[13246,1,"kw"],[13247,1,"mw"],[13248,1,"kω"],[13249,1,"mω"],[13250,3],[13251,1,"bq"],[13252,1,"cc"],[13253,1,"cd"],[13254,1,"c∕kg"],[13255,3],[13256,1,"db"],[13257,1,"gy"],[13258,1,"ha"],[13259,1,"hp"],[13260,1,"in"],[13261,1,"kk"],[13262,1,"km"],[13263,1,"kt"],[13264,1,"lm"],[13265,1,"ln"],[13266,1,"log"],[13267,1,"lx"],[13268,1,"mb"],[13269,1,"mil"],[13270,1,"mol"],[13271,1,"ph"],[13272,3],[13273,1,"ppm"],[13274,1,"pr"],[13275,1,"sr"],[13276,1,"sv"],[13277,1,"wb"],[13278,1,"v∕m"],[13279,1,"a∕m"],[13280,1,"1日"],[13281,1,"2日"],[13282,1,"3日"],[13283,1,"4日"],[13284,1,"5日"],[13285,1,"6日"],[13286,1,"7日"],[13287,1,"8日"],[13288,1,"9日"],[13289,1,"10日"],[13290,1,"11日"],[13291,1,"12日"],[13292,1,"13日"],[13293,1,"14日"],[13294,1,"15日"],[13295,1,"16日"],[13296,1,"17日"],[13297,1,"18日"],[13298,1,"19日"],[13299,1,"20日"],[13300,1,"21日"],[13301,1,"22日"],[13302,1,"23日"],[13303,1,"24日"],[13304,1,"25日"],[13305,1,"26日"],[13306,1,"27日"],[13307,1,"28日"],[13308,1,"29日"],[13309,1,"30日"],[13310,1,"31日"],[13311,1,"gal"],[[13312,19893],2],[[19894,19903],2],[[19904,19967],2],[[19968,40869],2],[[40870,40891],2],[[40892,40899],2],[[40900,40907],2],[40908,2],[[40909,40917],2],[[40918,40938],2],[[40939,40943],2],[[40944,40956],2],[[40957,40959],2],[[40960,42124],2],[[42125,42127],3],[[42128,42145],2],[[42146,42147],2],[[42148,42163],2],[42164,2],[[42165,42176],2],[42177,2],[[42178,42180],2],[42181,2],[42182,2],[[42183,42191],3],[[42192,42237],2],[[42238,42239],2],[[42240,42508],2],[[42509,42511],2],[[42512,42539],2],[[42540,42559],3],[42560,1,"ꙁ"],[42561,2],[42562,1,"ꙃ"],[42563,2],[42564,1,"ꙅ"],[42565,2],[42566,1,"ꙇ"],[42567,2],[42568,1,"ꙉ"],[42569,2],[42570,1,"ꙋ"],[42571,2],[42572,1,"ꙍ"],[42573,2],[42574,1,"ꙏ"],[42575,2],[42576,1,"ꙑ"],[42577,2],[42578,1,"ꙓ"],[42579,2],[42580,1,"ꙕ"],[42581,2],[42582,1,"ꙗ"],[42583,2],[42584,1,"ꙙ"],[42585,2],[42586,1,"ꙛ"],[42587,2],[42588,1,"ꙝ"],[42589,2],[42590,1,"ꙟ"],[42591,2],[42592,1,"ꙡ"],[42593,2],[42594,1,"ꙣ"],[42595,2],[42596,1,"ꙥ"],[42597,2],[42598,1,"ꙧ"],[42599,2],[42600,1,"ꙩ"],[42601,2],[42602,1,"ꙫ"],[42603,2],[42604,1,"ꙭ"],[[42605,42607],2],[[42608,42611],2],[[42612,42619],2],[[42620,42621],2],[42622,2],[42623,2],[42624,1,"ꚁ"],[42625,2],[42626,1,"ꚃ"],[42627,2],[42628,1,"ꚅ"],[42629,2],[42630,1,"ꚇ"],[42631,2],[42632,1,"ꚉ"],[42633,2],[42634,1,"ꚋ"],[42635,2],[42636,1,"ꚍ"],[42637,2],[42638,1,"ꚏ"],[42639,2],[42640,1,"ꚑ"],[42641,2],[42642,1,"ꚓ"],[42643,2],[42644,1,"ꚕ"],[42645,2],[42646,1,"ꚗ"],[42647,2],[42648,1,"ꚙ"],[42649,2],[42650,1,"ꚛ"],[42651,2],[42652,1,"ъ"],[42653,1,"ь"],[42654,2],[42655,2],[[42656,42725],2],[[42726,42735],2],[[42736,42737],2],[[42738,42743],2],[[42744,42751],3],[[42752,42774],2],[[42775,42778],2],[[42779,42783],2],[[42784,42785],2],[42786,1,"ꜣ"],[42787,2],[42788,1,"ꜥ"],[42789,2],[42790,1,"ꜧ"],[42791,2],[42792,1,"ꜩ"],[42793,2],[42794,1,"ꜫ"],[42795,2],[42796,1,"ꜭ"],[42797,2],[42798,1,"ꜯ"],[[42799,42801],2],[42802,1,"ꜳ"],[42803,2],[42804,1,"ꜵ"],[42805,2],[42806,1,"ꜷ"],[42807,2],[42808,1,"ꜹ"],[42809,2],[42810,1,"ꜻ"],[42811,2],[42812,1,"ꜽ"],[42813,2],[42814,1,"ꜿ"],[42815,2],[42816,1,"ꝁ"],[42817,2],[42818,1,"ꝃ"],[42819,2],[42820,1,"ꝅ"],[42821,2],[42822,1,"ꝇ"],[42823,2],[42824,1,"ꝉ"],[42825,2],[42826,1,"ꝋ"],[42827,2],[42828,1,"ꝍ"],[42829,2],[42830,1,"ꝏ"],[42831,2],[42832,1,"ꝑ"],[42833,2],[42834,1,"ꝓ"],[42835,2],[42836,1,"ꝕ"],[42837,2],[42838,1,"ꝗ"],[42839,2],[42840,1,"ꝙ"],[42841,2],[42842,1,"ꝛ"],[42843,2],[42844,1,"ꝝ"],[42845,2],[42846,1,"ꝟ"],[42847,2],[42848,1,"ꝡ"],[42849,2],[42850,1,"ꝣ"],[42851,2],[42852,1,"ꝥ"],[42853,2],[42854,1,"ꝧ"],[42855,2],[42856,1,"ꝩ"],[42857,2],[42858,1,"ꝫ"],[42859,2],[42860,1,"ꝭ"],[42861,2],[42862,1,"ꝯ"],[42863,2],[42864,1,"ꝯ"],[[42865,42872],2],[42873,1,"ꝺ"],[42874,2],[42875,1,"ꝼ"],[42876,2],[42877,1,"ᵹ"],[42878,1,"ꝿ"],[42879,2],[42880,1,"ꞁ"],[42881,2],[42882,1,"ꞃ"],[42883,2],[42884,1,"ꞅ"],[42885,2],[42886,1,"ꞇ"],[[42887,42888],2],[[42889,42890],2],[42891,1,"ꞌ"],[42892,2],[42893,1,"ɥ"],[42894,2],[42895,2],[42896,1,"ꞑ"],[42897,2],[42898,1,"ꞓ"],[42899,2],[[42900,42901],2],[42902,1,"ꞗ"],[42903,2],[42904,1,"ꞙ"],[42905,2],[42906,1,"ꞛ"],[42907,2],[42908,1,"ꞝ"],[42909,2],[42910,1,"ꞟ"],[42911,2],[42912,1,"ꞡ"],[42913,2],[42914,1,"ꞣ"],[42915,2],[42916,1,"ꞥ"],[42917,2],[42918,1,"ꞧ"],[42919,2],[42920,1,"ꞩ"],[42921,2],[42922,1,"ɦ"],[42923,1,"ɜ"],[42924,1,"ɡ"],[42925,1,"ɬ"],[42926,1,"ɪ"],[42927,2],[42928,1,"ʞ"],[42929,1,"ʇ"],[42930,1,"ʝ"],[42931,1,"ꭓ"],[42932,1,"ꞵ"],[42933,2],[42934,1,"ꞷ"],[42935,2],[42936,1,"ꞹ"],[42937,2],[42938,1,"ꞻ"],[42939,2],[42940,1,"ꞽ"],[42941,2],[42942,1,"ꞿ"],[42943,2],[42944,1,"ꟁ"],[42945,2],[42946,1,"ꟃ"],[42947,2],[42948,1,"ꞔ"],[42949,1,"ʂ"],[42950,1,"ᶎ"],[42951,1,"ꟈ"],[42952,2],[42953,1,"ꟊ"],[42954,2],[[42955,42959],3],[42960,1,"ꟑ"],[42961,2],[42962,3],[42963,2],[42964,3],[42965,2],[42966,1,"ꟗ"],[42967,2],[42968,1,"ꟙ"],[42969,2],[[42970,42993],3],[42994,1,"c"],[42995,1,"f"],[42996,1,"q"],[42997,1,"ꟶ"],[42998,2],[42999,2],[43000,1,"ħ"],[43001,1,"œ"],[43002,2],[[43003,43007],2],[[43008,43047],2],[[43048,43051],2],[43052,2],[[43053,43055],3],[[43056,43065],2],[[43066,43071],3],[[43072,43123],2],[[43124,43127],2],[[43128,43135],3],[[43136,43204],2],[43205,2],[[43206,43213],3],[[43214,43215],2],[[43216,43225],2],[[43226,43231],3],[[43232,43255],2],[[43256,43258],2],[43259,2],[43260,2],[43261,2],[[43262,43263],2],[[43264,43309],2],[[43310,43311],2],[[43312,43347],2],[[43348,43358],3],[43359,2],[[43360,43388],2],[[43389,43391],3],[[43392,43456],2],[[43457,43469],2],[43470,3],[[43471,43481],2],[[43482,43485],3],[[43486,43487],2],[[43488,43518],2],[43519,3],[[43520,43574],2],[[43575,43583],3],[[43584,43597],2],[[43598,43599],3],[[43600,43609],2],[[43610,43611],3],[[43612,43615],2],[[43616,43638],2],[[43639,43641],2],[[43642,43643],2],[[43644,43647],2],[[43648,43714],2],[[43715,43738],3],[[43739,43741],2],[[43742,43743],2],[[43744,43759],2],[[43760,43761],2],[[43762,43766],2],[[43767,43776],3],[[43777,43782],2],[[43783,43784],3],[[43785,43790],2],[[43791,43792],3],[[43793,43798],2],[[43799,43807],3],[[43808,43814],2],[43815,3],[[43816,43822],2],[43823,3],[[43824,43866],2],[43867,2],[43868,1,"ꜧ"],[43869,1,"ꬷ"],[43870,1,"ɫ"],[43871,1,"ꭒ"],[[43872,43875],2],[[43876,43877],2],[[43878,43879],2],[43880,2],[43881,1,"ʍ"],[[43882,43883],2],[[43884,43887],3],[43888,1,"Ꭰ"],[43889,1,"Ꭱ"],[43890,1,"Ꭲ"],[43891,1,"Ꭳ"],[43892,1,"Ꭴ"],[43893,1,"Ꭵ"],[43894,1,"Ꭶ"],[43895,1,"Ꭷ"],[43896,1,"Ꭸ"],[43897,1,"Ꭹ"],[43898,1,"Ꭺ"],[43899,1,"Ꭻ"],[43900,1,"Ꭼ"],[43901,1,"Ꭽ"],[43902,1,"Ꭾ"],[43903,1,"Ꭿ"],[43904,1,"Ꮀ"],[43905,1,"Ꮁ"],[43906,1,"Ꮂ"],[43907,1,"Ꮃ"],[43908,1,"Ꮄ"],[43909,1,"Ꮅ"],[43910,1,"Ꮆ"],[43911,1,"Ꮇ"],[43912,1,"Ꮈ"],[43913,1,"Ꮉ"],[43914,1,"Ꮊ"],[43915,1,"Ꮋ"],[43916,1,"Ꮌ"],[43917,1,"Ꮍ"],[43918,1,"Ꮎ"],[43919,1,"Ꮏ"],[43920,1,"Ꮐ"],[43921,1,"Ꮑ"],[43922,1,"Ꮒ"],[43923,1,"Ꮓ"],[43924,1,"Ꮔ"],[43925,1,"Ꮕ"],[43926,1,"Ꮖ"],[43927,1,"Ꮗ"],[43928,1,"Ꮘ"],[43929,1,"Ꮙ"],[43930,1,"Ꮚ"],[43931,1,"Ꮛ"],[43932,1,"Ꮜ"],[43933,1,"Ꮝ"],[43934,1,"Ꮞ"],[43935,1,"Ꮟ"],[43936,1,"Ꮠ"],[43937,1,"Ꮡ"],[43938,1,"Ꮢ"],[43939,1,"Ꮣ"],[43940,1,"Ꮤ"],[43941,1,"Ꮥ"],[43942,1,"Ꮦ"],[43943,1,"Ꮧ"],[43944,1,"Ꮨ"],[43945,1,"Ꮩ"],[43946,1,"Ꮪ"],[43947,1,"Ꮫ"],[43948,1,"Ꮬ"],[43949,1,"Ꮭ"],[43950,1,"Ꮮ"],[43951,1,"Ꮯ"],[43952,1,"Ꮰ"],[43953,1,"Ꮱ"],[43954,1,"Ꮲ"],[43955,1,"Ꮳ"],[43956,1,"Ꮴ"],[43957,1,"Ꮵ"],[43958,1,"Ꮶ"],[43959,1,"Ꮷ"],[43960,1,"Ꮸ"],[43961,1,"Ꮹ"],[43962,1,"Ꮺ"],[43963,1,"Ꮻ"],[43964,1,"Ꮼ"],[43965,1,"Ꮽ"],[43966,1,"Ꮾ"],[43967,1,"Ꮿ"],[[43968,44010],2],[44011,2],[[44012,44013],2],[[44014,44015],3],[[44016,44025],2],[[44026,44031],3],[[44032,55203],2],[[55204,55215],3],[[55216,55238],2],[[55239,55242],3],[[55243,55291],2],[[55292,55295],3],[[55296,57343],3],[[57344,63743],3],[63744,1,"豈"],[63745,1,"更"],[63746,1,"車"],[63747,1,"賈"],[63748,1,"滑"],[63749,1,"串"],[63750,1,"句"],[[63751,63752],1,"龜"],[63753,1,"契"],[63754,1,"金"],[63755,1,"喇"],[63756,1,"奈"],[63757,1,"懶"],[63758,1,"癩"],[63759,1,"羅"],[63760,1,"蘿"],[63761,1,"螺"],[63762,1,"裸"],[63763,1,"邏"],[63764,1,"樂"],[63765,1,"洛"],[63766,1,"烙"],[63767,1,"珞"],[63768,1,"落"],[63769,1,"酪"],[63770,1,"駱"],[63771,1,"亂"],[63772,1,"卵"],[63773,1,"欄"],[63774,1,"爛"],[63775,1,"蘭"],[63776,1,"鸞"],[63777,1,"嵐"],[63778,1,"濫"],[63779,1,"藍"],[63780,1,"襤"],[63781,1,"拉"],[63782,1,"臘"],[63783,1,"蠟"],[63784,1,"廊"],[63785,1,"朗"],[63786,1,"浪"],[63787,1,"狼"],[63788,1,"郎"],[63789,1,"來"],[63790,1,"冷"],[63791,1,"勞"],[63792,1,"擄"],[63793,1,"櫓"],[63794,1,"爐"],[63795,1,"盧"],[63796,1,"老"],[63797,1,"蘆"],[63798,1,"虜"],[63799,1,"路"],[63800,1,"露"],[63801,1,"魯"],[63802,1,"鷺"],[63803,1,"碌"],[63804,1,"祿"],[63805,1,"綠"],[63806,1,"菉"],[63807,1,"錄"],[63808,1,"鹿"],[63809,1,"論"],[63810,1,"壟"],[63811,1,"弄"],[63812,1,"籠"],[63813,1,"聾"],[63814,1,"牢"],[63815,1,"磊"],[63816,1,"賂"],[63817,1,"雷"],[63818,1,"壘"],[63819,1,"屢"],[63820,1,"樓"],[63821,1,"淚"],[63822,1,"漏"],[63823,1,"累"],[63824,1,"縷"],[63825,1,"陋"],[63826,1,"勒"],[63827,1,"肋"],[63828,1,"凜"],[63829,1,"凌"],[63830,1,"稜"],[63831,1,"綾"],[63832,1,"菱"],[63833,1,"陵"],[63834,1,"讀"],[63835,1,"拏"],[63836,1,"樂"],[63837,1,"諾"],[63838,1,"丹"],[63839,1,"寧"],[63840,1,"怒"],[63841,1,"率"],[63842,1,"異"],[63843,1,"北"],[63844,1,"磻"],[63845,1,"便"],[63846,1,"復"],[63847,1,"不"],[63848,1,"泌"],[63849,1,"數"],[63850,1,"索"],[63851,1,"參"],[63852,1,"塞"],[63853,1,"省"],[63854,1,"葉"],[63855,1,"說"],[63856,1,"殺"],[63857,1,"辰"],[63858,1,"沈"],[63859,1,"拾"],[63860,1,"若"],[63861,1,"掠"],[63862,1,"略"],[63863,1,"亮"],[63864,1,"兩"],[63865,1,"凉"],[63866,1,"梁"],[63867,1,"糧"],[63868,1,"良"],[63869,1,"諒"],[63870,1,"量"],[63871,1,"勵"],[63872,1,"呂"],[63873,1,"女"],[63874,1,"廬"],[63875,1,"旅"],[63876,1,"濾"],[63877,1,"礪"],[63878,1,"閭"],[63879,1,"驪"],[63880,1,"麗"],[63881,1,"黎"],[63882,1,"力"],[63883,1,"曆"],[63884,1,"歷"],[63885,1,"轢"],[63886,1,"年"],[63887,1,"憐"],[63888,1,"戀"],[63889,1,"撚"],[63890,1,"漣"],[63891,1,"煉"],[63892,1,"璉"],[63893,1,"秊"],[63894,1,"練"],[63895,1,"聯"],[63896,1,"輦"],[63897,1,"蓮"],[63898,1,"連"],[63899,1,"鍊"],[63900,1,"列"],[63901,1,"劣"],[63902,1,"咽"],[63903,1,"烈"],[63904,1,"裂"],[63905,1,"說"],[63906,1,"廉"],[63907,1,"念"],[63908,1,"捻"],[63909,1,"殮"],[63910,1,"簾"],[63911,1,"獵"],[63912,1,"令"],[63913,1,"囹"],[63914,1,"寧"],[63915,1,"嶺"],[63916,1,"怜"],[63917,1,"玲"],[63918,1,"瑩"],[63919,1,"羚"],[63920,1,"聆"],[63921,1,"鈴"],[63922,1,"零"],[63923,1,"靈"],[63924,1,"領"],[63925,1,"例"],[63926,1,"禮"],[63927,1,"醴"],[63928,1,"隸"],[63929,1,"惡"],[63930,1,"了"],[63931,1,"僚"],[63932,1,"寮"],[63933,1,"尿"],[63934,1,"料"],[63935,1,"樂"],[63936,1,"燎"],[63937,1,"療"],[63938,1,"蓼"],[63939,1,"遼"],[63940,1,"龍"],[63941,1,"暈"],[63942,1,"阮"],[63943,1,"劉"],[63944,1,"杻"],[63945,1,"柳"],[63946,1,"流"],[63947,1,"溜"],[63948,1,"琉"],[63949,1,"留"],[63950,1,"硫"],[63951,1,"紐"],[63952,1,"類"],[63953,1,"六"],[63954,1,"戮"],[63955,1,"陸"],[63956,1,"倫"],[63957,1,"崙"],[63958,1,"淪"],[63959,1,"輪"],[63960,1,"律"],[63961,1,"慄"],[63962,1,"栗"],[63963,1,"率"],[63964,1,"隆"],[63965,1,"利"],[63966,1,"吏"],[63967,1,"履"],[63968,1,"易"],[63969,1,"李"],[63970,1,"梨"],[63971,1,"泥"],[63972,1,"理"],[63973,1,"痢"],[63974,1,"罹"],[63975,1,"裏"],[63976,1,"裡"],[63977,1,"里"],[63978,1,"離"],[63979,1,"匿"],[63980,1,"溺"],[63981,1,"吝"],[63982,1,"燐"],[63983,1,"璘"],[63984,1,"藺"],[63985,1,"隣"],[63986,1,"鱗"],[63987,1,"麟"],[63988,1,"林"],[63989,1,"淋"],[63990,1,"臨"],[63991,1,"立"],[63992,1,"笠"],[63993,1,"粒"],[63994,1,"狀"],[63995,1,"炙"],[63996,1,"識"],[63997,1,"什"],[63998,1,"茶"],[63999,1,"刺"],[64000,1,"切"],[64001,1,"度"],[64002,1,"拓"],[64003,1,"糖"],[64004,1,"宅"],[64005,1,"洞"],[64006,1,"暴"],[64007,1,"輻"],[64008,1,"行"],[64009,1,"降"],[64010,1,"見"],[64011,1,"廓"],[64012,1,"兀"],[64013,1,"嗀"],[[64014,64015],2],[64016,1,"塚"],[64017,2],[64018,1,"晴"],[[64019,64020],2],[64021,1,"凞"],[64022,1,"猪"],[64023,1,"益"],[64024,1,"礼"],[64025,1,"神"],[64026,1,"祥"],[64027,1,"福"],[64028,1,"靖"],[64029,1,"精"],[64030,1,"羽"],[64031,2],[64032,1,"蘒"],[64033,2],[64034,1,"諸"],[[64035,64036],2],[64037,1,"逸"],[64038,1,"都"],[[64039,64041],2],[64042,1,"飯"],[64043,1,"飼"],[64044,1,"館"],[64045,1,"鶴"],[64046,1,"郞"],[64047,1,"隷"],[64048,1,"侮"],[64049,1,"僧"],[64050,1,"免"],[64051,1,"勉"],[64052,1,"勤"],[64053,1,"卑"],[64054,1,"喝"],[64055,1,"嘆"],[64056,1,"器"],[64057,1,"塀"],[64058,1,"墨"],[64059,1,"層"],[64060,1,"屮"],[64061,1,"悔"],[64062,1,"慨"],[64063,1,"憎"],[64064,1,"懲"],[64065,1,"敏"],[64066,1,"既"],[64067,1,"暑"],[64068,1,"梅"],[64069,1,"海"],[64070,1,"渚"],[64071,1,"漢"],[64072,1,"煮"],[64073,1,"爫"],[64074,1,"琢"],[64075,1,"碑"],[64076,1,"社"],[64077,1,"祉"],[64078,1,"祈"],[64079,1,"祐"],[64080,1,"祖"],[64081,1,"祝"],[64082,1,"禍"],[64083,1,"禎"],[64084,1,"穀"],[64085,1,"突"],[64086,1,"節"],[64087,1,"練"],[64088,1,"縉"],[64089,1,"繁"],[64090,1,"署"],[64091,1,"者"],[64092,1,"臭"],[[64093,64094],1,"艹"],[64095,1,"著"],[64096,1,"褐"],[64097,1,"視"],[64098,1,"謁"],[64099,1,"謹"],[64100,1,"賓"],[64101,1,"贈"],[64102,1,"辶"],[64103,1,"逸"],[64104,1,"難"],[64105,1,"響"],[64106,1,"頻"],[64107,1,"恵"],[64108,1,"𤋮"],[64109,1,"舘"],[[64110,64111],3],[64112,1,"並"],[64113,1,"况"],[64114,1,"全"],[64115,1,"侀"],[64116,1,"充"],[64117,1,"冀"],[64118,1,"勇"],[64119,1,"勺"],[64120,1,"喝"],[64121,1,"啕"],[64122,1,"喙"],[64123,1,"嗢"],[64124,1,"塚"],[64125,1,"墳"],[64126,1,"奄"],[64127,1,"奔"],[64128,1,"婢"],[64129,1,"嬨"],[64130,1,"廒"],[64131,1,"廙"],[64132,1,"彩"],[64133,1,"徭"],[64134,1,"惘"],[64135,1,"慎"],[64136,1,"愈"],[64137,1,"憎"],[64138,1,"慠"],[64139,1,"懲"],[64140,1,"戴"],[64141,1,"揄"],[64142,1,"搜"],[64143,1,"摒"],[64144,1,"敖"],[64145,1,"晴"],[64146,1,"朗"],[64147,1,"望"],[64148,1,"杖"],[64149,1,"歹"],[64150,1,"殺"],[64151,1,"流"],[64152,1,"滛"],[64153,1,"滋"],[64154,1,"漢"],[64155,1,"瀞"],[64156,1,"煮"],[64157,1,"瞧"],[64158,1,"爵"],[64159,1,"犯"],[64160,1,"猪"],[64161,1,"瑱"],[64162,1,"甆"],[64163,1,"画"],[64164,1,"瘝"],[64165,1,"瘟"],[64166,1,"益"],[64167,1,"盛"],[64168,1,"直"],[64169,1,"睊"],[64170,1,"着"],[64171,1,"磌"],[64172,1,"窱"],[64173,1,"節"],[64174,1,"类"],[64175,1,"絛"],[64176,1,"練"],[64177,1,"缾"],[64178,1,"者"],[64179,1,"荒"],[64180,1,"華"],[64181,1,"蝹"],[64182,1,"襁"],[64183,1,"覆"],[64184,1,"視"],[64185,1,"調"],[64186,1,"諸"],[64187,1,"請"],[64188,1,"謁"],[64189,1,"諾"],[64190,1,"諭"],[64191,1,"謹"],[64192,1,"變"],[64193,1,"贈"],[64194,1,"輸"],[64195,1,"遲"],[64196,1,"醙"],[64197,1,"鉶"],[64198,1,"陼"],[64199,1,"難"],[64200,1,"靖"],[64201,1,"韛"],[64202,1,"響"],[64203,1,"頋"],[64204,1,"頻"],[64205,1,"鬒"],[64206,1,"龜"],[64207,1,"𢡊"],[64208,1,"𢡄"],[64209,1,"𣏕"],[64210,1,"㮝"],[64211,1,"䀘"],[64212,1,"䀹"],[64213,1,"𥉉"],[64214,1,"𥳐"],[64215,1,"𧻓"],[64216,1,"齃"],[64217,1,"龎"],[[64218,64255],3],[64256,1,"ff"],[64257,1,"fi"],[64258,1,"fl"],[64259,1,"ffi"],[64260,1,"ffl"],[[64261,64262],1,"st"],[[64263,64274],3],[64275,1,"մն"],[64276,1,"մե"],[64277,1,"մի"],[64278,1,"վն"],[64279,1,"մխ"],[[64280,64284],3],[64285,1,"יִ"],[64286,2],[64287,1,"ײַ"],[64288,1,"ע"],[64289,1,"א"],[64290,1,"ד"],[64291,1,"ה"],[64292,1,"כ"],[64293,1,"ל"],[64294,1,"ם"],[64295,1,"ר"],[64296,1,"ת"],[64297,5,"+"],[64298,1,"שׁ"],[64299,1,"שׂ"],[64300,1,"שּׁ"],[64301,1,"שּׂ"],[64302,1,"אַ"],[64303,1,"אָ"],[64304,1,"אּ"],[64305,1,"בּ"],[64306,1,"גּ"],[64307,1,"דּ"],[64308,1,"הּ"],[64309,1,"וּ"],[64310,1,"זּ"],[64311,3],[64312,1,"טּ"],[64313,1,"יּ"],[64314,1,"ךּ"],[64315,1,"כּ"],[64316,1,"לּ"],[64317,3],[64318,1,"מּ"],[64319,3],[64320,1,"נּ"],[64321,1,"סּ"],[64322,3],[64323,1,"ףּ"],[64324,1,"פּ"],[64325,3],[64326,1,"צּ"],[64327,1,"קּ"],[64328,1,"רּ"],[64329,1,"שּ"],[64330,1,"תּ"],[64331,1,"וֹ"],[64332,1,"בֿ"],[64333,1,"כֿ"],[64334,1,"פֿ"],[64335,1,"אל"],[[64336,64337],1,"ٱ"],[[64338,64341],1,"ٻ"],[[64342,64345],1,"پ"],[[64346,64349],1,"ڀ"],[[64350,64353],1,"ٺ"],[[64354,64357],1,"ٿ"],[[64358,64361],1,"ٹ"],[[64362,64365],1,"ڤ"],[[64366,64369],1,"ڦ"],[[64370,64373],1,"ڄ"],[[64374,64377],1,"ڃ"],[[64378,64381],1,"چ"],[[64382,64385],1,"ڇ"],[[64386,64387],1,"ڍ"],[[64388,64389],1,"ڌ"],[[64390,64391],1,"ڎ"],[[64392,64393],1,"ڈ"],[[64394,64395],1,"ژ"],[[64396,64397],1,"ڑ"],[[64398,64401],1,"ک"],[[64402,64405],1,"گ"],[[64406,64409],1,"ڳ"],[[64410,64413],1,"ڱ"],[[64414,64415],1,"ں"],[[64416,64419],1,"ڻ"],[[64420,64421],1,"ۀ"],[[64422,64425],1,"ہ"],[[64426,64429],1,"ھ"],[[64430,64431],1,"ے"],[[64432,64433],1,"ۓ"],[[64434,64449],2],[64450,2],[[64451,64466],3],[[64467,64470],1,"ڭ"],[[64471,64472],1,"ۇ"],[[64473,64474],1,"ۆ"],[[64475,64476],1,"ۈ"],[64477,1,"ۇٴ"],[[64478,64479],1,"ۋ"],[[64480,64481],1,"ۅ"],[[64482,64483],1,"ۉ"],[[64484,64487],1,"ې"],[[64488,64489],1,"ى"],[[64490,64491],1,"ئا"],[[64492,64493],1,"ئە"],[[64494,64495],1,"ئو"],[[64496,64497],1,"ئۇ"],[[64498,64499],1,"ئۆ"],[[64500,64501],1,"ئۈ"],[[64502,64504],1,"ئې"],[[64505,64507],1,"ئى"],[[64508,64511],1,"ی"],[64512,1,"ئج"],[64513,1,"ئح"],[64514,1,"ئم"],[64515,1,"ئى"],[64516,1,"ئي"],[64517,1,"بج"],[64518,1,"بح"],[64519,1,"بخ"],[64520,1,"بم"],[64521,1,"بى"],[64522,1,"بي"],[64523,1,"تج"],[64524,1,"تح"],[64525,1,"تخ"],[64526,1,"تم"],[64527,1,"تى"],[64528,1,"تي"],[64529,1,"ثج"],[64530,1,"ثم"],[64531,1,"ثى"],[64532,1,"ثي"],[64533,1,"جح"],[64534,1,"جم"],[64535,1,"حج"],[64536,1,"حم"],[64537,1,"خج"],[64538,1,"خح"],[64539,1,"خم"],[64540,1,"سج"],[64541,1,"سح"],[64542,1,"سخ"],[64543,1,"سم"],[64544,1,"صح"],[64545,1,"صم"],[64546,1,"ضج"],[64547,1,"ضح"],[64548,1,"ضخ"],[64549,1,"ضم"],[64550,1,"طح"],[64551,1,"طم"],[64552,1,"ظم"],[64553,1,"عج"],[64554,1,"عم"],[64555,1,"غج"],[64556,1,"غم"],[64557,1,"فج"],[64558,1,"فح"],[64559,1,"فخ"],[64560,1,"فم"],[64561,1,"فى"],[64562,1,"في"],[64563,1,"قح"],[64564,1,"قم"],[64565,1,"قى"],[64566,1,"قي"],[64567,1,"كا"],[64568,1,"كج"],[64569,1,"كح"],[64570,1,"كخ"],[64571,1,"كل"],[64572,1,"كم"],[64573,1,"كى"],[64574,1,"كي"],[64575,1,"لج"],[64576,1,"لح"],[64577,1,"لخ"],[64578,1,"لم"],[64579,1,"لى"],[64580,1,"لي"],[64581,1,"مج"],[64582,1,"مح"],[64583,1,"مخ"],[64584,1,"مم"],[64585,1,"مى"],[64586,1,"مي"],[64587,1,"نج"],[64588,1,"نح"],[64589,1,"نخ"],[64590,1,"نم"],[64591,1,"نى"],[64592,1,"ني"],[64593,1,"هج"],[64594,1,"هم"],[64595,1,"هى"],[64596,1,"هي"],[64597,1,"يج"],[64598,1,"يح"],[64599,1,"يخ"],[64600,1,"يم"],[64601,1,"يى"],[64602,1,"يي"],[64603,1,"ذٰ"],[64604,1,"رٰ"],[64605,1,"ىٰ"],[64606,5," ٌّ"],[64607,5," ٍّ"],[64608,5," َّ"],[64609,5," ُّ"],[64610,5," ِّ"],[64611,5," ّٰ"],[64612,1,"ئر"],[64613,1,"ئز"],[64614,1,"ئم"],[64615,1,"ئن"],[64616,1,"ئى"],[64617,1,"ئي"],[64618,1,"بر"],[64619,1,"بز"],[64620,1,"بم"],[64621,1,"بن"],[64622,1,"بى"],[64623,1,"بي"],[64624,1,"تر"],[64625,1,"تز"],[64626,1,"تم"],[64627,1,"تن"],[64628,1,"تى"],[64629,1,"تي"],[64630,1,"ثر"],[64631,1,"ثز"],[64632,1,"ثم"],[64633,1,"ثن"],[64634,1,"ثى"],[64635,1,"ثي"],[64636,1,"فى"],[64637,1,"في"],[64638,1,"قى"],[64639,1,"قي"],[64640,1,"كا"],[64641,1,"كل"],[64642,1,"كم"],[64643,1,"كى"],[64644,1,"كي"],[64645,1,"لم"],[64646,1,"لى"],[64647,1,"لي"],[64648,1,"ما"],[64649,1,"مم"],[64650,1,"نر"],[64651,1,"نز"],[64652,1,"نم"],[64653,1,"نن"],[64654,1,"نى"],[64655,1,"ني"],[64656,1,"ىٰ"],[64657,1,"ير"],[64658,1,"يز"],[64659,1,"يم"],[64660,1,"ين"],[64661,1,"يى"],[64662,1,"يي"],[64663,1,"ئج"],[64664,1,"ئح"],[64665,1,"ئخ"],[64666,1,"ئم"],[64667,1,"ئه"],[64668,1,"بج"],[64669,1,"بح"],[64670,1,"بخ"],[64671,1,"بم"],[64672,1,"به"],[64673,1,"تج"],[64674,1,"تح"],[64675,1,"تخ"],[64676,1,"تم"],[64677,1,"ته"],[64678,1,"ثم"],[64679,1,"جح"],[64680,1,"جم"],[64681,1,"حج"],[64682,1,"حم"],[64683,1,"خج"],[64684,1,"خم"],[64685,1,"سج"],[64686,1,"سح"],[64687,1,"سخ"],[64688,1,"سم"],[64689,1,"صح"],[64690,1,"صخ"],[64691,1,"صم"],[64692,1,"ضج"],[64693,1,"ضح"],[64694,1,"ضخ"],[64695,1,"ضم"],[64696,1,"طح"],[64697,1,"ظم"],[64698,1,"عج"],[64699,1,"عم"],[64700,1,"غج"],[64701,1,"غم"],[64702,1,"فج"],[64703,1,"فح"],[64704,1,"فخ"],[64705,1,"فم"],[64706,1,"قح"],[64707,1,"قم"],[64708,1,"كج"],[64709,1,"كح"],[64710,1,"كخ"],[64711,1,"كل"],[64712,1,"كم"],[64713,1,"لج"],[64714,1,"لح"],[64715,1,"لخ"],[64716,1,"لم"],[64717,1,"له"],[64718,1,"مج"],[64719,1,"مح"],[64720,1,"مخ"],[64721,1,"مم"],[64722,1,"نج"],[64723,1,"نح"],[64724,1,"نخ"],[64725,1,"نم"],[64726,1,"نه"],[64727,1,"هج"],[64728,1,"هم"],[64729,1,"هٰ"],[64730,1,"يج"],[64731,1,"يح"],[64732,1,"يخ"],[64733,1,"يم"],[64734,1,"يه"],[64735,1,"ئم"],[64736,1,"ئه"],[64737,1,"بم"],[64738,1,"به"],[64739,1,"تم"],[64740,1,"ته"],[64741,1,"ثم"],[64742,1,"ثه"],[64743,1,"سم"],[64744,1,"سه"],[64745,1,"شم"],[64746,1,"شه"],[64747,1,"كل"],[64748,1,"كم"],[64749,1,"لم"],[64750,1,"نم"],[64751,1,"نه"],[64752,1,"يم"],[64753,1,"يه"],[64754,1,"ـَّ"],[64755,1,"ـُّ"],[64756,1,"ـِّ"],[64757,1,"طى"],[64758,1,"طي"],[64759,1,"عى"],[64760,1,"عي"],[64761,1,"غى"],[64762,1,"غي"],[64763,1,"سى"],[64764,1,"سي"],[64765,1,"شى"],[64766,1,"شي"],[64767,1,"حى"],[64768,1,"حي"],[64769,1,"جى"],[64770,1,"جي"],[64771,1,"خى"],[64772,1,"خي"],[64773,1,"صى"],[64774,1,"صي"],[64775,1,"ضى"],[64776,1,"ضي"],[64777,1,"شج"],[64778,1,"شح"],[64779,1,"شخ"],[64780,1,"شم"],[64781,1,"شر"],[64782,1,"سر"],[64783,1,"صر"],[64784,1,"ضر"],[64785,1,"طى"],[64786,1,"طي"],[64787,1,"عى"],[64788,1,"عي"],[64789,1,"غى"],[64790,1,"غي"],[64791,1,"سى"],[64792,1,"سي"],[64793,1,"شى"],[64794,1,"شي"],[64795,1,"حى"],[64796,1,"حي"],[64797,1,"جى"],[64798,1,"جي"],[64799,1,"خى"],[64800,1,"خي"],[64801,1,"صى"],[64802,1,"صي"],[64803,1,"ضى"],[64804,1,"ضي"],[64805,1,"شج"],[64806,1,"شح"],[64807,1,"شخ"],[64808,1,"شم"],[64809,1,"شر"],[64810,1,"سر"],[64811,1,"صر"],[64812,1,"ضر"],[64813,1,"شج"],[64814,1,"شح"],[64815,1,"شخ"],[64816,1,"شم"],[64817,1,"سه"],[64818,1,"شه"],[64819,1,"طم"],[64820,1,"سج"],[64821,1,"سح"],[64822,1,"سخ"],[64823,1,"شج"],[64824,1,"شح"],[64825,1,"شخ"],[64826,1,"طم"],[64827,1,"ظم"],[[64828,64829],1,"اً"],[[64830,64831],2],[[64832,64847],2],[64848,1,"تجم"],[[64849,64850],1,"تحج"],[64851,1,"تحم"],[64852,1,"تخم"],[64853,1,"تمج"],[64854,1,"تمح"],[64855,1,"تمخ"],[[64856,64857],1,"جمح"],[64858,1,"حمي"],[64859,1,"حمى"],[64860,1,"سحج"],[64861,1,"سجح"],[64862,1,"سجى"],[[64863,64864],1,"سمح"],[64865,1,"سمج"],[[64866,64867],1,"سمم"],[[64868,64869],1,"صحح"],[64870,1,"صمم"],[[64871,64872],1,"شحم"],[64873,1,"شجي"],[[64874,64875],1,"شمخ"],[[64876,64877],1,"شمم"],[64878,1,"ضحى"],[[64879,64880],1,"ضخم"],[[64881,64882],1,"طمح"],[64883,1,"طمم"],[64884,1,"طمي"],[64885,1,"عجم"],[[64886,64887],1,"عمم"],[64888,1,"عمى"],[64889,1,"غمم"],[64890,1,"غمي"],[64891,1,"غمى"],[[64892,64893],1,"فخم"],[64894,1,"قمح"],[64895,1,"قمم"],[64896,1,"لحم"],[64897,1,"لحي"],[64898,1,"لحى"],[[64899,64900],1,"لجج"],[[64901,64902],1,"لخم"],[[64903,64904],1,"لمح"],[64905,1,"محج"],[64906,1,"محم"],[64907,1,"محي"],[64908,1,"مجح"],[64909,1,"مجم"],[64910,1,"مخج"],[64911,1,"مخم"],[[64912,64913],3],[64914,1,"مجخ"],[64915,1,"همج"],[64916,1,"همم"],[64917,1,"نحم"],[64918,1,"نحى"],[[64919,64920],1,"نجم"],[64921,1,"نجى"],[64922,1,"نمي"],[64923,1,"نمى"],[[64924,64925],1,"يمم"],[64926,1,"بخي"],[64927,1,"تجي"],[64928,1,"تجى"],[64929,1,"تخي"],[64930,1,"تخى"],[64931,1,"تمي"],[64932,1,"تمى"],[64933,1,"جمي"],[64934,1,"جحى"],[64935,1,"جمى"],[64936,1,"سخى"],[64937,1,"صحي"],[64938,1,"شحي"],[64939,1,"ضحي"],[64940,1,"لجي"],[64941,1,"لمي"],[64942,1,"يحي"],[64943,1,"يجي"],[64944,1,"يمي"],[64945,1,"ممي"],[64946,1,"قمي"],[64947,1,"نحي"],[64948,1,"قمح"],[64949,1,"لحم"],[64950,1,"عمي"],[64951,1,"كمي"],[64952,1,"نجح"],[64953,1,"مخي"],[64954,1,"لجم"],[64955,1,"كمم"],[64956,1,"لجم"],[64957,1,"نجح"],[64958,1,"جحي"],[64959,1,"حجي"],[64960,1,"مجي"],[64961,1,"فمي"],[64962,1,"بحي"],[64963,1,"كمم"],[64964,1,"عجم"],[64965,1,"صمم"],[64966,1,"سخي"],[64967,1,"نجي"],[[64968,64974],3],[64975,2],[[64976,65007],3],[65008,1,"صلے"],[65009,1,"قلے"],[65010,1,"الله"],[65011,1,"اكبر"],[65012,1,"محمد"],[65013,1,"صلعم"],[65014,1,"رسول"],[65015,1,"عليه"],[65016,1,"وسلم"],[65017,1,"صلى"],[65018,5,"صلى الله عليه وسلم"],[65019,5,"جل جلاله"],[65020,1,"ریال"],[65021,2],[[65022,65023],2],[[65024,65039],7],[65040,5,","],[65041,1,"、"],[65042,3],[65043,5,":"],[65044,5,";"],[65045,5,"!"],[65046,5,"?"],[65047,1,"〖"],[65048,1,"〗"],[65049,3],[[65050,65055],3],[[65056,65059],2],[[65060,65062],2],[[65063,65069],2],[[65070,65071],2],[65072,3],[65073,1,"—"],[65074,1,"–"],[[65075,65076],5,"_"],[65077,5,"("],[65078,5,")"],[65079,5,"{"],[65080,5,"}"],[65081,1,"〔"],[65082,1,"〕"],[65083,1,"【"],[65084,1,"】"],[65085,1,"《"],[65086,1,"》"],[65087,1,"〈"],[65088,1,"〉"],[65089,1,"「"],[65090,1,"」"],[65091,1,"『"],[65092,1,"』"],[[65093,65094],2],[65095,5,"["],[65096,5,"]"],[[65097,65100],5," ̅"],[[65101,65103],5,"_"],[65104,5,","],[65105,1,"、"],[65106,3],[65107,3],[65108,5,";"],[65109,5,":"],[65110,5,"?"],[65111,5,"!"],[65112,1,"—"],[65113,5,"("],[65114,5,")"],[65115,5,"{"],[65116,5,"}"],[65117,1,"〔"],[65118,1,"〕"],[65119,5,"#"],[65120,5,"&"],[65121,5,"*"],[65122,5,"+"],[65123,1,"-"],[65124,5,"<"],[65125,5,">"],[65126,5,"="],[65127,3],[65128,5,"\\\\"],[65129,5,"$"],[65130,5,"%"],[65131,5,"@"],[[65132,65135],3],[65136,5," ً"],[65137,1,"ـً"],[65138,5," ٌ"],[65139,2],[65140,5," ٍ"],[65141,3],[65142,5," َ"],[65143,1,"ـَ"],[65144,5," ُ"],[65145,1,"ـُ"],[65146,5," ِ"],[65147,1,"ـِ"],[65148,5," ّ"],[65149,1,"ـّ"],[65150,5," ْ"],[65151,1,"ـْ"],[65152,1,"ء"],[[65153,65154],1,"آ"],[[65155,65156],1,"أ"],[[65157,65158],1,"ؤ"],[[65159,65160],1,"إ"],[[65161,65164],1,"ئ"],[[65165,65166],1,"ا"],[[65167,65170],1,"ب"],[[65171,65172],1,"ة"],[[65173,65176],1,"ت"],[[65177,65180],1,"ث"],[[65181,65184],1,"ج"],[[65185,65188],1,"ح"],[[65189,65192],1,"خ"],[[65193,65194],1,"د"],[[65195,65196],1,"ذ"],[[65197,65198],1,"ر"],[[65199,65200],1,"ز"],[[65201,65204],1,"س"],[[65205,65208],1,"ش"],[[65209,65212],1,"ص"],[[65213,65216],1,"ض"],[[65217,65220],1,"ط"],[[65221,65224],1,"ظ"],[[65225,65228],1,"ع"],[[65229,65232],1,"غ"],[[65233,65236],1,"ف"],[[65237,65240],1,"ق"],[[65241,65244],1,"ك"],[[65245,65248],1,"ل"],[[65249,65252],1,"م"],[[65253,65256],1,"ن"],[[65257,65260],1,"ه"],[[65261,65262],1,"و"],[[65263,65264],1,"ى"],[[65265,65268],1,"ي"],[[65269,65270],1,"لآ"],[[65271,65272],1,"لأ"],[[65273,65274],1,"لإ"],[[65275,65276],1,"لا"],[[65277,65278],3],[65279,7],[65280,3],[65281,5,"!"],[65282,5,"\\""],[65283,5,"#"],[65284,5,"$"],[65285,5,"%"],[65286,5,"&"],[65287,5,"\'"],[65288,5,"("],[65289,5,")"],[65290,5,"*"],[65291,5,"+"],[65292,5,","],[65293,1,"-"],[65294,1,"."],[65295,5,"/"],[65296,1,"0"],[65297,1,"1"],[65298,1,"2"],[65299,1,"3"],[65300,1,"4"],[65301,1,"5"],[65302,1,"6"],[65303,1,"7"],[65304,1,"8"],[65305,1,"9"],[65306,5,":"],[65307,5,";"],[65308,5,"<"],[65309,5,"="],[65310,5,">"],[65311,5,"?"],[65312,5,"@"],[65313,1,"a"],[65314,1,"b"],[65315,1,"c"],[65316,1,"d"],[65317,1,"e"],[65318,1,"f"],[65319,1,"g"],[65320,1,"h"],[65321,1,"i"],[65322,1,"j"],[65323,1,"k"],[65324,1,"l"],[65325,1,"m"],[65326,1,"n"],[65327,1,"o"],[65328,1,"p"],[65329,1,"q"],[65330,1,"r"],[65331,1,"s"],[65332,1,"t"],[65333,1,"u"],[65334,1,"v"],[65335,1,"w"],[65336,1,"x"],[65337,1,"y"],[65338,1,"z"],[65339,5,"["],[65340,5,"\\\\"],[65341,5,"]"],[65342,5,"^"],[65343,5,"_"],[65344,5,"`"],[65345,1,"a"],[65346,1,"b"],[65347,1,"c"],[65348,1,"d"],[65349,1,"e"],[65350,1,"f"],[65351,1,"g"],[65352,1,"h"],[65353,1,"i"],[65354,1,"j"],[65355,1,"k"],[65356,1,"l"],[65357,1,"m"],[65358,1,"n"],[65359,1,"o"],[65360,1,"p"],[65361,1,"q"],[65362,1,"r"],[65363,1,"s"],[65364,1,"t"],[65365,1,"u"],[65366,1,"v"],[65367,1,"w"],[65368,1,"x"],[65369,1,"y"],[65370,1,"z"],[65371,5,"{"],[65372,5,"|"],[65373,5,"}"],[65374,5,"~"],[65375,1,"⦅"],[65376,1,"⦆"],[65377,1,"."],[65378,1,"「"],[65379,1,"」"],[65380,1,"、"],[65381,1,"・"],[65382,1,"ヲ"],[65383,1,"ァ"],[65384,1,"ィ"],[65385,1,"ゥ"],[65386,1,"ェ"],[65387,1,"ォ"],[65388,1,"ャ"],[65389,1,"ュ"],[65390,1,"ョ"],[65391,1,"ッ"],[65392,1,"ー"],[65393,1,"ア"],[65394,1,"イ"],[65395,1,"ウ"],[65396,1,"エ"],[65397,1,"オ"],[65398,1,"カ"],[65399,1,"キ"],[65400,1,"ク"],[65401,1,"ケ"],[65402,1,"コ"],[65403,1,"サ"],[65404,1,"シ"],[65405,1,"ス"],[65406,1,"セ"],[65407,1,"ソ"],[65408,1,"タ"],[65409,1,"チ"],[65410,1,"ツ"],[65411,1,"テ"],[65412,1,"ト"],[65413,1,"ナ"],[65414,1,"ニ"],[65415,1,"ヌ"],[65416,1,"ネ"],[65417,1,"ノ"],[65418,1,"ハ"],[65419,1,"ヒ"],[65420,1,"フ"],[65421,1,"ヘ"],[65422,1,"ホ"],[65423,1,"マ"],[65424,1,"ミ"],[65425,1,"ム"],[65426,1,"メ"],[65427,1,"モ"],[65428,1,"ヤ"],[65429,1,"ユ"],[65430,1,"ヨ"],[65431,1,"ラ"],[65432,1,"リ"],[65433,1,"ル"],[65434,1,"レ"],[65435,1,"ロ"],[65436,1,"ワ"],[65437,1,"ン"],[65438,1,"゙"],[65439,1,"゚"],[65440,3],[65441,1,"ᄀ"],[65442,1,"ᄁ"],[65443,1,"ᆪ"],[65444,1,"ᄂ"],[65445,1,"ᆬ"],[65446,1,"ᆭ"],[65447,1,"ᄃ"],[65448,1,"ᄄ"],[65449,1,"ᄅ"],[65450,1,"ᆰ"],[65451,1,"ᆱ"],[65452,1,"ᆲ"],[65453,1,"ᆳ"],[65454,1,"ᆴ"],[65455,1,"ᆵ"],[65456,1,"ᄚ"],[65457,1,"ᄆ"],[65458,1,"ᄇ"],[65459,1,"ᄈ"],[65460,1,"ᄡ"],[65461,1,"ᄉ"],[65462,1,"ᄊ"],[65463,1,"ᄋ"],[65464,1,"ᄌ"],[65465,1,"ᄍ"],[65466,1,"ᄎ"],[65467,1,"ᄏ"],[65468,1,"ᄐ"],[65469,1,"ᄑ"],[65470,1,"ᄒ"],[[65471,65473],3],[65474,1,"ᅡ"],[65475,1,"ᅢ"],[65476,1,"ᅣ"],[65477,1,"ᅤ"],[65478,1,"ᅥ"],[65479,1,"ᅦ"],[[65480,65481],3],[65482,1,"ᅧ"],[65483,1,"ᅨ"],[65484,1,"ᅩ"],[65485,1,"ᅪ"],[65486,1,"ᅫ"],[65487,1,"ᅬ"],[[65488,65489],3],[65490,1,"ᅭ"],[65491,1,"ᅮ"],[65492,1,"ᅯ"],[65493,1,"ᅰ"],[65494,1,"ᅱ"],[65495,1,"ᅲ"],[[65496,65497],3],[65498,1,"ᅳ"],[65499,1,"ᅴ"],[65500,1,"ᅵ"],[[65501,65503],3],[65504,1,"¢"],[65505,1,"£"],[65506,1,"¬"],[65507,5," ̄"],[65508,1,"¦"],[65509,1,"¥"],[65510,1,"₩"],[65511,3],[65512,1,"│"],[65513,1,"←"],[65514,1,"↑"],[65515,1,"→"],[65516,1,"↓"],[65517,1,"■"],[65518,1,"○"],[[65519,65528],3],[[65529,65531],3],[65532,3],[65533,3],[[65534,65535],3],[[65536,65547],2],[65548,3],[[65549,65574],2],[65575,3],[[65576,65594],2],[65595,3],[[65596,65597],2],[65598,3],[[65599,65613],2],[[65614,65615],3],[[65616,65629],2],[[65630,65663],3],[[65664,65786],2],[[65787,65791],3],[[65792,65794],2],[[65795,65798],3],[[65799,65843],2],[[65844,65846],3],[[65847,65855],2],[[65856,65930],2],[[65931,65932],2],[[65933,65934],2],[65935,3],[[65936,65947],2],[65948,2],[[65949,65951],3],[65952,2],[[65953,65999],3],[[66000,66044],2],[66045,2],[[66046,66175],3],[[66176,66204],2],[[66205,66207],3],[[66208,66256],2],[[66257,66271],3],[66272,2],[[66273,66299],2],[[66300,66303],3],[[66304,66334],2],[66335,2],[[66336,66339],2],[[66340,66348],3],[[66349,66351],2],[[66352,66368],2],[66369,2],[[66370,66377],2],[66378,2],[[66379,66383],3],[[66384,66426],2],[[66427,66431],3],[[66432,66461],2],[66462,3],[66463,2],[[66464,66499],2],[[66500,66503],3],[[66504,66511],2],[[66512,66517],2],[[66518,66559],3],[66560,1,"𐐨"],[66561,1,"𐐩"],[66562,1,"𐐪"],[66563,1,"𐐫"],[66564,1,"𐐬"],[66565,1,"𐐭"],[66566,1,"𐐮"],[66567,1,"𐐯"],[66568,1,"𐐰"],[66569,1,"𐐱"],[66570,1,"𐐲"],[66571,1,"𐐳"],[66572,1,"𐐴"],[66573,1,"𐐵"],[66574,1,"𐐶"],[66575,1,"𐐷"],[66576,1,"𐐸"],[66577,1,"𐐹"],[66578,1,"𐐺"],[66579,1,"𐐻"],[66580,1,"𐐼"],[66581,1,"𐐽"],[66582,1,"𐐾"],[66583,1,"𐐿"],[66584,1,"𐑀"],[66585,1,"𐑁"],[66586,1,"𐑂"],[66587,1,"𐑃"],[66588,1,"𐑄"],[66589,1,"𐑅"],[66590,1,"𐑆"],[66591,1,"𐑇"],[66592,1,"𐑈"],[66593,1,"𐑉"],[66594,1,"𐑊"],[66595,1,"𐑋"],[66596,1,"𐑌"],[66597,1,"𐑍"],[66598,1,"𐑎"],[66599,1,"𐑏"],[[66600,66637],2],[[66638,66717],2],[[66718,66719],3],[[66720,66729],2],[[66730,66735],3],[66736,1,"𐓘"],[66737,1,"𐓙"],[66738,1,"𐓚"],[66739,1,"𐓛"],[66740,1,"𐓜"],[66741,1,"𐓝"],[66742,1,"𐓞"],[66743,1,"𐓟"],[66744,1,"𐓠"],[66745,1,"𐓡"],[66746,1,"𐓢"],[66747,1,"𐓣"],[66748,1,"𐓤"],[66749,1,"𐓥"],[66750,1,"𐓦"],[66751,1,"𐓧"],[66752,1,"𐓨"],[66753,1,"𐓩"],[66754,1,"𐓪"],[66755,1,"𐓫"],[66756,1,"𐓬"],[66757,1,"𐓭"],[66758,1,"𐓮"],[66759,1,"𐓯"],[66760,1,"𐓰"],[66761,1,"𐓱"],[66762,1,"𐓲"],[66763,1,"𐓳"],[66764,1,"𐓴"],[66765,1,"𐓵"],[66766,1,"𐓶"],[66767,1,"𐓷"],[66768,1,"𐓸"],[66769,1,"𐓹"],[66770,1,"𐓺"],[66771,1,"𐓻"],[[66772,66775],3],[[66776,66811],2],[[66812,66815],3],[[66816,66855],2],[[66856,66863],3],[[66864,66915],2],[[66916,66926],3],[66927,2],[66928,1,"𐖗"],[66929,1,"𐖘"],[66930,1,"𐖙"],[66931,1,"𐖚"],[66932,1,"𐖛"],[66933,1,"𐖜"],[66934,1,"𐖝"],[66935,1,"𐖞"],[66936,1,"𐖟"],[66937,1,"𐖠"],[66938,1,"𐖡"],[66939,3],[66940,1,"𐖣"],[66941,1,"𐖤"],[66942,1,"𐖥"],[66943,1,"𐖦"],[66944,1,"𐖧"],[66945,1,"𐖨"],[66946,1,"𐖩"],[66947,1,"𐖪"],[66948,1,"𐖫"],[66949,1,"𐖬"],[66950,1,"𐖭"],[66951,1,"𐖮"],[66952,1,"𐖯"],[66953,1,"𐖰"],[66954,1,"𐖱"],[66955,3],[66956,1,"𐖳"],[66957,1,"𐖴"],[66958,1,"𐖵"],[66959,1,"𐖶"],[66960,1,"𐖷"],[66961,1,"𐖸"],[66962,1,"𐖹"],[66963,3],[66964,1,"𐖻"],[66965,1,"𐖼"],[66966,3],[[66967,66977],2],[66978,3],[[66979,66993],2],[66994,3],[[66995,67001],2],[67002,3],[[67003,67004],2],[[67005,67071],3],[[67072,67382],2],[[67383,67391],3],[[67392,67413],2],[[67414,67423],3],[[67424,67431],2],[[67432,67455],3],[67456,2],[67457,1,"ː"],[67458,1,"ˑ"],[67459,1,"æ"],[67460,1,"ʙ"],[67461,1,"ɓ"],[67462,3],[67463,1,"ʣ"],[67464,1,"ꭦ"],[67465,1,"ʥ"],[67466,1,"ʤ"],[67467,1,"ɖ"],[67468,1,"ɗ"],[67469,1,"ᶑ"],[67470,1,"ɘ"],[67471,1,"ɞ"],[67472,1,"ʩ"],[67473,1,"ɤ"],[67474,1,"ɢ"],[67475,1,"ɠ"],[67476,1,"ʛ"],[67477,1,"ħ"],[67478,1,"ʜ"],[67479,1,"ɧ"],[67480,1,"ʄ"],[67481,1,"ʪ"],[67482,1,"ʫ"],[67483,1,"ɬ"],[67484,1,"𝼄"],[67485,1,"ꞎ"],[67486,1,"ɮ"],[67487,1,"𝼅"],[67488,1,"ʎ"],[67489,1,"𝼆"],[67490,1,"ø"],[67491,1,"ɶ"],[67492,1,"ɷ"],[67493,1,"q"],[67494,1,"ɺ"],[67495,1,"𝼈"],[67496,1,"ɽ"],[67497,1,"ɾ"],[67498,1,"ʀ"],[67499,1,"ʨ"],[67500,1,"ʦ"],[67501,1,"ꭧ"],[67502,1,"ʧ"],[67503,1,"ʈ"],[67504,1,"ⱱ"],[67505,3],[67506,1,"ʏ"],[67507,1,"ʡ"],[67508,1,"ʢ"],[67509,1,"ʘ"],[67510,1,"ǀ"],[67511,1,"ǁ"],[67512,1,"ǂ"],[67513,1,"𝼊"],[67514,1,"𝼞"],[[67515,67583],3],[[67584,67589],2],[[67590,67591],3],[67592,2],[67593,3],[[67594,67637],2],[67638,3],[[67639,67640],2],[[67641,67643],3],[67644,2],[[67645,67646],3],[67647,2],[[67648,67669],2],[67670,3],[[67671,67679],2],[[67680,67702],2],[[67703,67711],2],[[67712,67742],2],[[67743,67750],3],[[67751,67759],2],[[67760,67807],3],[[67808,67826],2],[67827,3],[[67828,67829],2],[[67830,67834],3],[[67835,67839],2],[[67840,67861],2],[[67862,67865],2],[[67866,67867],2],[[67868,67870],3],[67871,2],[[67872,67897],2],[[67898,67902],3],[67903,2],[[67904,67967],3],[[67968,68023],2],[[68024,68027],3],[[68028,68029],2],[[68030,68031],2],[[68032,68047],2],[[68048,68049],3],[[68050,68095],2],[[68096,68099],2],[68100,3],[[68101,68102],2],[[68103,68107],3],[[68108,68115],2],[68116,3],[[68117,68119],2],[68120,3],[[68121,68147],2],[[68148,68149],2],[[68150,68151],3],[[68152,68154],2],[[68155,68158],3],[68159,2],[[68160,68167],2],[68168,2],[[68169,68175],3],[[68176,68184],2],[[68185,68191],3],[[68192,68220],2],[[68221,68223],2],[[68224,68252],2],[[68253,68255],2],[[68256,68287],3],[[68288,68295],2],[68296,2],[[68297,68326],2],[[68327,68330],3],[[68331,68342],2],[[68343,68351],3],[[68352,68405],2],[[68406,68408],3],[[68409,68415],2],[[68416,68437],2],[[68438,68439],3],[[68440,68447],2],[[68448,68466],2],[[68467,68471],3],[[68472,68479],2],[[68480,68497],2],[[68498,68504],3],[[68505,68508],2],[[68509,68520],3],[[68521,68527],2],[[68528,68607],3],[[68608,68680],2],[[68681,68735],3],[68736,1,"𐳀"],[68737,1,"𐳁"],[68738,1,"𐳂"],[68739,1,"𐳃"],[68740,1,"𐳄"],[68741,1,"𐳅"],[68742,1,"𐳆"],[68743,1,"𐳇"],[68744,1,"𐳈"],[68745,1,"𐳉"],[68746,1,"𐳊"],[68747,1,"𐳋"],[68748,1,"𐳌"],[68749,1,"𐳍"],[68750,1,"𐳎"],[68751,1,"𐳏"],[68752,1,"𐳐"],[68753,1,"𐳑"],[68754,1,"𐳒"],[68755,1,"𐳓"],[68756,1,"𐳔"],[68757,1,"𐳕"],[68758,1,"𐳖"],[68759,1,"𐳗"],[68760,1,"𐳘"],[68761,1,"𐳙"],[68762,1,"𐳚"],[68763,1,"𐳛"],[68764,1,"𐳜"],[68765,1,"𐳝"],[68766,1,"𐳞"],[68767,1,"𐳟"],[68768,1,"𐳠"],[68769,1,"𐳡"],[68770,1,"𐳢"],[68771,1,"𐳣"],[68772,1,"𐳤"],[68773,1,"𐳥"],[68774,1,"𐳦"],[68775,1,"𐳧"],[68776,1,"𐳨"],[68777,1,"𐳩"],[68778,1,"𐳪"],[68779,1,"𐳫"],[68780,1,"𐳬"],[68781,1,"𐳭"],[68782,1,"𐳮"],[68783,1,"𐳯"],[68784,1,"𐳰"],[68785,1,"𐳱"],[68786,1,"𐳲"],[[68787,68799],3],[[68800,68850],2],[[68851,68857],3],[[68858,68863],2],[[68864,68903],2],[[68904,68911],3],[[68912,68921],2],[[68922,69215],3],[[69216,69246],2],[69247,3],[[69248,69289],2],[69290,3],[[69291,69292],2],[69293,2],[[69294,69295],3],[[69296,69297],2],[[69298,69375],3],[[69376,69404],2],[[69405,69414],2],[69415,2],[[69416,69423],3],[[69424,69456],2],[[69457,69465],2],[[69466,69487],3],[[69488,69509],2],[[69510,69513],2],[[69514,69551],3],[[69552,69572],2],[[69573,69579],2],[[69580,69599],3],[[69600,69622],2],[[69623,69631],3],[[69632,69702],2],[[69703,69709],2],[[69710,69713],3],[[69714,69733],2],[[69734,69743],2],[[69744,69749],2],[[69750,69758],3],[69759,2],[[69760,69818],2],[[69819,69820],2],[69821,3],[[69822,69825],2],[69826,2],[[69827,69836],3],[69837,3],[[69838,69839],3],[[69840,69864],2],[[69865,69871],3],[[69872,69881],2],[[69882,69887],3],[[69888,69940],2],[69941,3],[[69942,69951],2],[[69952,69955],2],[[69956,69958],2],[69959,2],[[69960,69967],3],[[69968,70003],2],[[70004,70005],2],[70006,2],[[70007,70015],3],[[70016,70084],2],[[70085,70088],2],[[70089,70092],2],[70093,2],[[70094,70095],2],[[70096,70105],2],[70106,2],[70107,2],[70108,2],[[70109,70111],2],[70112,3],[[70113,70132],2],[[70133,70143],3],[[70144,70161],2],[70162,3],[[70163,70199],2],[[70200,70205],2],[70206,2],[[70207,70271],3],[[70272,70278],2],[70279,3],[70280,2],[70281,3],[[70282,70285],2],[70286,3],[[70287,70301],2],[70302,3],[[70303,70312],2],[70313,2],[[70314,70319],3],[[70320,70378],2],[[70379,70383],3],[[70384,70393],2],[[70394,70399],3],[70400,2],[[70401,70403],2],[70404,3],[[70405,70412],2],[[70413,70414],3],[[70415,70416],2],[[70417,70418],3],[[70419,70440],2],[70441,3],[[70442,70448],2],[70449,3],[[70450,70451],2],[70452,3],[[70453,70457],2],[70458,3],[70459,2],[[70460,70468],2],[[70469,70470],3],[[70471,70472],2],[[70473,70474],3],[[70475,70477],2],[[70478,70479],3],[70480,2],[[70481,70486],3],[70487,2],[[70488,70492],3],[[70493,70499],2],[[70500,70501],3],[[70502,70508],2],[[70509,70511],3],[[70512,70516],2],[[70517,70655],3],[[70656,70730],2],[[70731,70735],2],[[70736,70745],2],[70746,2],[70747,2],[70748,3],[70749,2],[70750,2],[70751,2],[[70752,70753],2],[[70754,70783],3],[[70784,70853],2],[70854,2],[70855,2],[[70856,70863],3],[[70864,70873],2],[[70874,71039],3],[[71040,71093],2],[[71094,71095],3],[[71096,71104],2],[[71105,71113],2],[[71114,71127],2],[[71128,71133],2],[[71134,71167],3],[[71168,71232],2],[[71233,71235],2],[71236,2],[[71237,71247],3],[[71248,71257],2],[[71258,71263],3],[[71264,71276],2],[[71277,71295],3],[[71296,71351],2],[71352,2],[71353,2],[[71354,71359],3],[[71360,71369],2],[[71370,71423],3],[[71424,71449],2],[71450,2],[[71451,71452],3],[[71453,71467],2],[[71468,71471],3],[[71472,71481],2],[[71482,71487],2],[[71488,71494],2],[[71495,71679],3],[[71680,71738],2],[71739,2],[[71740,71839],3],[71840,1,"𑣀"],[71841,1,"𑣁"],[71842,1,"𑣂"],[71843,1,"𑣃"],[71844,1,"𑣄"],[71845,1,"𑣅"],[71846,1,"𑣆"],[71847,1,"𑣇"],[71848,1,"𑣈"],[71849,1,"𑣉"],[71850,1,"𑣊"],[71851,1,"𑣋"],[71852,1,"𑣌"],[71853,1,"𑣍"],[71854,1,"𑣎"],[71855,1,"𑣏"],[71856,1,"𑣐"],[71857,1,"𑣑"],[71858,1,"𑣒"],[71859,1,"𑣓"],[71860,1,"𑣔"],[71861,1,"𑣕"],[71862,1,"𑣖"],[71863,1,"𑣗"],[71864,1,"𑣘"],[71865,1,"𑣙"],[71866,1,"𑣚"],[71867,1,"𑣛"],[71868,1,"𑣜"],[71869,1,"𑣝"],[71870,1,"𑣞"],[71871,1,"𑣟"],[[71872,71913],2],[[71914,71922],2],[[71923,71934],3],[71935,2],[[71936,71942],2],[[71943,71944],3],[71945,2],[[71946,71947],3],[[71948,71955],2],[71956,3],[[71957,71958],2],[71959,3],[[71960,71989],2],[71990,3],[[71991,71992],2],[[71993,71994],3],[[71995,72003],2],[[72004,72006],2],[[72007,72015],3],[[72016,72025],2],[[72026,72095],3],[[72096,72103],2],[[72104,72105],3],[[72106,72151],2],[[72152,72153],3],[[72154,72161],2],[72162,2],[[72163,72164],2],[[72165,72191],3],[[72192,72254],2],[[72255,72262],2],[72263,2],[[72264,72271],3],[[72272,72323],2],[[72324,72325],2],[[72326,72345],2],[[72346,72348],2],[72349,2],[[72350,72354],2],[[72355,72367],3],[[72368,72383],2],[[72384,72440],2],[[72441,72703],3],[[72704,72712],2],[72713,3],[[72714,72758],2],[72759,3],[[72760,72768],2],[[72769,72773],2],[[72774,72783],3],[[72784,72793],2],[[72794,72812],2],[[72813,72815],3],[[72816,72817],2],[[72818,72847],2],[[72848,72849],3],[[72850,72871],2],[72872,3],[[72873,72886],2],[[72887,72959],3],[[72960,72966],2],[72967,3],[[72968,72969],2],[72970,3],[[72971,73014],2],[[73015,73017],3],[73018,2],[73019,3],[[73020,73021],2],[73022,3],[[73023,73031],2],[[73032,73039],3],[[73040,73049],2],[[73050,73055],3],[[73056,73061],2],[73062,3],[[73063,73064],2],[73065,3],[[73066,73102],2],[73103,3],[[73104,73105],2],[73106,3],[[73107,73112],2],[[73113,73119],3],[[73120,73129],2],[[73130,73439],3],[[73440,73462],2],[[73463,73464],2],[[73465,73647],3],[73648,2],[[73649,73663],3],[[73664,73713],2],[[73714,73726],3],[73727,2],[[73728,74606],2],[[74607,74648],2],[74649,2],[[74650,74751],3],[[74752,74850],2],[[74851,74862],2],[74863,3],[[74864,74867],2],[74868,2],[[74869,74879],3],[[74880,75075],2],[[75076,77711],3],[[77712,77808],2],[[77809,77810],2],[[77811,77823],3],[[77824,78894],2],[78895,3],[[78896,78904],3],[[78905,82943],3],[[82944,83526],2],[[83527,92159],3],[[92160,92728],2],[[92729,92735],3],[[92736,92766],2],[92767,3],[[92768,92777],2],[[92778,92781],3],[[92782,92783],2],[[92784,92862],2],[92863,3],[[92864,92873],2],[[92874,92879],3],[[92880,92909],2],[[92910,92911],3],[[92912,92916],2],[92917,2],[[92918,92927],3],[[92928,92982],2],[[92983,92991],2],[[92992,92995],2],[[92996,92997],2],[[92998,93007],3],[[93008,93017],2],[93018,3],[[93019,93025],2],[93026,3],[[93027,93047],2],[[93048,93052],3],[[93053,93071],2],[[93072,93759],3],[93760,1,"𖹠"],[93761,1,"𖹡"],[93762,1,"𖹢"],[93763,1,"𖹣"],[93764,1,"𖹤"],[93765,1,"𖹥"],[93766,1,"𖹦"],[93767,1,"𖹧"],[93768,1,"𖹨"],[93769,1,"𖹩"],[93770,1,"𖹪"],[93771,1,"𖹫"],[93772,1,"𖹬"],[93773,1,"𖹭"],[93774,1,"𖹮"],[93775,1,"𖹯"],[93776,1,"𖹰"],[93777,1,"𖹱"],[93778,1,"𖹲"],[93779,1,"𖹳"],[93780,1,"𖹴"],[93781,1,"𖹵"],[93782,1,"𖹶"],[93783,1,"𖹷"],[93784,1,"𖹸"],[93785,1,"𖹹"],[93786,1,"𖹺"],[93787,1,"𖹻"],[93788,1,"𖹼"],[93789,1,"𖹽"],[93790,1,"𖹾"],[93791,1,"𖹿"],[[93792,93823],2],[[93824,93850],2],[[93851,93951],3],[[93952,94020],2],[[94021,94026],2],[[94027,94030],3],[94031,2],[[94032,94078],2],[[94079,94087],2],[[94088,94094],3],[[94095,94111],2],[[94112,94175],3],[94176,2],[94177,2],[94178,2],[94179,2],[94180,2],[[94181,94191],3],[[94192,94193],2],[[94194,94207],3],[[94208,100332],2],[[100333,100337],2],[[100338,100343],2],[[100344,100351],3],[[100352,101106],2],[[101107,101589],2],[[101590,101631],3],[[101632,101640],2],[[101641,110575],3],[[110576,110579],2],[110580,3],[[110581,110587],2],[110588,3],[[110589,110590],2],[110591,3],[[110592,110593],2],[[110594,110878],2],[[110879,110882],2],[[110883,110927],3],[[110928,110930],2],[[110931,110947],3],[[110948,110951],2],[[110952,110959],3],[[110960,111355],2],[[111356,113663],3],[[113664,113770],2],[[113771,113775],3],[[113776,113788],2],[[113789,113791],3],[[113792,113800],2],[[113801,113807],3],[[113808,113817],2],[[113818,113819],3],[113820,2],[[113821,113822],2],[113823,2],[[113824,113827],7],[[113828,118527],3],[[118528,118573],2],[[118574,118575],3],[[118576,118598],2],[[118599,118607],3],[[118608,118723],2],[[118724,118783],3],[[118784,119029],2],[[119030,119039],3],[[119040,119078],2],[[119079,119080],3],[119081,2],[[119082,119133],2],[119134,1,"𝅗𝅥"],[119135,1,"𝅘𝅥"],[119136,1,"𝅘𝅥𝅮"],[119137,1,"𝅘𝅥𝅯"],[119138,1,"𝅘𝅥𝅰"],[119139,1,"𝅘𝅥𝅱"],[119140,1,"𝅘𝅥𝅲"],[[119141,119154],2],[[119155,119162],3],[[119163,119226],2],[119227,1,"𝆹𝅥"],[119228,1,"𝆺𝅥"],[119229,1,"𝆹𝅥𝅮"],[119230,1,"𝆺𝅥𝅮"],[119231,1,"𝆹𝅥𝅯"],[119232,1,"𝆺𝅥𝅯"],[[119233,119261],2],[[119262,119272],2],[[119273,119274],2],[[119275,119295],3],[[119296,119365],2],[[119366,119519],3],[[119520,119539],2],[[119540,119551],3],[[119552,119638],2],[[119639,119647],3],[[119648,119665],2],[[119666,119672],2],[[119673,119807],3],[119808,1,"a"],[119809,1,"b"],[119810,1,"c"],[119811,1,"d"],[119812,1,"e"],[119813,1,"f"],[119814,1,"g"],[119815,1,"h"],[119816,1,"i"],[119817,1,"j"],[119818,1,"k"],[119819,1,"l"],[119820,1,"m"],[119821,1,"n"],[119822,1,"o"],[119823,1,"p"],[119824,1,"q"],[119825,1,"r"],[119826,1,"s"],[119827,1,"t"],[119828,1,"u"],[119829,1,"v"],[119830,1,"w"],[119831,1,"x"],[119832,1,"y"],[119833,1,"z"],[119834,1,"a"],[119835,1,"b"],[119836,1,"c"],[119837,1,"d"],[119838,1,"e"],[119839,1,"f"],[119840,1,"g"],[119841,1,"h"],[119842,1,"i"],[119843,1,"j"],[119844,1,"k"],[119845,1,"l"],[119846,1,"m"],[119847,1,"n"],[119848,1,"o"],[119849,1,"p"],[119850,1,"q"],[119851,1,"r"],[119852,1,"s"],[119853,1,"t"],[119854,1,"u"],[119855,1,"v"],[119856,1,"w"],[119857,1,"x"],[119858,1,"y"],[119859,1,"z"],[119860,1,"a"],[119861,1,"b"],[119862,1,"c"],[119863,1,"d"],[119864,1,"e"],[119865,1,"f"],[119866,1,"g"],[119867,1,"h"],[119868,1,"i"],[119869,1,"j"],[119870,1,"k"],[119871,1,"l"],[119872,1,"m"],[119873,1,"n"],[119874,1,"o"],[119875,1,"p"],[119876,1,"q"],[119877,1,"r"],[119878,1,"s"],[119879,1,"t"],[119880,1,"u"],[119881,1,"v"],[119882,1,"w"],[119883,1,"x"],[119884,1,"y"],[119885,1,"z"],[119886,1,"a"],[119887,1,"b"],[119888,1,"c"],[119889,1,"d"],[119890,1,"e"],[119891,1,"f"],[119892,1,"g"],[119893,3],[119894,1,"i"],[119895,1,"j"],[119896,1,"k"],[119897,1,"l"],[119898,1,"m"],[119899,1,"n"],[119900,1,"o"],[119901,1,"p"],[119902,1,"q"],[119903,1,"r"],[119904,1,"s"],[119905,1,"t"],[119906,1,"u"],[119907,1,"v"],[119908,1,"w"],[119909,1,"x"],[119910,1,"y"],[119911,1,"z"],[119912,1,"a"],[119913,1,"b"],[119914,1,"c"],[119915,1,"d"],[119916,1,"e"],[119917,1,"f"],[119918,1,"g"],[119919,1,"h"],[119920,1,"i"],[119921,1,"j"],[119922,1,"k"],[119923,1,"l"],[119924,1,"m"],[119925,1,"n"],[119926,1,"o"],[119927,1,"p"],[119928,1,"q"],[119929,1,"r"],[119930,1,"s"],[119931,1,"t"],[119932,1,"u"],[119933,1,"v"],[119934,1,"w"],[119935,1,"x"],[119936,1,"y"],[119937,1,"z"],[119938,1,"a"],[119939,1,"b"],[119940,1,"c"],[119941,1,"d"],[119942,1,"e"],[119943,1,"f"],[119944,1,"g"],[119945,1,"h"],[119946,1,"i"],[119947,1,"j"],[119948,1,"k"],[119949,1,"l"],[119950,1,"m"],[119951,1,"n"],[119952,1,"o"],[119953,1,"p"],[119954,1,"q"],[119955,1,"r"],[119956,1,"s"],[119957,1,"t"],[119958,1,"u"],[119959,1,"v"],[119960,1,"w"],[119961,1,"x"],[119962,1,"y"],[119963,1,"z"],[119964,1,"a"],[119965,3],[119966,1,"c"],[119967,1,"d"],[[119968,119969],3],[119970,1,"g"],[[119971,119972],3],[119973,1,"j"],[119974,1,"k"],[[119975,119976],3],[119977,1,"n"],[119978,1,"o"],[119979,1,"p"],[119980,1,"q"],[119981,3],[119982,1,"s"],[119983,1,"t"],[119984,1,"u"],[119985,1,"v"],[119986,1,"w"],[119987,1,"x"],[119988,1,"y"],[119989,1,"z"],[119990,1,"a"],[119991,1,"b"],[119992,1,"c"],[119993,1,"d"],[119994,3],[119995,1,"f"],[119996,3],[119997,1,"h"],[119998,1,"i"],[119999,1,"j"],[120000,1,"k"],[120001,1,"l"],[120002,1,"m"],[120003,1,"n"],[120004,3],[120005,1,"p"],[120006,1,"q"],[120007,1,"r"],[120008,1,"s"],[120009,1,"t"],[120010,1,"u"],[120011,1,"v"],[120012,1,"w"],[120013,1,"x"],[120014,1,"y"],[120015,1,"z"],[120016,1,"a"],[120017,1,"b"],[120018,1,"c"],[120019,1,"d"],[120020,1,"e"],[120021,1,"f"],[120022,1,"g"],[120023,1,"h"],[120024,1,"i"],[120025,1,"j"],[120026,1,"k"],[120027,1,"l"],[120028,1,"m"],[120029,1,"n"],[120030,1,"o"],[120031,1,"p"],[120032,1,"q"],[120033,1,"r"],[120034,1,"s"],[120035,1,"t"],[120036,1,"u"],[120037,1,"v"],[120038,1,"w"],[120039,1,"x"],[120040,1,"y"],[120041,1,"z"],[120042,1,"a"],[120043,1,"b"],[120044,1,"c"],[120045,1,"d"],[120046,1,"e"],[120047,1,"f"],[120048,1,"g"],[120049,1,"h"],[120050,1,"i"],[120051,1,"j"],[120052,1,"k"],[120053,1,"l"],[120054,1,"m"],[120055,1,"n"],[120056,1,"o"],[120057,1,"p"],[120058,1,"q"],[120059,1,"r"],[120060,1,"s"],[120061,1,"t"],[120062,1,"u"],[120063,1,"v"],[120064,1,"w"],[120065,1,"x"],[120066,1,"y"],[120067,1,"z"],[120068,1,"a"],[120069,1,"b"],[120070,3],[120071,1,"d"],[120072,1,"e"],[120073,1,"f"],[120074,1,"g"],[[120075,120076],3],[120077,1,"j"],[120078,1,"k"],[120079,1,"l"],[120080,1,"m"],[120081,1,"n"],[120082,1,"o"],[120083,1,"p"],[120084,1,"q"],[120085,3],[120086,1,"s"],[120087,1,"t"],[120088,1,"u"],[120089,1,"v"],[120090,1,"w"],[120091,1,"x"],[120092,1,"y"],[120093,3],[120094,1,"a"],[120095,1,"b"],[120096,1,"c"],[120097,1,"d"],[120098,1,"e"],[120099,1,"f"],[120100,1,"g"],[120101,1,"h"],[120102,1,"i"],[120103,1,"j"],[120104,1,"k"],[120105,1,"l"],[120106,1,"m"],[120107,1,"n"],[120108,1,"o"],[120109,1,"p"],[120110,1,"q"],[120111,1,"r"],[120112,1,"s"],[120113,1,"t"],[120114,1,"u"],[120115,1,"v"],[120116,1,"w"],[120117,1,"x"],[120118,1,"y"],[120119,1,"z"],[120120,1,"a"],[120121,1,"b"],[120122,3],[120123,1,"d"],[120124,1,"e"],[120125,1,"f"],[120126,1,"g"],[120127,3],[120128,1,"i"],[120129,1,"j"],[120130,1,"k"],[120131,1,"l"],[120132,1,"m"],[120133,3],[120134,1,"o"],[[120135,120137],3],[120138,1,"s"],[120139,1,"t"],[120140,1,"u"],[120141,1,"v"],[120142,1,"w"],[120143,1,"x"],[120144,1,"y"],[120145,3],[120146,1,"a"],[120147,1,"b"],[120148,1,"c"],[120149,1,"d"],[120150,1,"e"],[120151,1,"f"],[120152,1,"g"],[120153,1,"h"],[120154,1,"i"],[120155,1,"j"],[120156,1,"k"],[120157,1,"l"],[120158,1,"m"],[120159,1,"n"],[120160,1,"o"],[120161,1,"p"],[120162,1,"q"],[120163,1,"r"],[120164,1,"s"],[120165,1,"t"],[120166,1,"u"],[120167,1,"v"],[120168,1,"w"],[120169,1,"x"],[120170,1,"y"],[120171,1,"z"],[120172,1,"a"],[120173,1,"b"],[120174,1,"c"],[120175,1,"d"],[120176,1,"e"],[120177,1,"f"],[120178,1,"g"],[120179,1,"h"],[120180,1,"i"],[120181,1,"j"],[120182,1,"k"],[120183,1,"l"],[120184,1,"m"],[120185,1,"n"],[120186,1,"o"],[120187,1,"p"],[120188,1,"q"],[120189,1,"r"],[120190,1,"s"],[120191,1,"t"],[120192,1,"u"],[120193,1,"v"],[120194,1,"w"],[120195,1,"x"],[120196,1,"y"],[120197,1,"z"],[120198,1,"a"],[120199,1,"b"],[120200,1,"c"],[120201,1,"d"],[120202,1,"e"],[120203,1,"f"],[120204,1,"g"],[120205,1,"h"],[120206,1,"i"],[120207,1,"j"],[120208,1,"k"],[120209,1,"l"],[120210,1,"m"],[120211,1,"n"],[120212,1,"o"],[120213,1,"p"],[120214,1,"q"],[120215,1,"r"],[120216,1,"s"],[120217,1,"t"],[120218,1,"u"],[120219,1,"v"],[120220,1,"w"],[120221,1,"x"],[120222,1,"y"],[120223,1,"z"],[120224,1,"a"],[120225,1,"b"],[120226,1,"c"],[120227,1,"d"],[120228,1,"e"],[120229,1,"f"],[120230,1,"g"],[120231,1,"h"],[120232,1,"i"],[120233,1,"j"],[120234,1,"k"],[120235,1,"l"],[120236,1,"m"],[120237,1,"n"],[120238,1,"o"],[120239,1,"p"],[120240,1,"q"],[120241,1,"r"],[120242,1,"s"],[120243,1,"t"],[120244,1,"u"],[120245,1,"v"],[120246,1,"w"],[120247,1,"x"],[120248,1,"y"],[120249,1,"z"],[120250,1,"a"],[120251,1,"b"],[120252,1,"c"],[120253,1,"d"],[120254,1,"e"],[120255,1,"f"],[120256,1,"g"],[120257,1,"h"],[120258,1,"i"],[120259,1,"j"],[120260,1,"k"],[120261,1,"l"],[120262,1,"m"],[120263,1,"n"],[120264,1,"o"],[120265,1,"p"],[120266,1,"q"],[120267,1,"r"],[120268,1,"s"],[120269,1,"t"],[120270,1,"u"],[120271,1,"v"],[120272,1,"w"],[120273,1,"x"],[120274,1,"y"],[120275,1,"z"],[120276,1,"a"],[120277,1,"b"],[120278,1,"c"],[120279,1,"d"],[120280,1,"e"],[120281,1,"f"],[120282,1,"g"],[120283,1,"h"],[120284,1,"i"],[120285,1,"j"],[120286,1,"k"],[120287,1,"l"],[120288,1,"m"],[120289,1,"n"],[120290,1,"o"],[120291,1,"p"],[120292,1,"q"],[120293,1,"r"],[120294,1,"s"],[120295,1,"t"],[120296,1,"u"],[120297,1,"v"],[120298,1,"w"],[120299,1,"x"],[120300,1,"y"],[120301,1,"z"],[120302,1,"a"],[120303,1,"b"],[120304,1,"c"],[120305,1,"d"],[120306,1,"e"],[120307,1,"f"],[120308,1,"g"],[120309,1,"h"],[120310,1,"i"],[120311,1,"j"],[120312,1,"k"],[120313,1,"l"],[120314,1,"m"],[120315,1,"n"],[120316,1,"o"],[120317,1,"p"],[120318,1,"q"],[120319,1,"r"],[120320,1,"s"],[120321,1,"t"],[120322,1,"u"],[120323,1,"v"],[120324,1,"w"],[120325,1,"x"],[120326,1,"y"],[120327,1,"z"],[120328,1,"a"],[120329,1,"b"],[120330,1,"c"],[120331,1,"d"],[120332,1,"e"],[120333,1,"f"],[120334,1,"g"],[120335,1,"h"],[120336,1,"i"],[120337,1,"j"],[120338,1,"k"],[120339,1,"l"],[120340,1,"m"],[120341,1,"n"],[120342,1,"o"],[120343,1,"p"],[120344,1,"q"],[120345,1,"r"],[120346,1,"s"],[120347,1,"t"],[120348,1,"u"],[120349,1,"v"],[120350,1,"w"],[120351,1,"x"],[120352,1,"y"],[120353,1,"z"],[120354,1,"a"],[120355,1,"b"],[120356,1,"c"],[120357,1,"d"],[120358,1,"e"],[120359,1,"f"],[120360,1,"g"],[120361,1,"h"],[120362,1,"i"],[120363,1,"j"],[120364,1,"k"],[120365,1,"l"],[120366,1,"m"],[120367,1,"n"],[120368,1,"o"],[120369,1,"p"],[120370,1,"q"],[120371,1,"r"],[120372,1,"s"],[120373,1,"t"],[120374,1,"u"],[120375,1,"v"],[120376,1,"w"],[120377,1,"x"],[120378,1,"y"],[120379,1,"z"],[120380,1,"a"],[120381,1,"b"],[120382,1,"c"],[120383,1,"d"],[120384,1,"e"],[120385,1,"f"],[120386,1,"g"],[120387,1,"h"],[120388,1,"i"],[120389,1,"j"],[120390,1,"k"],[120391,1,"l"],[120392,1,"m"],[120393,1,"n"],[120394,1,"o"],[120395,1,"p"],[120396,1,"q"],[120397,1,"r"],[120398,1,"s"],[120399,1,"t"],[120400,1,"u"],[120401,1,"v"],[120402,1,"w"],[120403,1,"x"],[120404,1,"y"],[120405,1,"z"],[120406,1,"a"],[120407,1,"b"],[120408,1,"c"],[120409,1,"d"],[120410,1,"e"],[120411,1,"f"],[120412,1,"g"],[120413,1,"h"],[120414,1,"i"],[120415,1,"j"],[120416,1,"k"],[120417,1,"l"],[120418,1,"m"],[120419,1,"n"],[120420,1,"o"],[120421,1,"p"],[120422,1,"q"],[120423,1,"r"],[120424,1,"s"],[120425,1,"t"],[120426,1,"u"],[120427,1,"v"],[120428,1,"w"],[120429,1,"x"],[120430,1,"y"],[120431,1,"z"],[120432,1,"a"],[120433,1,"b"],[120434,1,"c"],[120435,1,"d"],[120436,1,"e"],[120437,1,"f"],[120438,1,"g"],[120439,1,"h"],[120440,1,"i"],[120441,1,"j"],[120442,1,"k"],[120443,1,"l"],[120444,1,"m"],[120445,1,"n"],[120446,1,"o"],[120447,1,"p"],[120448,1,"q"],[120449,1,"r"],[120450,1,"s"],[120451,1,"t"],[120452,1,"u"],[120453,1,"v"],[120454,1,"w"],[120455,1,"x"],[120456,1,"y"],[120457,1,"z"],[120458,1,"a"],[120459,1,"b"],[120460,1,"c"],[120461,1,"d"],[120462,1,"e"],[120463,1,"f"],[120464,1,"g"],[120465,1,"h"],[120466,1,"i"],[120467,1,"j"],[120468,1,"k"],[120469,1,"l"],[120470,1,"m"],[120471,1,"n"],[120472,1,"o"],[120473,1,"p"],[120474,1,"q"],[120475,1,"r"],[120476,1,"s"],[120477,1,"t"],[120478,1,"u"],[120479,1,"v"],[120480,1,"w"],[120481,1,"x"],[120482,1,"y"],[120483,1,"z"],[120484,1,"ı"],[120485,1,"ȷ"],[[120486,120487],3],[120488,1,"α"],[120489,1,"β"],[120490,1,"γ"],[120491,1,"δ"],[120492,1,"ε"],[120493,1,"ζ"],[120494,1,"η"],[120495,1,"θ"],[120496,1,"ι"],[120497,1,"κ"],[120498,1,"λ"],[120499,1,"μ"],[120500,1,"ν"],[120501,1,"ξ"],[120502,1,"ο"],[120503,1,"π"],[120504,1,"ρ"],[120505,1,"θ"],[120506,1,"σ"],[120507,1,"τ"],[120508,1,"υ"],[120509,1,"φ"],[120510,1,"χ"],[120511,1,"ψ"],[120512,1,"ω"],[120513,1,"∇"],[120514,1,"α"],[120515,1,"β"],[120516,1,"γ"],[120517,1,"δ"],[120518,1,"ε"],[120519,1,"ζ"],[120520,1,"η"],[120521,1,"θ"],[120522,1,"ι"],[120523,1,"κ"],[120524,1,"λ"],[120525,1,"μ"],[120526,1,"ν"],[120527,1,"ξ"],[120528,1,"ο"],[120529,1,"π"],[120530,1,"ρ"],[[120531,120532],1,"σ"],[120533,1,"τ"],[120534,1,"υ"],[120535,1,"φ"],[120536,1,"χ"],[120537,1,"ψ"],[120538,1,"ω"],[120539,1,"∂"],[120540,1,"ε"],[120541,1,"θ"],[120542,1,"κ"],[120543,1,"φ"],[120544,1,"ρ"],[120545,1,"π"],[120546,1,"α"],[120547,1,"β"],[120548,1,"γ"],[120549,1,"δ"],[120550,1,"ε"],[120551,1,"ζ"],[120552,1,"η"],[120553,1,"θ"],[120554,1,"ι"],[120555,1,"κ"],[120556,1,"λ"],[120557,1,"μ"],[120558,1,"ν"],[120559,1,"ξ"],[120560,1,"ο"],[120561,1,"π"],[120562,1,"ρ"],[120563,1,"θ"],[120564,1,"σ"],[120565,1,"τ"],[120566,1,"υ"],[120567,1,"φ"],[120568,1,"χ"],[120569,1,"ψ"],[120570,1,"ω"],[120571,1,"∇"],[120572,1,"α"],[120573,1,"β"],[120574,1,"γ"],[120575,1,"δ"],[120576,1,"ε"],[120577,1,"ζ"],[120578,1,"η"],[120579,1,"θ"],[120580,1,"ι"],[120581,1,"κ"],[120582,1,"λ"],[120583,1,"μ"],[120584,1,"ν"],[120585,1,"ξ"],[120586,1,"ο"],[120587,1,"π"],[120588,1,"ρ"],[[120589,120590],1,"σ"],[120591,1,"τ"],[120592,1,"υ"],[120593,1,"φ"],[120594,1,"χ"],[120595,1,"ψ"],[120596,1,"ω"],[120597,1,"∂"],[120598,1,"ε"],[120599,1,"θ"],[120600,1,"κ"],[120601,1,"φ"],[120602,1,"ρ"],[120603,1,"π"],[120604,1,"α"],[120605,1,"β"],[120606,1,"γ"],[120607,1,"δ"],[120608,1,"ε"],[120609,1,"ζ"],[120610,1,"η"],[120611,1,"θ"],[120612,1,"ι"],[120613,1,"κ"],[120614,1,"λ"],[120615,1,"μ"],[120616,1,"ν"],[120617,1,"ξ"],[120618,1,"ο"],[120619,1,"π"],[120620,1,"ρ"],[120621,1,"θ"],[120622,1,"σ"],[120623,1,"τ"],[120624,1,"υ"],[120625,1,"φ"],[120626,1,"χ"],[120627,1,"ψ"],[120628,1,"ω"],[120629,1,"∇"],[120630,1,"α"],[120631,1,"β"],[120632,1,"γ"],[120633,1,"δ"],[120634,1,"ε"],[120635,1,"ζ"],[120636,1,"η"],[120637,1,"θ"],[120638,1,"ι"],[120639,1,"κ"],[120640,1,"λ"],[120641,1,"μ"],[120642,1,"ν"],[120643,1,"ξ"],[120644,1,"ο"],[120645,1,"π"],[120646,1,"ρ"],[[120647,120648],1,"σ"],[120649,1,"τ"],[120650,1,"υ"],[120651,1,"φ"],[120652,1,"χ"],[120653,1,"ψ"],[120654,1,"ω"],[120655,1,"∂"],[120656,1,"ε"],[120657,1,"θ"],[120658,1,"κ"],[120659,1,"φ"],[120660,1,"ρ"],[120661,1,"π"],[120662,1,"α"],[120663,1,"β"],[120664,1,"γ"],[120665,1,"δ"],[120666,1,"ε"],[120667,1,"ζ"],[120668,1,"η"],[120669,1,"θ"],[120670,1,"ι"],[120671,1,"κ"],[120672,1,"λ"],[120673,1,"μ"],[120674,1,"ν"],[120675,1,"ξ"],[120676,1,"ο"],[120677,1,"π"],[120678,1,"ρ"],[120679,1,"θ"],[120680,1,"σ"],[120681,1,"τ"],[120682,1,"υ"],[120683,1,"φ"],[120684,1,"χ"],[120685,1,"ψ"],[120686,1,"ω"],[120687,1,"∇"],[120688,1,"α"],[120689,1,"β"],[120690,1,"γ"],[120691,1,"δ"],[120692,1,"ε"],[120693,1,"ζ"],[120694,1,"η"],[120695,1,"θ"],[120696,1,"ι"],[120697,1,"κ"],[120698,1,"λ"],[120699,1,"μ"],[120700,1,"ν"],[120701,1,"ξ"],[120702,1,"ο"],[120703,1,"π"],[120704,1,"ρ"],[[120705,120706],1,"σ"],[120707,1,"τ"],[120708,1,"υ"],[120709,1,"φ"],[120710,1,"χ"],[120711,1,"ψ"],[120712,1,"ω"],[120713,1,"∂"],[120714,1,"ε"],[120715,1,"θ"],[120716,1,"κ"],[120717,1,"φ"],[120718,1,"ρ"],[120719,1,"π"],[120720,1,"α"],[120721,1,"β"],[120722,1,"γ"],[120723,1,"δ"],[120724,1,"ε"],[120725,1,"ζ"],[120726,1,"η"],[120727,1,"θ"],[120728,1,"ι"],[120729,1,"κ"],[120730,1,"λ"],[120731,1,"μ"],[120732,1,"ν"],[120733,1,"ξ"],[120734,1,"ο"],[120735,1,"π"],[120736,1,"ρ"],[120737,1,"θ"],[120738,1,"σ"],[120739,1,"τ"],[120740,1,"υ"],[120741,1,"φ"],[120742,1,"χ"],[120743,1,"ψ"],[120744,1,"ω"],[120745,1,"∇"],[120746,1,"α"],[120747,1,"β"],[120748,1,"γ"],[120749,1,"δ"],[120750,1,"ε"],[120751,1,"ζ"],[120752,1,"η"],[120753,1,"θ"],[120754,1,"ι"],[120755,1,"κ"],[120756,1,"λ"],[120757,1,"μ"],[120758,1,"ν"],[120759,1,"ξ"],[120760,1,"ο"],[120761,1,"π"],[120762,1,"ρ"],[[120763,120764],1,"σ"],[120765,1,"τ"],[120766,1,"υ"],[120767,1,"φ"],[120768,1,"χ"],[120769,1,"ψ"],[120770,1,"ω"],[120771,1,"∂"],[120772,1,"ε"],[120773,1,"θ"],[120774,1,"κ"],[120775,1,"φ"],[120776,1,"ρ"],[120777,1,"π"],[[120778,120779],1,"ϝ"],[[120780,120781],3],[120782,1,"0"],[120783,1,"1"],[120784,1,"2"],[120785,1,"3"],[120786,1,"4"],[120787,1,"5"],[120788,1,"6"],[120789,1,"7"],[120790,1,"8"],[120791,1,"9"],[120792,1,"0"],[120793,1,"1"],[120794,1,"2"],[120795,1,"3"],[120796,1,"4"],[120797,1,"5"],[120798,1,"6"],[120799,1,"7"],[120800,1,"8"],[120801,1,"9"],[120802,1,"0"],[120803,1,"1"],[120804,1,"2"],[120805,1,"3"],[120806,1,"4"],[120807,1,"5"],[120808,1,"6"],[120809,1,"7"],[120810,1,"8"],[120811,1,"9"],[120812,1,"0"],[120813,1,"1"],[120814,1,"2"],[120815,1,"3"],[120816,1,"4"],[120817,1,"5"],[120818,1,"6"],[120819,1,"7"],[120820,1,"8"],[120821,1,"9"],[120822,1,"0"],[120823,1,"1"],[120824,1,"2"],[120825,1,"3"],[120826,1,"4"],[120827,1,"5"],[120828,1,"6"],[120829,1,"7"],[120830,1,"8"],[120831,1,"9"],[[120832,121343],2],[[121344,121398],2],[[121399,121402],2],[[121403,121452],2],[[121453,121460],2],[121461,2],[[121462,121475],2],[121476,2],[[121477,121483],2],[[121484,121498],3],[[121499,121503],2],[121504,3],[[121505,121519],2],[[121520,122623],3],[[122624,122654],2],[[122655,122879],3],[[122880,122886],2],[122887,3],[[122888,122904],2],[[122905,122906],3],[[122907,122913],2],[122914,3],[[122915,122916],2],[122917,3],[[122918,122922],2],[[122923,123135],3],[[123136,123180],2],[[123181,123183],3],[[123184,123197],2],[[123198,123199],3],[[123200,123209],2],[[123210,123213],3],[123214,2],[123215,2],[[123216,123535],3],[[123536,123566],2],[[123567,123583],3],[[123584,123641],2],[[123642,123646],3],[123647,2],[[123648,124895],3],[[124896,124902],2],[124903,3],[[124904,124907],2],[124908,3],[[124909,124910],2],[124911,3],[[124912,124926],2],[124927,3],[[124928,125124],2],[[125125,125126],3],[[125127,125135],2],[[125136,125142],2],[[125143,125183],3],[125184,1,"𞤢"],[125185,1,"𞤣"],[125186,1,"𞤤"],[125187,1,"𞤥"],[125188,1,"𞤦"],[125189,1,"𞤧"],[125190,1,"𞤨"],[125191,1,"𞤩"],[125192,1,"𞤪"],[125193,1,"𞤫"],[125194,1,"𞤬"],[125195,1,"𞤭"],[125196,1,"𞤮"],[125197,1,"𞤯"],[125198,1,"𞤰"],[125199,1,"𞤱"],[125200,1,"𞤲"],[125201,1,"𞤳"],[125202,1,"𞤴"],[125203,1,"𞤵"],[125204,1,"𞤶"],[125205,1,"𞤷"],[125206,1,"𞤸"],[125207,1,"𞤹"],[125208,1,"𞤺"],[125209,1,"𞤻"],[125210,1,"𞤼"],[125211,1,"𞤽"],[125212,1,"𞤾"],[125213,1,"𞤿"],[125214,1,"𞥀"],[125215,1,"𞥁"],[125216,1,"𞥂"],[125217,1,"𞥃"],[[125218,125258],2],[125259,2],[[125260,125263],3],[[125264,125273],2],[[125274,125277],3],[[125278,125279],2],[[125280,126064],3],[[126065,126132],2],[[126133,126208],3],[[126209,126269],2],[[126270,126463],3],[126464,1,"ا"],[126465,1,"ب"],[126466,1,"ج"],[126467,1,"د"],[126468,3],[126469,1,"و"],[126470,1,"ز"],[126471,1,"ح"],[126472,1,"ط"],[126473,1,"ي"],[126474,1,"ك"],[126475,1,"ل"],[126476,1,"م"],[126477,1,"ن"],[126478,1,"س"],[126479,1,"ع"],[126480,1,"ف"],[126481,1,"ص"],[126482,1,"ق"],[126483,1,"ر"],[126484,1,"ش"],[126485,1,"ت"],[126486,1,"ث"],[126487,1,"خ"],[126488,1,"ذ"],[126489,1,"ض"],[126490,1,"ظ"],[126491,1,"غ"],[126492,1,"ٮ"],[126493,1,"ں"],[126494,1,"ڡ"],[126495,1,"ٯ"],[126496,3],[126497,1,"ب"],[126498,1,"ج"],[126499,3],[126500,1,"ه"],[[126501,126502],3],[126503,1,"ح"],[126504,3],[126505,1,"ي"],[126506,1,"ك"],[126507,1,"ل"],[126508,1,"م"],[126509,1,"ن"],[126510,1,"س"],[126511,1,"ع"],[126512,1,"ف"],[126513,1,"ص"],[126514,1,"ق"],[126515,3],[126516,1,"ش"],[126517,1,"ت"],[126518,1,"ث"],[126519,1,"خ"],[126520,3],[126521,1,"ض"],[126522,3],[126523,1,"غ"],[[126524,126529],3],[126530,1,"ج"],[[126531,126534],3],[126535,1,"ح"],[126536,3],[126537,1,"ي"],[126538,3],[126539,1,"ل"],[126540,3],[126541,1,"ن"],[126542,1,"س"],[126543,1,"ع"],[126544,3],[126545,1,"ص"],[126546,1,"ق"],[126547,3],[126548,1,"ش"],[[126549,126550],3],[126551,1,"خ"],[126552,3],[126553,1,"ض"],[126554,3],[126555,1,"غ"],[126556,3],[126557,1,"ں"],[126558,3],[126559,1,"ٯ"],[126560,3],[126561,1,"ب"],[126562,1,"ج"],[126563,3],[126564,1,"ه"],[[126565,126566],3],[126567,1,"ح"],[126568,1,"ط"],[126569,1,"ي"],[126570,1,"ك"],[126571,3],[126572,1,"م"],[126573,1,"ن"],[126574,1,"س"],[126575,1,"ع"],[126576,1,"ف"],[126577,1,"ص"],[126578,1,"ق"],[126579,3],[126580,1,"ش"],[126581,1,"ت"],[126582,1,"ث"],[126583,1,"خ"],[126584,3],[126585,1,"ض"],[126586,1,"ظ"],[126587,1,"غ"],[126588,1,"ٮ"],[126589,3],[126590,1,"ڡ"],[126591,3],[126592,1,"ا"],[126593,1,"ب"],[126594,1,"ج"],[126595,1,"د"],[126596,1,"ه"],[126597,1,"و"],[126598,1,"ز"],[126599,1,"ح"],[126600,1,"ط"],[126601,1,"ي"],[126602,3],[126603,1,"ل"],[126604,1,"م"],[126605,1,"ن"],[126606,1,"س"],[126607,1,"ع"],[126608,1,"ف"],[126609,1,"ص"],[126610,1,"ق"],[126611,1,"ر"],[126612,1,"ش"],[126613,1,"ت"],[126614,1,"ث"],[126615,1,"خ"],[126616,1,"ذ"],[126617,1,"ض"],[126618,1,"ظ"],[126619,1,"غ"],[[126620,126624],3],[126625,1,"ب"],[126626,1,"ج"],[126627,1,"د"],[126628,3],[126629,1,"و"],[126630,1,"ز"],[126631,1,"ح"],[126632,1,"ط"],[126633,1,"ي"],[126634,3],[126635,1,"ل"],[126636,1,"م"],[126637,1,"ن"],[126638,1,"س"],[126639,1,"ع"],[126640,1,"ف"],[126641,1,"ص"],[126642,1,"ق"],[126643,1,"ر"],[126644,1,"ش"],[126645,1,"ت"],[126646,1,"ث"],[126647,1,"خ"],[126648,1,"ذ"],[126649,1,"ض"],[126650,1,"ظ"],[126651,1,"غ"],[[126652,126703],3],[[126704,126705],2],[[126706,126975],3],[[126976,127019],2],[[127020,127023],3],[[127024,127123],2],[[127124,127135],3],[[127136,127150],2],[[127151,127152],3],[[127153,127166],2],[127167,2],[127168,3],[[127169,127183],2],[127184,3],[[127185,127199],2],[[127200,127221],2],[[127222,127231],3],[127232,3],[127233,5,"0,"],[127234,5,"1,"],[127235,5,"2,"],[127236,5,"3,"],[127237,5,"4,"],[127238,5,"5,"],[127239,5,"6,"],[127240,5,"7,"],[127241,5,"8,"],[127242,5,"9,"],[[127243,127244],2],[[127245,127247],2],[127248,5,"(a)"],[127249,5,"(b)"],[127250,5,"(c)"],[127251,5,"(d)"],[127252,5,"(e)"],[127253,5,"(f)"],[127254,5,"(g)"],[127255,5,"(h)"],[127256,5,"(i)"],[127257,5,"(j)"],[127258,5,"(k)"],[127259,5,"(l)"],[127260,5,"(m)"],[127261,5,"(n)"],[127262,5,"(o)"],[127263,5,"(p)"],[127264,5,"(q)"],[127265,5,"(r)"],[127266,5,"(s)"],[127267,5,"(t)"],[127268,5,"(u)"],[127269,5,"(v)"],[127270,5,"(w)"],[127271,5,"(x)"],[127272,5,"(y)"],[127273,5,"(z)"],[127274,1,"〔s〕"],[127275,1,"c"],[127276,1,"r"],[127277,1,"cd"],[127278,1,"wz"],[127279,2],[127280,1,"a"],[127281,1,"b"],[127282,1,"c"],[127283,1,"d"],[127284,1,"e"],[127285,1,"f"],[127286,1,"g"],[127287,1,"h"],[127288,1,"i"],[127289,1,"j"],[127290,1,"k"],[127291,1,"l"],[127292,1,"m"],[127293,1,"n"],[127294,1,"o"],[127295,1,"p"],[127296,1,"q"],[127297,1,"r"],[127298,1,"s"],[127299,1,"t"],[127300,1,"u"],[127301,1,"v"],[127302,1,"w"],[127303,1,"x"],[127304,1,"y"],[127305,1,"z"],[127306,1,"hv"],[127307,1,"mv"],[127308,1,"sd"],[127309,1,"ss"],[127310,1,"ppv"],[127311,1,"wc"],[[127312,127318],2],[127319,2],[[127320,127326],2],[127327,2],[[127328,127337],2],[127338,1,"mc"],[127339,1,"md"],[127340,1,"mr"],[[127341,127343],2],[[127344,127352],2],[127353,2],[127354,2],[[127355,127356],2],[[127357,127358],2],[127359,2],[[127360,127369],2],[[127370,127373],2],[[127374,127375],2],[127376,1,"dj"],[[127377,127386],2],[[127387,127404],2],[127405,2],[[127406,127461],3],[[127462,127487],2],[127488,1,"ほか"],[127489,1,"ココ"],[127490,1,"サ"],[[127491,127503],3],[127504,1,"手"],[127505,1,"字"],[127506,1,"双"],[127507,1,"デ"],[127508,1,"二"],[127509,1,"多"],[127510,1,"解"],[127511,1,"天"],[127512,1,"交"],[127513,1,"映"],[127514,1,"無"],[127515,1,"料"],[127516,1,"前"],[127517,1,"後"],[127518,1,"再"],[127519,1,"新"],[127520,1,"初"],[127521,1,"終"],[127522,1,"生"],[127523,1,"販"],[127524,1,"声"],[127525,1,"吹"],[127526,1,"演"],[127527,1,"投"],[127528,1,"捕"],[127529,1,"一"],[127530,1,"三"],[127531,1,"遊"],[127532,1,"左"],[127533,1,"中"],[127534,1,"右"],[127535,1,"指"],[127536,1,"走"],[127537,1,"打"],[127538,1,"禁"],[127539,1,"空"],[127540,1,"合"],[127541,1,"満"],[127542,1,"有"],[127543,1,"月"],[127544,1,"申"],[127545,1,"割"],[127546,1,"営"],[127547,1,"配"],[[127548,127551],3],[127552,1,"〔本〕"],[127553,1,"〔三〕"],[127554,1,"〔二〕"],[127555,1,"〔安〕"],[127556,1,"〔点〕"],[127557,1,"〔打〕"],[127558,1,"〔盗〕"],[127559,1,"〔勝〕"],[127560,1,"〔敗〕"],[[127561,127567],3],[127568,1,"得"],[127569,1,"可"],[[127570,127583],3],[[127584,127589],2],[[127590,127743],3],[[127744,127776],2],[[127777,127788],2],[[127789,127791],2],[[127792,127797],2],[127798,2],[[127799,127868],2],[127869,2],[[127870,127871],2],[[127872,127891],2],[[127892,127903],2],[[127904,127940],2],[127941,2],[[127942,127946],2],[[127947,127950],2],[[127951,127955],2],[[127956,127967],2],[[127968,127984],2],[[127985,127991],2],[[127992,127999],2],[[128000,128062],2],[128063,2],[128064,2],[128065,2],[[128066,128247],2],[128248,2],[[128249,128252],2],[[128253,128254],2],[128255,2],[[128256,128317],2],[[128318,128319],2],[[128320,128323],2],[[128324,128330],2],[[128331,128335],2],[[128336,128359],2],[[128360,128377],2],[128378,2],[[128379,128419],2],[128420,2],[[128421,128506],2],[[128507,128511],2],[128512,2],[[128513,128528],2],[128529,2],[[128530,128532],2],[128533,2],[128534,2],[128535,2],[128536,2],[128537,2],[128538,2],[128539,2],[[128540,128542],2],[128543,2],[[128544,128549],2],[[128550,128551],2],[[128552,128555],2],[128556,2],[128557,2],[[128558,128559],2],[[128560,128563],2],[128564,2],[[128565,128576],2],[[128577,128578],2],[[128579,128580],2],[[128581,128591],2],[[128592,128639],2],[[128640,128709],2],[[128710,128719],2],[128720,2],[[128721,128722],2],[[128723,128724],2],[128725,2],[[128726,128727],2],[[128728,128732],3],[[128733,128735],2],[[128736,128748],2],[[128749,128751],3],[[128752,128755],2],[[128756,128758],2],[[128759,128760],2],[128761,2],[128762,2],[[128763,128764],2],[[128765,128767],3],[[128768,128883],2],[[128884,128895],3],[[128896,128980],2],[[128981,128984],2],[[128985,128991],3],[[128992,129003],2],[[129004,129007],3],[129008,2],[[129009,129023],3],[[129024,129035],2],[[129036,129039],3],[[129040,129095],2],[[129096,129103],3],[[129104,129113],2],[[129114,129119],3],[[129120,129159],2],[[129160,129167],3],[[129168,129197],2],[[129198,129199],3],[[129200,129201],2],[[129202,129279],3],[[129280,129291],2],[129292,2],[[129293,129295],2],[[129296,129304],2],[[129305,129310],2],[129311,2],[[129312,129319],2],[[129320,129327],2],[129328,2],[[129329,129330],2],[[129331,129342],2],[129343,2],[[129344,129355],2],[129356,2],[[129357,129359],2],[[129360,129374],2],[[129375,129387],2],[[129388,129392],2],[129393,2],[129394,2],[[129395,129398],2],[[129399,129400],2],[129401,2],[129402,2],[129403,2],[[129404,129407],2],[[129408,129412],2],[[129413,129425],2],[[129426,129431],2],[[129432,129442],2],[[129443,129444],2],[[129445,129450],2],[[129451,129453],2],[[129454,129455],2],[[129456,129465],2],[[129466,129471],2],[129472,2],[[129473,129474],2],[[129475,129482],2],[129483,2],[129484,2],[[129485,129487],2],[[129488,129510],2],[[129511,129535],2],[[129536,129619],2],[[129620,129631],3],[[129632,129645],2],[[129646,129647],3],[[129648,129651],2],[129652,2],[[129653,129655],3],[[129656,129658],2],[[129659,129660],2],[[129661,129663],3],[[129664,129666],2],[[129667,129670],2],[[129671,129679],3],[[129680,129685],2],[[129686,129704],2],[[129705,129708],2],[[129709,129711],3],[[129712,129718],2],[[129719,129722],2],[[129723,129727],3],[[129728,129730],2],[[129731,129733],2],[[129734,129743],3],[[129744,129750],2],[[129751,129753],2],[[129754,129759],3],[[129760,129767],2],[[129768,129775],3],[[129776,129782],2],[[129783,129791],3],[[129792,129938],2],[129939,3],[[129940,129994],2],[[129995,130031],3],[130032,1,"0"],[130033,1,"1"],[130034,1,"2"],[130035,1,"3"],[130036,1,"4"],[130037,1,"5"],[130038,1,"6"],[130039,1,"7"],[130040,1,"8"],[130041,1,"9"],[[130042,131069],3],[[131070,131071],3],[[131072,173782],2],[[173783,173789],2],[[173790,173791],2],[[173792,173823],3],[[173824,177972],2],[[177973,177976],2],[[177977,177983],3],[[177984,178205],2],[[178206,178207],3],[[178208,183969],2],[[183970,183983],3],[[183984,191456],2],[[191457,194559],3],[194560,1,"丽"],[194561,1,"丸"],[194562,1,"乁"],[194563,1,"𠄢"],[194564,1,"你"],[194565,1,"侮"],[194566,1,"侻"],[194567,1,"倂"],[194568,1,"偺"],[194569,1,"備"],[194570,1,"僧"],[194571,1,"像"],[194572,1,"㒞"],[194573,1,"𠘺"],[194574,1,"免"],[194575,1,"兔"],[194576,1,"兤"],[194577,1,"具"],[194578,1,"𠔜"],[194579,1,"㒹"],[194580,1,"內"],[194581,1,"再"],[194582,1,"𠕋"],[194583,1,"冗"],[194584,1,"冤"],[194585,1,"仌"],[194586,1,"冬"],[194587,1,"况"],[194588,1,"𩇟"],[194589,1,"凵"],[194590,1,"刃"],[194591,1,"㓟"],[194592,1,"刻"],[194593,1,"剆"],[194594,1,"割"],[194595,1,"剷"],[194596,1,"㔕"],[194597,1,"勇"],[194598,1,"勉"],[194599,1,"勤"],[194600,1,"勺"],[194601,1,"包"],[194602,1,"匆"],[194603,1,"北"],[194604,1,"卉"],[194605,1,"卑"],[194606,1,"博"],[194607,1,"即"],[194608,1,"卽"],[[194609,194611],1,"卿"],[194612,1,"𠨬"],[194613,1,"灰"],[194614,1,"及"],[194615,1,"叟"],[194616,1,"𠭣"],[194617,1,"叫"],[194618,1,"叱"],[194619,1,"吆"],[194620,1,"咞"],[194621,1,"吸"],[194622,1,"呈"],[194623,1,"周"],[194624,1,"咢"],[194625,1,"哶"],[194626,1,"唐"],[194627,1,"啓"],[194628,1,"啣"],[[194629,194630],1,"善"],[194631,1,"喙"],[194632,1,"喫"],[194633,1,"喳"],[194634,1,"嗂"],[194635,1,"圖"],[194636,1,"嘆"],[194637,1,"圗"],[194638,1,"噑"],[194639,1,"噴"],[194640,1,"切"],[194641,1,"壮"],[194642,1,"城"],[194643,1,"埴"],[194644,1,"堍"],[194645,1,"型"],[194646,1,"堲"],[194647,1,"報"],[194648,1,"墬"],[194649,1,"𡓤"],[194650,1,"売"],[194651,1,"壷"],[194652,1,"夆"],[194653,1,"多"],[194654,1,"夢"],[194655,1,"奢"],[194656,1,"𡚨"],[194657,1,"𡛪"],[194658,1,"姬"],[194659,1,"娛"],[194660,1,"娧"],[194661,1,"姘"],[194662,1,"婦"],[194663,1,"㛮"],[194664,3],[194665,1,"嬈"],[[194666,194667],1,"嬾"],[194668,1,"𡧈"],[194669,1,"寃"],[194670,1,"寘"],[194671,1,"寧"],[194672,1,"寳"],[194673,1,"𡬘"],[194674,1,"寿"],[194675,1,"将"],[194676,3],[194677,1,"尢"],[194678,1,"㞁"],[194679,1,"屠"],[194680,1,"屮"],[194681,1,"峀"],[194682,1,"岍"],[194683,1,"𡷤"],[194684,1,"嵃"],[194685,1,"𡷦"],[194686,1,"嵮"],[194687,1,"嵫"],[194688,1,"嵼"],[194689,1,"巡"],[194690,1,"巢"],[194691,1,"㠯"],[194692,1,"巽"],[194693,1,"帨"],[194694,1,"帽"],[194695,1,"幩"],[194696,1,"㡢"],[194697,1,"𢆃"],[194698,1,"㡼"],[194699,1,"庰"],[194700,1,"庳"],[194701,1,"庶"],[194702,1,"廊"],[194703,1,"𪎒"],[194704,1,"廾"],[[194705,194706],1,"𢌱"],[194707,1,"舁"],[[194708,194709],1,"弢"],[194710,1,"㣇"],[194711,1,"𣊸"],[194712,1,"𦇚"],[194713,1,"形"],[194714,1,"彫"],[194715,1,"㣣"],[194716,1,"徚"],[194717,1,"忍"],[194718,1,"志"],[194719,1,"忹"],[194720,1,"悁"],[194721,1,"㤺"],[194722,1,"㤜"],[194723,1,"悔"],[194724,1,"𢛔"],[194725,1,"惇"],[194726,1,"慈"],[194727,1,"慌"],[194728,1,"慎"],[194729,1,"慌"],[194730,1,"慺"],[194731,1,"憎"],[194732,1,"憲"],[194733,1,"憤"],[194734,1,"憯"],[194735,1,"懞"],[194736,1,"懲"],[194737,1,"懶"],[194738,1,"成"],[194739,1,"戛"],[194740,1,"扝"],[194741,1,"抱"],[194742,1,"拔"],[194743,1,"捐"],[194744,1,"𢬌"],[194745,1,"挽"],[194746,1,"拼"],[194747,1,"捨"],[194748,1,"掃"],[194749,1,"揤"],[194750,1,"𢯱"],[194751,1,"搢"],[194752,1,"揅"],[194753,1,"掩"],[194754,1,"㨮"],[194755,1,"摩"],[194756,1,"摾"],[194757,1,"撝"],[194758,1,"摷"],[194759,1,"㩬"],[194760,1,"敏"],[194761,1,"敬"],[194762,1,"𣀊"],[194763,1,"旣"],[194764,1,"書"],[194765,1,"晉"],[194766,1,"㬙"],[194767,1,"暑"],[194768,1,"㬈"],[194769,1,"㫤"],[194770,1,"冒"],[194771,1,"冕"],[194772,1,"最"],[194773,1,"暜"],[194774,1,"肭"],[194775,1,"䏙"],[194776,1,"朗"],[194777,1,"望"],[194778,1,"朡"],[194779,1,"杞"],[194780,1,"杓"],[194781,1,"𣏃"],[194782,1,"㭉"],[194783,1,"柺"],[194784,1,"枅"],[194785,1,"桒"],[194786,1,"梅"],[194787,1,"𣑭"],[194788,1,"梎"],[194789,1,"栟"],[194790,1,"椔"],[194791,1,"㮝"],[194792,1,"楂"],[194793,1,"榣"],[194794,1,"槪"],[194795,1,"檨"],[194796,1,"𣚣"],[194797,1,"櫛"],[194798,1,"㰘"],[194799,1,"次"],[194800,1,"𣢧"],[194801,1,"歔"],[194802,1,"㱎"],[194803,1,"歲"],[194804,1,"殟"],[194805,1,"殺"],[194806,1,"殻"],[194807,1,"𣪍"],[194808,1,"𡴋"],[194809,1,"𣫺"],[194810,1,"汎"],[194811,1,"𣲼"],[194812,1,"沿"],[194813,1,"泍"],[194814,1,"汧"],[194815,1,"洖"],[194816,1,"派"],[194817,1,"海"],[194818,1,"流"],[194819,1,"浩"],[194820,1,"浸"],[194821,1,"涅"],[194822,1,"𣴞"],[194823,1,"洴"],[194824,1,"港"],[194825,1,"湮"],[194826,1,"㴳"],[194827,1,"滋"],[194828,1,"滇"],[194829,1,"𣻑"],[194830,1,"淹"],[194831,1,"潮"],[194832,1,"𣽞"],[194833,1,"𣾎"],[194834,1,"濆"],[194835,1,"瀹"],[194836,1,"瀞"],[194837,1,"瀛"],[194838,1,"㶖"],[194839,1,"灊"],[194840,1,"災"],[194841,1,"灷"],[194842,1,"炭"],[194843,1,"𠔥"],[194844,1,"煅"],[194845,1,"𤉣"],[194846,1,"熜"],[194847,3],[194848,1,"爨"],[194849,1,"爵"],[194850,1,"牐"],[194851,1,"𤘈"],[194852,1,"犀"],[194853,1,"犕"],[194854,1,"𤜵"],[194855,1,"𤠔"],[194856,1,"獺"],[194857,1,"王"],[194858,1,"㺬"],[194859,1,"玥"],[[194860,194861],1,"㺸"],[194862,1,"瑇"],[194863,1,"瑜"],[194864,1,"瑱"],[194865,1,"璅"],[194866,1,"瓊"],[194867,1,"㼛"],[194868,1,"甤"],[194869,1,"𤰶"],[194870,1,"甾"],[194871,1,"𤲒"],[194872,1,"異"],[194873,1,"𢆟"],[194874,1,"瘐"],[194875,1,"𤾡"],[194876,1,"𤾸"],[194877,1,"𥁄"],[194878,1,"㿼"],[194879,1,"䀈"],[194880,1,"直"],[194881,1,"𥃳"],[194882,1,"𥃲"],[194883,1,"𥄙"],[194884,1,"𥄳"],[194885,1,"眞"],[[194886,194887],1,"真"],[194888,1,"睊"],[194889,1,"䀹"],[194890,1,"瞋"],[194891,1,"䁆"],[194892,1,"䂖"],[194893,1,"𥐝"],[194894,1,"硎"],[194895,1,"碌"],[194896,1,"磌"],[194897,1,"䃣"],[194898,1,"𥘦"],[194899,1,"祖"],[194900,1,"𥚚"],[194901,1,"𥛅"],[194902,1,"福"],[194903,1,"秫"],[194904,1,"䄯"],[194905,1,"穀"],[194906,1,"穊"],[194907,1,"穏"],[194908,1,"𥥼"],[[194909,194910],1,"𥪧"],[194911,3],[194912,1,"䈂"],[194913,1,"𥮫"],[194914,1,"篆"],[194915,1,"築"],[194916,1,"䈧"],[194917,1,"𥲀"],[194918,1,"糒"],[194919,1,"䊠"],[194920,1,"糨"],[194921,1,"糣"],[194922,1,"紀"],[194923,1,"𥾆"],[194924,1,"絣"],[194925,1,"䌁"],[194926,1,"緇"],[194927,1,"縂"],[194928,1,"繅"],[194929,1,"䌴"],[194930,1,"𦈨"],[194931,1,"𦉇"],[194932,1,"䍙"],[194933,1,"𦋙"],[194934,1,"罺"],[194935,1,"𦌾"],[194936,1,"羕"],[194937,1,"翺"],[194938,1,"者"],[194939,1,"𦓚"],[194940,1,"𦔣"],[194941,1,"聠"],[194942,1,"𦖨"],[194943,1,"聰"],[194944,1,"𣍟"],[194945,1,"䏕"],[194946,1,"育"],[194947,1,"脃"],[194948,1,"䐋"],[194949,1,"脾"],[194950,1,"媵"],[194951,1,"𦞧"],[194952,1,"𦞵"],[194953,1,"𣎓"],[194954,1,"𣎜"],[194955,1,"舁"],[194956,1,"舄"],[194957,1,"辞"],[194958,1,"䑫"],[194959,1,"芑"],[194960,1,"芋"],[194961,1,"芝"],[194962,1,"劳"],[194963,1,"花"],[194964,1,"芳"],[194965,1,"芽"],[194966,1,"苦"],[194967,1,"𦬼"],[194968,1,"若"],[194969,1,"茝"],[194970,1,"荣"],[194971,1,"莭"],[194972,1,"茣"],[194973,1,"莽"],[194974,1,"菧"],[194975,1,"著"],[194976,1,"荓"],[194977,1,"菊"],[194978,1,"菌"],[194979,1,"菜"],[194980,1,"𦰶"],[194981,1,"𦵫"],[194982,1,"𦳕"],[194983,1,"䔫"],[194984,1,"蓱"],[194985,1,"蓳"],[194986,1,"蔖"],[194987,1,"𧏊"],[194988,1,"蕤"],[194989,1,"𦼬"],[194990,1,"䕝"],[194991,1,"䕡"],[194992,1,"𦾱"],[194993,1,"𧃒"],[194994,1,"䕫"],[194995,1,"虐"],[194996,1,"虜"],[194997,1,"虧"],[194998,1,"虩"],[194999,1,"蚩"],[195000,1,"蚈"],[195001,1,"蜎"],[195002,1,"蛢"],[195003,1,"蝹"],[195004,1,"蜨"],[195005,1,"蝫"],[195006,1,"螆"],[195007,3],[195008,1,"蟡"],[195009,1,"蠁"],[195010,1,"䗹"],[195011,1,"衠"],[195012,1,"衣"],[195013,1,"𧙧"],[195014,1,"裗"],[195015,1,"裞"],[195016,1,"䘵"],[195017,1,"裺"],[195018,1,"㒻"],[195019,1,"𧢮"],[195020,1,"𧥦"],[195021,1,"䚾"],[195022,1,"䛇"],[195023,1,"誠"],[195024,1,"諭"],[195025,1,"變"],[195026,1,"豕"],[195027,1,"𧲨"],[195028,1,"貫"],[195029,1,"賁"],[195030,1,"贛"],[195031,1,"起"],[195032,1,"𧼯"],[195033,1,"𠠄"],[195034,1,"跋"],[195035,1,"趼"],[195036,1,"跰"],[195037,1,"𠣞"],[195038,1,"軔"],[195039,1,"輸"],[195040,1,"𨗒"],[195041,1,"𨗭"],[195042,1,"邔"],[195043,1,"郱"],[195044,1,"鄑"],[195045,1,"𨜮"],[195046,1,"鄛"],[195047,1,"鈸"],[195048,1,"鋗"],[195049,1,"鋘"],[195050,1,"鉼"],[195051,1,"鏹"],[195052,1,"鐕"],[195053,1,"𨯺"],[195054,1,"開"],[195055,1,"䦕"],[195056,1,"閷"],[195057,1,"𨵷"],[195058,1,"䧦"],[195059,1,"雃"],[195060,1,"嶲"],[195061,1,"霣"],[195062,1,"𩅅"],[195063,1,"𩈚"],[195064,1,"䩮"],[195065,1,"䩶"],[195066,1,"韠"],[195067,1,"𩐊"],[195068,1,"䪲"],[195069,1,"𩒖"],[[195070,195071],1,"頋"],[195072,1,"頩"],[195073,1,"𩖶"],[195074,1,"飢"],[195075,1,"䬳"],[195076,1,"餩"],[195077,1,"馧"],[195078,1,"駂"],[195079,1,"駾"],[195080,1,"䯎"],[195081,1,"𩬰"],[195082,1,"鬒"],[195083,1,"鱀"],[195084,1,"鳽"],[195085,1,"䳎"],[195086,1,"䳭"],[195087,1,"鵧"],[195088,1,"𪃎"],[195089,1,"䳸"],[195090,1,"𪄅"],[195091,1,"𪈎"],[195092,1,"𪊑"],[195093,1,"麻"],[195094,1,"䵖"],[195095,1,"黹"],[195096,1,"黾"],[195097,1,"鼅"],[195098,1,"鼏"],[195099,1,"鼖"],[195100,1,"鼻"],[195101,1,"𪘀"],[[195102,196605],3],[[196606,196607],3],[[196608,201546],2],[[201547,262141],3],[[262142,262143],3],[[262144,327677],3],[[327678,327679],3],[[327680,393213],3],[[393214,393215],3],[[393216,458749],3],[[458750,458751],3],[[458752,524285],3],[[524286,524287],3],[[524288,589821],3],[[589822,589823],3],[[589824,655357],3],[[655358,655359],3],[[655360,720893],3],[[720894,720895],3],[[720896,786429],3],[[786430,786431],3],[[786432,851965],3],[[851966,851967],3],[[851968,917501],3],[[917502,917503],3],[917504,3],[917505,3],[[917506,917535],3],[[917536,917631],3],[[917632,917759],3],[[917760,917999],7],[[918000,983037],3],[[983038,983039],3],[[983040,1048573],3],[[1048574,1048575],3],[[1048576,1114109],3],[[1114110,1114111],3]]'); - // UNUSED EXPORTS: connectToDb +/***/ }), - // EXTERNAL MODULE: ./node_modules/debug/src/index.js - var src = __nccwpck_require__(8237); - var src_default = /*#__PURE__*/ __nccwpck_require__.n(src); // CONCATENATED MODULE: ./src/lib/debuggers.ts - const debugMongo = src_default()("vn:mongo"); +/***/ 306: +/***/ ((module) => { - // EXTERNAL MODULE: ./node_modules/mongoose/index.js - var mongoose = __nccwpck_require__(4740); - var mongoose_default = /*#__PURE__*/ __nccwpck_require__.n(mongoose); // CONCATENATED MODULE: ./src/api/mongoose/connection.ts - const globalNode = { - mongooseCache: undefined, - ...global, - }; - let mongooseCache = globalNode.mongooseCache; // shared promise, so "then" chains are called correctly for all code trying to connect (avoids race conditions) - if (!mongooseCache) { - globalNode.mongooseCache = { connectPromise: null }; - mongooseCache = globalNode.mongooseCache; - } - /** - * Connect to any mongo database - * - * NOTE: do not use directly, prefer using "connectToMainDb" - * @param mongoUri - * @param options - */ - const connectToDb = async (mongoUri, options) => { - if ( - mongooseCache === null || mongooseCache === void 0 - ? void 0 - : mongooseCache.connectPromise - ) { - debugMongo( - "Running connectToDb, already connected or connecting to Mongo, waiting for promise" - ); - await mongooseCache.connectPromise; - } - if (![1, 2].includes(mongoose_default().connection.readyState)) { - debugMongo("Call mongoose connect"); - mongooseCache.connectPromise = mongoose_default().connect(mongoUri, { - useNewUrlParser: true, - useUnifiedTopology: true, - ...(options || {}), - }); - // Wait for connection - await (mongooseCache === null || mongooseCache === void 0 - ? void 0 - : mongooseCache.connectPromise); - } - }; - /** - * Connect to the application main database - * - * Mongo URI is provided throught the MONGO_URI environment variable - */ - const connectToAppDb = async () => { - const mongoUri = process.env.MONGO_URI; - if (!mongoUri) throw new Error("MONGO_URI env variable is not defined"); - const isLocalMongo = mongoUri.match(/localhost/); - try { - await connectToDb(mongoUri, { - // fail the seed early during development - serverSelectionTimeoutMS: isLocalMongo ? 3000 : undefined, - }); - } catch (err) { - console.error( - `\nCould not connect to Mongo database on URI ${mongoUri}.` - ); - if (isLocalMongo) { - console.error("Did you forget to run 'yarn run start:mongo'?\n"); - } - console.error(err); - // rethrow - throw err; - } - }; - async function closeDbConnection() { - try { - await mongoose_default().connection.close(); - } catch (err) { - // Catch locally error - console.error("Could not close mongoose connection"); - console.error(err); - throw err; - } - } +"use strict"; +module.exports = JSON.parse('{"name":"vulcan-next","version":"0.6.5","private":true,"scripts":{"analyze:bundle:storybook":"cross-env ANALYZE=true yarn run build:storybook","analyze:bundle":"cross-env ANALYZE=true npm run build","auto-changelog":"auto-changelog -u","build-storybook":"build-storybook","build:docker":"docker build -f ./.vn/docker/vn.production.dockerfile -t vulcan-next .","build:scripts":"./.vn/scripts/build-scripts.sh","build:static":"# Next Export is not compatible with i18n, this feature is now deactivated in Vulcan Next. See https://github.com/VulcanJS/vulcan-next/issues/98 #next build && next export","build:storybook":"rm -Rf storybook-static && build-storybook -s ./public # TODO: we shouldn\'t need to remove, but Storybook 6.1 has a small bug and can\'t remove existing build automatically","build:test:docker":"docker build -f ./.vn/docker/cypress.dockerfile -t vulcan-next-test .","build":"next build","chromatic":"dotenv -e .env.development.local chromatic --build-script-name build-storybook","clean":"rm -Rf ./dist ./storybook-static .yalc # clean various build folders","combine:reports":"nyc merge reports && mv coverage.json .nyc_output/out.json # intermediate script","copy:reports":"cp coverage-e2e/coverage-final.json reports/from-cypress.json && cp coverage-unit/coverage-final.json reports/from-jest.json # intermediate scripts","coverage:e2e":"cross-env COVERAGE=1 npm run build && start-server-and-test start:test http://localhost:3000 \'COVERAGE=1 cypress run\'","coverage:unit":"jest --coverage","coverage":"npm run coverage:unit && npm run coverage:e2e","cypress:open":"cross-env CYPRESS_coverage=false NODE_ENV=test cypress open","cypress:run":"cross-env CYPRESS_DEBUG=false CYPRESS_coverage=false NODE_ENV=test cypress run --headless","db:test:seed":"dotenv -e .env.test node .vn/scripts/db/seed.js","db:test:reset":"dotenv -e .env.test node .vn/scripts/db/reset.js # reset can only happen against the test database!","debug":"NODE_OPTIONS=\'--inspect\' next","dev":"next","dev:test":"cross-env NODE_ENV=test next # Start app in test + dev mode","link:vulcan":"./.vn/scripts/link-vulcan.sh # for linking a local copy of Vulcan NPM monorepo (don\'t forget to publish in Vulcan NPM first)","lint":"yarn run next lint","mkdir:reports":"rm -Rf reports && mkdir reports || true # intermediate script","mongo":"yarn run start:mongo  # shortcut for start:mongo","postbuild":"next-sitemap --config vulcan-next-sitemap.js","postcoverage":"npm run report:combined # combine jest and cypress coverage reports","postinstall":"","precombine:reports":"npm run copy:reports && rm -Rf .nyc_output && mkdir .nyc_output || true # intermediate script","precopy:reports":"npm run mkdir:reports # intermediate script","precoverage":"rm -rf .nyc_output || true # delete previous nyx instrumentation","prereport:combined":"npm run combine:reports # intermediate script","report:combined":"nyc report --reporter lcov --report-dir coverage | exit 0 # intermediate script","start:docker":"docker run -p 3000:3000 --env-file .env.development -it vns:latest","start:mongo":"docker run --rm -p 27017:27017 -v \\"$(pwd)/.mongo:/data/db\\" --label vulcan-mongodb mongo:4.0.4 # will start or create & start the image + store data locally in .mongo folder + remove the container when stopped","start:static":"# Next Export is not compatible with i18n, this feature is now deactivated in Vulcan Next. See https://github.com/VulcanJS/vulcan-next/issues/98 #serve ./out","start:storybook-static":"serve storybook-static","start:test":"cross-env NODE_ENV=test npm run start # Start app in test mode","start":"next start","storybook":"start-storybook -p 6006 -s ./public","test:docker":"docker run --env-file .env.development -it vns-test:latest","test:e2e":"cross-env NODE_ENV=test npm run build && start-server-and-test start:test http://localhost:3000 \'cypress:run\'","test:unit":"jest","test:vn":"jest --config=./.vn/jest.config.vn.js --testPathPattern=tests/vn # run tests for Vulcan Next itself, eg scripts (long) ","test":"npm run test:unit && npm run test:e2e","upgrade:vulcan":"yarn upgrade --pattern \'@vulcanjs/*\'","typecheck-watch":"tsc --noEmit --p src/tsconfig.json -w","typecheck":"tsc --noEmit --p src/tsconfig.json # in case of error with @vulcanjs/* package, check that src/types (eg simpl-schema) are up-to-date with vulcan-npm","link:vulcan:update":"yalc update"},"dependencies":{"@apollo/client":"^3.2.0","@emotion/cache":"^11.4.0","@emotion/react":"^11.4.1","@emotion/server":"^11.4.0","@emotion/styled":"^11.3.0","@hapi/iron":"6.0.0","@mdx-js/loader":"^1.6.6","@mdx-js/react":"^1.6.13","@mui/icons-material":"^5.0.0","@mui/material":"^5.0.0","@next/mdx":"^10.0.2","@vulcanjs/demo":"^0.4.0","@vulcanjs/graphql":"^0.4.0","@vulcanjs/mdx":"^0.4.0","@vulcanjs/meteor-legacy":"^0.4.0","@vulcanjs/mongo":"^0.4.0","@vulcanjs/react-hooks":"^0.4.0","@vulcanjs/react-ui":"^0.4.2","apollo-server-express":"2.14.2","babel-jest":"26.0.1","babel-plugin-istanbul":"6.0.0","bcrypt":"^5.0.1","clsx":"^1.1.1","cors":"^2.8.5","cross-env":"7.0.2","debug":"4.1.1","express":"4.17.1","graphql":"15.4.0","graphql-tag":"2.10.3","gray-matter":"^4.0.2","i18next":"^19.4.5","i18next-browser-languagedetector":"^4.2.0","i18next-http-backend":"^1.0.15","lodash":"^4.17.19","mongoose":"6","nanoid":"^3.1.25","next":"12","next-connect":"^0.9.1","next-i18next":"^8.10.0","next-mdx-remote":"3","next-sitemap":"^1.4.17","nodemailer":"^6.6.3","passport":"^0.4.1","passport-local":"1.0.0","polished":"^3.6.5","postcss-nested":"^4.2.1","querystring":"^0.2.1","react":"^17.0.1","react-bootstrap-typeahead":"^6.0.0-alpha.4","react-cookie":"^4.1.1","react-dom":"^17.0.1","react-hook-form":"4.9.8","react-i18next":"^11.5.0","react-spring":"^8.0.27","styled-jsx-plugin-postcss":"^3.0.2","swr":"^0.4.0"},"devDependencies":{"@babel/core":"^7.10.2","@storybook/testing-react":"^0.0.22","@types/mongoose":"^5.7.27","@types/node":"^13.7.6","@types/nodemailer":"^6.4.4","@types/react":"^16.9.23","@types/react-dom":"^16.9.5","@types/shelljs":"^0.8.8","@vercel/ncc":"^0.30.0","babel-loader":"^8.1.0","babel-plugin-import":"^1.13.3","chalk":"^4.1.2","eslint":"^7.32.0","graphql-voyager":"^1.0.0-rc.31","mongodb-memory-server":"^7.3.6","react-is":"^16.13.1","source-map-support":"^0.5.19","storybook-css-modules-preset":"^1.1.1","supertest":"^6.1.6","ts-loader":"^7.0.5","ts-node":"^8.10.2","typescript":"=4.3.5","yalc":"^1.0.0-pre.53"},"optionalDependencies":{"@cypress/code-coverage":"^3.8.1","@cypress/webpack-preprocessor":"^5.4.1","@istanbuljs/nyc-config-typescript":"^1.0.1","@next/bundle-analyzer":"^9.4.4","@next/plugin-storybook":"^11.1.0","@storybook/addon-a11y":"^6.3.7","@storybook/addon-actions":"^6.3.7","@storybook/addon-backgrounds":"^6.3.7","@storybook/addon-controls":"^6.3.7","@storybook/addon-docs":"^6.3.7","@storybook/addon-essentials":"^6.3.7","@storybook/addon-links":"^6.3.7","@storybook/addons":"^6.3.7","@storybook/react":"^6.3.7","@testing-library/cypress":"^6.0.0","@testing-library/jest-dom":"^5.9.0","@testing-library/react":"^10.2.0","@testing-library/react-hooks":"^3.3.0","@types/jest":"^25.2.3","auto-changelog":"^2.2.1","chromatic":"^5.9.2","cypress":"^9","dotenv-cli":"^4.0.0","eslint-config-next":"^11.1.0","eslint-plugin-cypress":"2.11.1","jest":"^26.0.1","jest-transformer-mdx":"^2.2.0","nyc":"^15.1.0","serve":"^11.3.2","shelljs":"^0.8.4","smtp-tester":"^1.2.0","start-server-and-test":"^1.11.0","storybook-addon-next-router":"^3.0.7"}}'); - /***/ - }, +/***/ }), - /***/ 5764: /***/ (module) => { - module.exports = eval("require")("mongodb-client-encryption"); +/***/ 2357: +/***/ ((module) => { - /***/ - }, +"use strict"; +module.exports = require("assert"); - /***/ 869: /***/ (module) => { - function webpackEmptyContext(req) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = "MODULE_NOT_FOUND"; - throw e; - } - webpackEmptyContext.keys = () => []; - webpackEmptyContext.resolve = webpackEmptyContext; - webpackEmptyContext.id = 869; - module.exports = webpackEmptyContext; +/***/ }), - /***/ - }, +/***/ 4293: +/***/ ((module) => { - /***/ 306: /***/ (module) => { - "use strict"; - module.exports = JSON.parse( - '{"name":"vulcan-next","version":"0.4.1","private":true,"scripts":{"analyze-bundle:storybook":"cross-env ANALYZE=true yarn run build:storybook","analyze-bundle":"cross-env ANALYZE=true npm run build","auto-changelog":"auto-changelog -u","build-storybook":"build-storybook","build:docker":"docker build -f ./.vn/docker/vn.production.dockerfile -t vulcan-next .","build:scripts":"./.vn/scripts/build-scripts.sh","build:static":"next build && next export","build:storybook":"rm -Rf storybook-static && build-storybook -s ./public # TODO: we shouldn\'t need to remove, but Storybook 6.1 has a small bug and can\'t remove existing build automatically","build:test:docker":"docker build -f ./.vn/docker/cypress.dockerfile -t vulcan-next-test .","build":"next build","chromatic":"dotenv -e .env.development.local chromatic --build-script-name build-storybook","clean":"rm -Rf ./dist ./storybook-static .yalc # clean various build folders","combine:reports":"nyc merge reports && mv coverage.json .nyc_output/out.json # intermediate script","copy:reports":"cp coverage-e2e/coverage-final.json reports/from-cypress.json && cp coverage-unit/coverage-final.json reports/from-jest.json # intermediate scripts","coverage:e2e":"cross-env COVERAGE=1 npm run build && start-server-and-test start:test http://localhost:3000 \'COVERAGE=1 cypress run\'","coverage:unit":"jest --coverage","coverage":"npm run coverage:unit && npm run coverage:e2e","cypress:open":"cross-env CYPRESS_coverage=false NODE_ENV=test cypress open","cypress:run":"cross-env CYPRESS_DEBUG=false CYPRESS_coverage=false NODE_ENV=test cypress run --headless","db:test:seed":"dotenv -e .env.test node .vn/scripts/db/seed.js","db:test:reset":"dotenv -e .env.test node .vn/scripts/db/reset.js # reset can only happen against the test database!","debug":"NODE_OPTIONS=\'--inspect\' next","dev":"next","dev:test":"cross-env NODE_ENV=test next # Start app in test + dev mode","link-vulcan":"./.vn/scripts/link-vulcan.sh # for linking a local copy of Vulcan NPM monorepo (don\'t forget to publish in Vulcan NPM first)","lint":"yarn run next lint","mkdir:reports":"rm -Rf reports && mkdir reports || true # intermediate script","mongo":"yarn run start:mongo  # shortcut for start:mongo","postbuild":"next-sitemap --config vulcan-next-sitemap.js","postcoverage":"npm run report:combined # combine jest and cypress coverage reports","postinstall":"","precombine:reports":"npm run copy:reports && rm -Rf .nyc_output && mkdir .nyc_output || true # intermediate script","precopy:reports":"npm run mkdir:reports # intermediate script","precoverage":"rm -rf .nyc_output || true # delete previous nyx instrumentation","prereport:combined":"npm run combine:reports # intermediate script","report:combined":"nyc report --reporter lcov --report-dir coverage | exit 0 # intermediate script","start:docker":"docker run -p 3000:3000 --env-file .env.development -it vns:latest","start:mongo":"docker run --rm -p 27017:27017 -v \\"$(pwd)/.mongo:/data/db\\" --label vulcan-mongodb mongo:4.0.4 # will start or create & start the image + store data locally in .mongo folder + remove the container when stopped","start:static":"serve ./out","start:storybook-static":"serve storybook-static","start:test":"cross-env NODE_ENV=test npm run start # Start app in test mode","start":"next start","storybook":"start-storybook -p 6006 -s ./public","test:docker":"docker run --env-file .env.development -it vns-test:latest","test:e2e":"cross-env NODE_ENV=test npm run build && start-server-and-test start:test http://localhost:3000 \'cypress:run\'","test:unit":"jest --testPathIgnorePatterns=tests/vn","test:vn":"jest --testPathPattern=tests/vn # run tests for Vulcan Next itself, eg scripts (long) ","test":"npm run test:unit && npm run test:e2e","typecheck-watch":"tsc --noEmit --p src/tsconfig.json -w","typecheck":"tsc --noEmit --p src/tsconfig.json # in case of error with @vulcanjs/* package, check that src/types (eg simpl-schema) are up-to-date with vulcan-npm","link:vulcan:update":"yalc update"},"dependencies":{"@apollo/client":"^3.2.0","@emotion/react":"^11.4.0","@emotion/styled":"^11.3.0","@hapi/iron":"6.0.0","@material-ui/core":"^5.0.0-alpha.37","@material-ui/styles":"^4.11.4","@mdx-js/loader":"^1.6.6","@mdx-js/react":"^1.6.13","@next/mdx":"^10.0.2","@vulcanjs/demo":"^0.0.7","@vulcanjs/graphql":"^0.2.4","@vulcanjs/mdx":"^0.2.3-alpha.0","@vulcanjs/meteor-legacy":"^0.1.8","@vulcanjs/mongo":"^0.2.4","@vulcanjs/react-hooks":"^0.2.3","@vulcanjs/react-ui":"^0.2.3","apollo-server-express":"2.14.2","babel-jest":"26.0.1","babel-plugin-istanbul":"6.0.0","clsx":"^1.1.1","cors":"^2.8.5","cross-env":"7.0.2","debug":"4.1.1","express":"4.17.1","graphql":"15.4.0","graphql-tag":"2.10.3","gray-matter":"^4.0.2","i18next":"^19.4.5","i18next-browser-languagedetector":"^4.2.0","i18next-http-backend":"^1.0.15","lodash":"^4.17.19","mongoose":"^5.9.19","nanoid":"^3.1.25","next":"^11.1.0","next-connect":"^0.9.1","next-i18next":"^5.1.0","next-mdx-remote":"^2.1.3","next-sitemap":"^1.4.17","passport":"^0.4.1","passport-local":"1.0.0","polished":"^3.6.5","postcss-nested":"^4.2.1","react":"^17.0.1","react-dom":"^17.0.1","react-hook-form":"4.9.8","react-i18next":"^11.5.0","react-spring":"^8.0.27","styled-jsx-plugin-postcss":"^3.0.2","swr":"^0.4.0"},"devDependencies":{"@babel/core":"^7.10.2","@storybook/testing-react":"^0.0.22","@types/mongoose":"^5.7.27","@types/node":"^13.7.6","@types/react":"^16.9.23","@types/react-dom":"^16.9.5","@types/shelljs":"^0.8.8","@vercel/ncc":"^0.30.0","babel-loader":"^8.1.0","eslint":"^7.32.0","graphql-voyager":"^1.0.0-rc.31","mongodb-memory-server":"^7.3.6","react-is":"^16.13.1","source-map-support":"^0.5.19","storybook-css-modules-preset":"^1.1.1","ts-loader":"^7.0.5","ts-node":"^8.10.2","typescript":"=4.3.5","yalc":"^1.0.0-pre.53"},"optionalDependencies":{"@cypress/code-coverage":"^3.8.1","@cypress/webpack-preprocessor":"^5.4.1","@istanbuljs/nyc-config-typescript":"^1.0.1","@next/bundle-analyzer":"^9.4.4","@next/plugin-storybook":"^11.1.0","@storybook/addon-a11y":"^6.3.7","@storybook/addon-actions":"^6.3.7","@storybook/addon-backgrounds":"^6.3.7","@storybook/addon-controls":"^6.3.7","@storybook/addon-docs":"^6.3.7","@storybook/addon-essentials":"^6.3.7","@storybook/addon-links":"^6.3.7","@storybook/addons":"^6.3.7","@storybook/react":"^6.3.7","@testing-library/cypress":"^6.0.0","@testing-library/jest-dom":"^5.9.0","@testing-library/react":"^10.2.0","@testing-library/react-hooks":"^3.3.0","@types/jest":"^25.2.3","auto-changelog":"^2.2.1","chromatic":"^5.9.2","cypress":"4.8.0","dotenv-cli":"^4.0.0","eslint-config-next":"^11.1.0","eslint-plugin-cypress":"2.11.1","jest":"^26.0.1","jest-transformer-mdx":"^2.2.0","nyc":"^15.1.0","serve":"^11.3.2","shelljs":"^0.8.4","start-server-and-test":"^1.11.0","storybook-addon-next-router":"^3.0.7"}}' - ); +"use strict"; +module.exports = require("buffer"); - /***/ - }, +/***/ }), - /***/ 2357: /***/ (module) => { - "use strict"; - module.exports = require("assert"); +/***/ 6417: +/***/ ((module) => { - /***/ - }, +"use strict"; +module.exports = require("crypto"); - /***/ 4293: /***/ (module) => { - "use strict"; - module.exports = require("buffer"); +/***/ }), - /***/ - }, +/***/ 881: +/***/ ((module) => { - /***/ 6417: /***/ (module) => { - "use strict"; - module.exports = require("crypto"); +"use strict"; +module.exports = require("dns"); - /***/ - }, +/***/ }), - /***/ 881: /***/ (module) => { - "use strict"; - module.exports = require("dns"); +/***/ 8614: +/***/ ((module) => { - /***/ - }, +"use strict"; +module.exports = require("events"); - /***/ 8614: /***/ (module) => { - "use strict"; - module.exports = require("events"); +/***/ }), - /***/ - }, +/***/ 5747: +/***/ ((module) => { - /***/ 5747: /***/ (module) => { - "use strict"; - module.exports = require("fs"); +"use strict"; +module.exports = require("fs"); - /***/ - }, +/***/ }), - /***/ 8605: /***/ (module) => { - "use strict"; - module.exports = require("http"); +/***/ 8605: +/***/ ((module) => { - /***/ - }, +"use strict"; +module.exports = require("http"); - /***/ 2282: /***/ (module) => { - "use strict"; - module.exports = require("module"); +/***/ }), - /***/ - }, +/***/ 1631: +/***/ ((module) => { - /***/ 1631: /***/ (module) => { - "use strict"; - module.exports = require("net"); +"use strict"; +module.exports = require("net"); - /***/ - }, +/***/ }), - /***/ 2087: /***/ (module) => { - "use strict"; - module.exports = require("os"); +/***/ 2087: +/***/ ((module) => { - /***/ - }, +"use strict"; +module.exports = require("os"); - /***/ 5622: /***/ (module) => { - "use strict"; - module.exports = require("path"); +/***/ }), - /***/ - }, +/***/ 5622: +/***/ ((module) => { - /***/ 1191: /***/ (module) => { - "use strict"; - module.exports = require("querystring"); +"use strict"; +module.exports = require("path"); - /***/ - }, +/***/ }), - /***/ 2413: /***/ (module) => { - "use strict"; - module.exports = require("stream"); +/***/ 4213: +/***/ ((module) => { - /***/ - }, +"use strict"; +module.exports = require("punycode"); - /***/ 4016: /***/ (module) => { - "use strict"; - module.exports = require("tls"); +/***/ }), - /***/ - }, +/***/ 1191: +/***/ ((module) => { - /***/ 3867: /***/ (module) => { - "use strict"; - module.exports = require("tty"); +"use strict"; +module.exports = require("querystring"); - /***/ - }, +/***/ }), - /***/ 8835: /***/ (module) => { - "use strict"; - module.exports = require("url"); +/***/ 2413: +/***/ ((module) => { - /***/ - }, +"use strict"; +module.exports = require("stream"); - /***/ 1669: /***/ (module) => { - "use strict"; - module.exports = require("util"); +/***/ }), - /***/ - }, +/***/ 4016: +/***/ ((module) => { - /***/ 8761: /***/ (module) => { - "use strict"; - module.exports = require("zlib"); +"use strict"; +module.exports = require("tls"); - /***/ - }, +/***/ }), - /******/ - }; - /************************************************************************/ - /******/ // The module cache - /******/ var __webpack_module_cache__ = {}; - /******/ - /******/ // The require function - /******/ function __nccwpck_require__(moduleId) { - /******/ // Check if module is in cache - /******/ var cachedModule = __webpack_module_cache__[moduleId]; - /******/ if (cachedModule !== undefined) { - /******/ return cachedModule.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].call( - module.exports, - module, - module.exports, - __nccwpck_require__ - ); - /******/ threw = false; - /******/ - } finally { - /******/ if (threw) delete __webpack_module_cache__[moduleId]; - /******/ - } - /******/ - /******/ // Return the exports of the module - /******/ return module.exports; - /******/ - } - /******/ - /************************************************************************/ - /******/ /* webpack/runtime/async module */ - /******/ (() => { - /******/ var webpackThen = - typeof Symbol === "function" - ? Symbol("webpack then") - : "__webpack_then__"; - /******/ var webpackExports = - typeof Symbol === "function" - ? Symbol("webpack exports") - : "__webpack_exports__"; - /******/ var completeQueue = (queue) => { - /******/ if (queue) { - /******/ queue.forEach((fn) => fn.r--); - /******/ queue.forEach((fn) => (fn.r-- ? fn.r++ : fn())); - /******/ - } - /******/ - }; - /******/ var completeFunction = (fn) => !--fn.r && fn(); - /******/ var queueFunction = (queue, fn) => - queue ? queue.push(fn) : completeFunction(fn); - /******/ var wrapDeps = (deps) => - deps.map((dep) => { - /******/ if (dep !== null && typeof dep === "object") { - /******/ if (dep[webpackThen]) return dep; - /******/ if (dep.then) { - /******/ var queue = []; - /******/ dep.then((r) => { - /******/ obj[webpackExports] = r; - /******/ completeQueue(queue); - /******/ queue = 0; - /******/ - }); - /******/ var obj = {}; - /******/ obj[webpackThen] = (fn, reject) => ( - queueFunction(queue, fn), dep.catch(reject) - ); - /******/ return obj; - /******/ - } - /******/ - } - /******/ var ret = {}; - /******/ ret[webpackThen] = (fn) => completeFunction(fn); - /******/ ret[webpackExports] = dep; - /******/ return ret; - /******/ - }); - /******/ __nccwpck_require__.a = (module, body, hasAwait) => { - /******/ var queue = hasAwait && []; - /******/ var exports = module.exports; - /******/ var currentDeps; - /******/ var outerResolve; - /******/ var reject; - /******/ var isEvaluating = true; - /******/ var nested = false; - /******/ var whenAll = (deps, onResolve, onReject) => { - /******/ if (nested) return; - /******/ nested = true; - /******/ onResolve.r += deps.length; - /******/ deps.map((dep, i) => dep[webpackThen](onResolve, onReject)); - /******/ nested = false; - /******/ - }; - /******/ var promise = new Promise((resolve, rej) => { - /******/ reject = rej; - /******/ outerResolve = () => ( - resolve(exports), completeQueue(queue), (queue = 0) - ); - /******/ - }); - /******/ promise[webpackExports] = exports; - /******/ promise[webpackThen] = (fn, rejectFn) => { - /******/ if (isEvaluating) { - return completeFunction(fn); - } - /******/ if (currentDeps) whenAll(currentDeps, fn, rejectFn); - /******/ queueFunction(queue, fn); - /******/ promise.catch(rejectFn); - /******/ - }; - /******/ module.exports = promise; - /******/ body((deps) => { - /******/ if (!deps) return outerResolve(); - /******/ currentDeps = wrapDeps(deps); - /******/ var fn, result; - /******/ var promise = new Promise((resolve, reject) => { - /******/ fn = () => - resolve((result = currentDeps.map((d) => d[webpackExports]))); - /******/ fn.r = 0; - /******/ whenAll(currentDeps, fn, reject); - /******/ - }); - /******/ return fn.r ? promise : result; - /******/ - }).then(outerResolve, reject); - /******/ isEvaluating = false; - /******/ - }; - /******/ - })(); - /******/ - /******/ /* webpack/runtime/compat get default export */ - /******/ (() => { - /******/ // getDefaultExport function for compatibility with non-harmony modules - /******/ __nccwpck_require__.n = (module) => { - /******/ var getter = - module && module.__esModule - ? /******/ () => module["default"] - : /******/ () => module; - /******/ __nccwpck_require__.d(getter, { a: getter }); - /******/ return getter; - /******/ - }; - /******/ - })(); - /******/ - /******/ /* webpack/runtime/define property getters */ - /******/ (() => { - /******/ // define getter functions for harmony exports - /******/ __nccwpck_require__.d = (exports, definition) => { - /******/ for (var key in definition) { - /******/ if ( - __nccwpck_require__.o(definition, key) && - !__nccwpck_require__.o(exports, key) - ) { - /******/ Object.defineProperty(exports, key, { - enumerable: true, - get: definition[key], - }); - /******/ - } - /******/ - } - /******/ - }; - /******/ - })(); - /******/ - /******/ /* webpack/runtime/hasOwnProperty shorthand */ - /******/ (() => { - /******/ __nccwpck_require__.o = (obj, prop) => - Object.prototype.hasOwnProperty.call(obj, prop); - /******/ - })(); - /******/ - /******/ /* webpack/runtime/make namespace object */ - /******/ (() => { - /******/ // define __esModule on exports - /******/ __nccwpck_require__.r = (exports) => { - /******/ if (typeof Symbol !== "undefined" && Symbol.toStringTag) { - /******/ Object.defineProperty(exports, Symbol.toStringTag, { - value: "Module", - }); - /******/ - } - /******/ Object.defineProperty(exports, "__esModule", { value: true }); - /******/ - }; - /******/ - })(); - /******/ - /******/ /* webpack/runtime/compat */ - /******/ - /******/ if (typeof __nccwpck_require__ !== "undefined") - __nccwpck_require__.ab = __dirname + "/"; - /******/ - /************************************************************************/ - /******/ - /******/ // startup - /******/ // Load entry module and return exports - /******/ // This entry module used 'module' so it can't be inlined - /******/ var __webpack_exports__ = __nccwpck_require__(1977); - /******/ module.exports = __webpack_exports__; - /******/ - /******/ -})(); +/***/ 3867: +/***/ ((module) => { + +"use strict"; +module.exports = require("tty"); + +/***/ }), + +/***/ 8835: +/***/ ((module) => { + +"use strict"; +module.exports = require("url"); + +/***/ }), + +/***/ 1669: +/***/ ((module) => { + +"use strict"; +module.exports = require("util"); + +/***/ }), + +/***/ 8761: +/***/ ((module) => { + +"use strict"; +module.exports = require("zlib"); + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __nccwpck_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.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].call(module.exports, module, module.exports, __nccwpck_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/async module */ +/******/ (() => { +/******/ var webpackThen = typeof Symbol === "function" ? Symbol("webpack then") : "__webpack_then__"; +/******/ var webpackExports = typeof Symbol === "function" ? Symbol("webpack exports") : "__webpack_exports__"; +/******/ var completeQueue = (queue) => { +/******/ if(queue) { +/******/ queue.forEach((fn) => (fn.r--)); +/******/ queue.forEach((fn) => (fn.r-- ? fn.r++ : fn())); +/******/ } +/******/ } +/******/ var completeFunction = (fn) => (!--fn.r && fn()); +/******/ var queueFunction = (queue, fn) => (queue ? queue.push(fn) : completeFunction(fn)); +/******/ var wrapDeps = (deps) => (deps.map((dep) => { +/******/ if(dep !== null && typeof dep === "object") { +/******/ if(dep[webpackThen]) return dep; +/******/ if(dep.then) { +/******/ var queue = []; +/******/ dep.then((r) => { +/******/ obj[webpackExports] = r; +/******/ completeQueue(queue); +/******/ queue = 0; +/******/ }); +/******/ var obj = {}; +/******/ obj[webpackThen] = (fn, reject) => (queueFunction(queue, fn), dep.catch(reject)); +/******/ return obj; +/******/ } +/******/ } +/******/ var ret = {}; +/******/ ret[webpackThen] = (fn) => (completeFunction(fn)); +/******/ ret[webpackExports] = dep; +/******/ return ret; +/******/ })); +/******/ __nccwpck_require__.a = (module, body, hasAwait) => { +/******/ var queue = hasAwait && []; +/******/ var exports = module.exports; +/******/ var currentDeps; +/******/ var outerResolve; +/******/ var reject; +/******/ var isEvaluating = true; +/******/ var nested = false; +/******/ var whenAll = (deps, onResolve, onReject) => { +/******/ if (nested) return; +/******/ nested = true; +/******/ onResolve.r += deps.length; +/******/ deps.map((dep, i) => (dep[webpackThen](onResolve, onReject))); +/******/ nested = false; +/******/ }; +/******/ var promise = new Promise((resolve, rej) => { +/******/ reject = rej; +/******/ outerResolve = () => (resolve(exports), completeQueue(queue), queue = 0); +/******/ }); +/******/ promise[webpackExports] = exports; +/******/ promise[webpackThen] = (fn, rejectFn) => { +/******/ if (isEvaluating) { return completeFunction(fn); } +/******/ if (currentDeps) whenAll(currentDeps, fn, rejectFn); +/******/ queueFunction(queue, fn); +/******/ promise.catch(rejectFn); +/******/ }; +/******/ module.exports = promise; +/******/ body((deps) => { +/******/ if(!deps) return outerResolve(); +/******/ currentDeps = wrapDeps(deps); +/******/ var fn, result; +/******/ var promise = new Promise((resolve, reject) => { +/******/ fn = () => (resolve(result = currentDeps.map((d) => (d[webpackExports])))); +/******/ fn.r = 0; +/******/ whenAll(currentDeps, fn, reject); +/******/ }); +/******/ return fn.r ? promise : result; +/******/ }).then(outerResolve, reject); +/******/ isEvaluating = false; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/compat get default export */ +/******/ (() => { +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __nccwpck_require__.n = (module) => { +/******/ var getter = module && module.__esModule ? +/******/ () => (module['default']) : +/******/ () => (module); +/******/ __nccwpck_require__.d(getter, { a: getter }); +/******/ return getter; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __nccwpck_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ (() => { +/******/ // define __esModule on exports +/******/ __nccwpck_require__.r = (exports) => { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; +/******/ +/************************************************************************/ +/******/ +/******/ // startup +/******/ // Load entry module and return exports +/******/ // This entry module used 'module' so it can't be inlined +/******/ var __webpack_exports__ = __nccwpck_require__(1977); +/******/ module.exports = __webpack_exports__; +/******/ +/******/ })() +; \ No newline at end of file diff --git a/.vn/scripts/tsconfig.json b/.vn/scripts/tsconfig.json index d2cf5a10..e1d214a8 100644 --- a/.vn/scripts/tsconfig.json +++ b/.vn/scripts/tsconfig.json @@ -1,10 +1,14 @@ { "extends": "../../tsconfig.json", - "include": ["./**/*.tsx", "./**/*.ts"], + "include": [ + "./**/*.tsx", + "./**/*.ts" + ], "exclude": [], "compilerOptions": { - "noEmit": false, - "outDir": "./", - "moduleResolution": "node" + "jsx": "react", // otherwise it fails to build server-side components like mails or components in a schema + "noEmit": false, + "outDir": "./", + "moduleResolution": "node" } -} +} \ No newline at end of file diff --git a/yarn.lock b/yarn.lock index 6589f521..1b11fd27 100644 --- a/yarn.lock +++ b/yarn.lock @@ -27,9 +27,9 @@ tunnel "0.0.6" "@apollo/client@^3.2.0": - version "3.5.5" - resolved "https://registry.yarnpkg.com/@apollo/client/-/client-3.5.5.tgz#ce331403ee5f099e595430890f9b510c8435c932" - integrity sha512-EiQstc8VjeqosS2h21bwY9fhL3MCRRmACtRrRh2KYpp9vkDyx5pUfMnN3swgiBVYw1twdXg9jHmyZa1gZlvlog== + version "3.5.6" + resolved "https://registry.yarnpkg.com/@apollo/client/-/client-3.5.6.tgz#911929df073280689efd98e5603047b79e0c39a2" + integrity sha512-XHoouuEJ4L37mtfftcHHO1caCRrKKAofAwqRoq28UQIPMJk+e7n3X9OtRRNXKk/9tmhNkwelSary+EilfPwI7A== dependencies: "@graphql-typed-document-node/core" "^3.0.0" "@wry/context" "^0.6.0" @@ -40,7 +40,7 @@ optimism "^0.16.1" prop-types "^15.7.2" symbol-observable "^4.0.0" - ts-invariant "^0.9.0" + ts-invariant "^0.9.4" tslib "^2.3.0" zen-observable-ts "^1.2.0" @@ -163,7 +163,7 @@ semver "^5.4.1" source-map "^0.5.0" -"@babel/core@^7.1.0", "@babel/core@^7.12.3", "@babel/core@^7.7.5": +"@babel/core@^7.1.0", "@babel/core@^7.10.2", "@babel/core@^7.12.10", "@babel/core@^7.12.3", "@babel/core@^7.16.0", "@babel/core@^7.7.5": version "7.16.5" resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.16.5.tgz#924aa9e1ae56e1e55f7184c8bf073a50d8677f5c" integrity sha512-wUcenlLzuWMZ9Zt8S0KmFwGlH6QKRh3vsm/dhDA3CHkiTA45YuG1XkHRcNRl73EFPXDp/d5kVOU0/y7x2w6OaQ== @@ -184,37 +184,7 @@ semver "^6.3.0" source-map "^0.5.0" -"@babel/core@^7.10.2", "@babel/core@^7.12.10", "@babel/core@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.16.0.tgz#c4ff44046f5fe310525cc9eb4ef5147f0c5374d4" - integrity sha512-mYZEvshBRHGsIAiyH5PzCFTCfbWfoYbO/jcSdXQSUQu1/pW0xDZAUP7KEc32heqWTAfAHhV9j1vH8Sav7l+JNQ== - dependencies: - "@babel/code-frame" "^7.16.0" - "@babel/generator" "^7.16.0" - "@babel/helper-compilation-targets" "^7.16.0" - "@babel/helper-module-transforms" "^7.16.0" - "@babel/helpers" "^7.16.0" - "@babel/parser" "^7.16.0" - "@babel/template" "^7.16.0" - "@babel/traverse" "^7.16.0" - "@babel/types" "^7.16.0" - convert-source-map "^1.7.0" - debug "^4.1.0" - gensync "^1.0.0-beta.2" - json5 "^2.1.2" - semver "^6.3.0" - source-map "^0.5.0" - -"@babel/generator@^7.12.11", "@babel/generator@^7.12.5", "@babel/generator@^7.9.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.16.0.tgz#d40f3d1d5075e62d3500bccb67f3daa8a95265b2" - integrity sha512-RR8hUCfRQn9j9RPKEVXo9LiwoxLPYn6hNZlvUOR8tSnaxlD0p0+la00ZP9/SnRt6HchKr+X0fO2r8vrETiJGew== - dependencies: - "@babel/types" "^7.16.0" - jsesc "^2.5.1" - source-map "^0.5.0" - -"@babel/generator@^7.16.0", "@babel/generator@^7.16.5": +"@babel/generator@^7.12.11", "@babel/generator@^7.12.5", "@babel/generator@^7.16.5", "@babel/generator@^7.9.0": version "7.16.5" resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.16.5.tgz#26e1192eb8f78e0a3acaf3eede3c6fc96d22bedf" integrity sha512-kIvCdjZqcdKqoDbVVdt5R99icaRtrtYhYK/xux5qiWCBmfdvEYMFZ68QCrpE5cbFM1JsuArUNs1ZkuKtTtUcZA== @@ -230,15 +200,15 @@ dependencies: "@babel/types" "^7.16.0" -"@babel/helper-builder-binary-assignment-operator-visitor@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.16.0.tgz#f1a686b92da794020c26582eb852e9accd0d7882" - integrity sha512-9KuleLT0e77wFUku6TUkqZzCEymBdtuQQ27MhEKzf9UOOJu3cYj98kyaDAzxpC7lV6DGiZFuC8XqDsq8/Kl6aQ== +"@babel/helper-builder-binary-assignment-operator-visitor@^7.16.5": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.16.5.tgz#a8429d064dce8207194b8bf05a70a9ea828746af" + integrity sha512-3JEA9G5dmmnIWdzaT9d0NmFRgYnWUThLsDaL7982H0XqqWr56lRrsmwheXFMjR+TMl7QMBb6mzy9kvgr1lRLUA== dependencies: "@babel/helper-explode-assignable-expression" "^7.16.0" "@babel/types" "^7.16.0" -"@babel/helper-compilation-targets@^7.13.0", "@babel/helper-compilation-targets@^7.16.0", "@babel/helper-compilation-targets@^7.16.3", "@babel/helper-compilation-targets@^7.8.7": +"@babel/helper-compilation-targets@^7.13.0", "@babel/helper-compilation-targets@^7.16.3", "@babel/helper-compilation-targets@^7.8.7": version "7.16.3" resolved "https://registry.yarnpkg.com/@babel/helper-compilation-targets/-/helper-compilation-targets-7.16.3.tgz#5b480cd13f68363df6ec4dc8ac8e2da11363cbf0" integrity sha512-vKsoSQAyBmxS35JUOOt+07cLc6Nk/2ljLIHwmq2/NM6hdioUaqEXq/S+nXvbvXbZkNDlWOymPanJGOc4CBjSJA== @@ -248,16 +218,17 @@ browserslist "^4.17.5" semver "^6.3.0" -"@babel/helper-create-class-features-plugin@^7.16.0", "@babel/helper-create-class-features-plugin@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.16.0.tgz#090d4d166b342a03a9fec37ef4fd5aeb9c7c6a4b" - integrity sha512-XLwWvqEaq19zFlF5PTgOod4bUA+XbkR4WLQBct1bkzmxJGB0ZEJaoKF4c8cgH9oBtCDuYJ8BP5NB9uFiEgO5QA== +"@babel/helper-create-class-features-plugin@^7.16.0", "@babel/helper-create-class-features-plugin@^7.16.5", "@babel/helper-create-class-features-plugin@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.16.5.tgz#5d1bcd096792c1ebec6249eebc6358eec55d0cad" + integrity sha512-NEohnYA7mkB8L5JhU7BLwcBdU3j83IziR9aseMueWGeAjblbul3zzb8UvJ3a1zuBiqCMObzCJHFqKIQE6hTVmg== dependencies: "@babel/helper-annotate-as-pure" "^7.16.0" + "@babel/helper-environment-visitor" "^7.16.5" "@babel/helper-function-name" "^7.16.0" - "@babel/helper-member-expression-to-functions" "^7.16.0" + "@babel/helper-member-expression-to-functions" "^7.16.5" "@babel/helper-optimise-call-expression" "^7.16.0" - "@babel/helper-replace-supers" "^7.16.0" + "@babel/helper-replace-supers" "^7.16.5" "@babel/helper-split-export-declaration" "^7.16.0" "@babel/helper-create-regexp-features-plugin@^7.16.0": @@ -333,7 +304,7 @@ dependencies: "@babel/types" "^7.16.0" -"@babel/helper-member-expression-to-functions@^7.16.0", "@babel/helper-member-expression-to-functions@^7.16.5": +"@babel/helper-member-expression-to-functions@^7.16.5": version "7.16.5" resolved "https://registry.yarnpkg.com/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.16.5.tgz#1bc9f7e87354e86f8879c67b316cb03d3dc2caab" integrity sha512-7fecSXq7ZrLE+TWshbGT+HyCLkxloWNhTbU2QM1NTI/tDqyf0oZiMcEfYtDuUDCo528EOlt39G1rftea4bRZIw== @@ -347,21 +318,7 @@ dependencies: "@babel/types" "^7.16.0" -"@babel/helper-module-transforms@^7.12.1", "@babel/helper-module-transforms@^7.9.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/helper-module-transforms/-/helper-module-transforms-7.16.0.tgz#1c82a8dd4cb34577502ebd2909699b194c3e9bb5" - integrity sha512-My4cr9ATcaBbmaEa8M0dZNA74cfI6gitvUAskgDtAFmAqyFKDSHQo5YstxPbN+lzHl2D9l/YOEFqb2mtUh4gfA== - dependencies: - "@babel/helper-module-imports" "^7.16.0" - "@babel/helper-replace-supers" "^7.16.0" - "@babel/helper-simple-access" "^7.16.0" - "@babel/helper-split-export-declaration" "^7.16.0" - "@babel/helper-validator-identifier" "^7.15.7" - "@babel/template" "^7.16.0" - "@babel/traverse" "^7.16.0" - "@babel/types" "^7.16.0" - -"@babel/helper-module-transforms@^7.16.0", "@babel/helper-module-transforms@^7.16.5": +"@babel/helper-module-transforms@^7.12.1", "@babel/helper-module-transforms@^7.16.5", "@babel/helper-module-transforms@^7.9.0": version "7.16.5" resolved "https://registry.yarnpkg.com/@babel/helper-module-transforms/-/helper-module-transforms-7.16.5.tgz#530ebf6ea87b500f60840578515adda2af470a29" integrity sha512-CkvMxgV4ZyyioElFwcuWnDCcNIeyqTkCm9BxXZi73RR1ozqlpboqsbGUNvRTflgZtFbbJ1v5Emvm+lkjMYY/LQ== @@ -387,26 +344,21 @@ resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.10.4.tgz#2f75a831269d4f677de49986dff59927533cf375" integrity sha512-O4KCvQA6lLiMU9l2eawBPMf1xPP8xPfB3iEQw150hOVTqj/rfXz0ThTb4HEzqQfs2Bmo5Ay8BzxfzVtBrr9dVg== -"@babel/helper-plugin-utils@^7.0.0", "@babel/helper-plugin-utils@^7.10.4", "@babel/helper-plugin-utils@^7.12.13", "@babel/helper-plugin-utils@^7.14.5", "@babel/helper-plugin-utils@^7.8.0": +"@babel/helper-plugin-utils@^7.0.0", "@babel/helper-plugin-utils@^7.10.4", "@babel/helper-plugin-utils@^7.12.13", "@babel/helper-plugin-utils@^7.13.0", "@babel/helper-plugin-utils@^7.14.5", "@babel/helper-plugin-utils@^7.16.5", "@babel/helper-plugin-utils@^7.8.0", "@babel/helper-plugin-utils@^7.8.3": version "7.16.5" resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.16.5.tgz#afe37a45f39fce44a3d50a7958129ea5b1a5c074" integrity sha512-59KHWHXxVA9K4HNF4sbHCf+eJeFe0Te/ZFGqBT4OjXhrwvA04sGfaEGsVTdsjoszq0YTP49RC9UKe5g8uN2RwQ== -"@babel/helper-plugin-utils@^7.13.0", "@babel/helper-plugin-utils@^7.8.3": - version "7.14.5" - resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.14.5.tgz#5ac822ce97eec46741ab70a517971e443a70c5a9" - integrity sha512-/37qQCE3K0vvZKwoK4XU/irIJQdIfCJuhU5eKnNxpFDsOkgFaUAwbv+RYw6eYgsC0E4hS7r5KqGULUogqui0fQ== - -"@babel/helper-remap-async-to-generator@^7.16.0", "@babel/helper-remap-async-to-generator@^7.16.4": - version "7.16.4" - resolved "https://registry.yarnpkg.com/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.16.4.tgz#5d7902f61349ff6b963e07f06a389ce139fbfe6e" - integrity sha512-vGERmmhR+s7eH5Y/cp8PCVzj4XEjerq8jooMfxFdA5xVtAk9Sh4AQsrWgiErUEBjtGrBtOFKDUcWQFW4/dFwMA== +"@babel/helper-remap-async-to-generator@^7.16.5": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.16.5.tgz#e706646dc4018942acb4b29f7e185bc246d65ac3" + integrity sha512-X+aAJldyxrOmN9v3FKp+Hu1NO69VWgYgDGq6YDykwRPzxs5f2N+X988CBXS7EQahDU+Vpet5QYMqLk+nsp+Qxw== dependencies: "@babel/helper-annotate-as-pure" "^7.16.0" - "@babel/helper-wrap-function" "^7.16.0" + "@babel/helper-wrap-function" "^7.16.5" "@babel/types" "^7.16.0" -"@babel/helper-replace-supers@^7.16.0": +"@babel/helper-replace-supers@^7.16.5": version "7.16.5" resolved "https://registry.yarnpkg.com/@babel/helper-replace-supers/-/helper-replace-supers-7.16.5.tgz#96d3988bd0ab0a2d22c88c6198c3d3234ca25326" integrity sha512-ao3seGVa/FZCMCCNDuBcqnBFSbdr8N2EW35mzojx3TwfIbdPmNK+JV6+2d5bR0Z71W5ocLnQp9en/cTF7pBJiQ== @@ -448,26 +400,17 @@ resolved "https://registry.yarnpkg.com/@babel/helper-validator-option/-/helper-validator-option-7.14.5.tgz#6e72a1fff18d5dfcb878e1e62f1a021c4b72d5a3" integrity sha512-OX8D5eeX4XwcroVW45NMvoYaIuFI+GQpA2a8Gi+X/U/cDUIRsV37qQfF905F0htTRCREQIB4KqPeaveRJUl3Ow== -"@babel/helper-wrap-function@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/helper-wrap-function/-/helper-wrap-function-7.16.0.tgz#b3cf318afce774dfe75b86767cd6d68f3482e57c" - integrity sha512-VVMGzYY3vkWgCJML+qVLvGIam902mJW0FvT7Avj1zEe0Gn7D93aWdLblYARTxEw+6DhZmtzhBM2zv0ekE5zg1g== +"@babel/helper-wrap-function@^7.16.5": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/helper-wrap-function/-/helper-wrap-function-7.16.5.tgz#0158fca6f6d0889c3fee8a6ed6e5e07b9b54e41f" + integrity sha512-2J2pmLBqUqVdJw78U0KPNdeE2qeuIyKoG4mKV7wAq3mc4jJG282UgjZw4ZYDnqiWQuS3Y3IYdF/AQ6CpyBV3VA== dependencies: "@babel/helper-function-name" "^7.16.0" "@babel/template" "^7.16.0" - "@babel/traverse" "^7.16.0" - "@babel/types" "^7.16.0" - -"@babel/helpers@^7.12.5", "@babel/helpers@^7.9.0": - version "7.16.3" - resolved "https://registry.yarnpkg.com/@babel/helpers/-/helpers-7.16.3.tgz#27fc64f40b996e7074dc73128c3e5c3e7f55c43c" - integrity sha512-Xn8IhDlBPhvYTvgewPKawhADichOsbkZuzN7qz2BusOM0brChsyXMDJvldWaYMMUNiCQdQzNEioXTp3sC8Nt8w== - dependencies: - "@babel/template" "^7.16.0" - "@babel/traverse" "^7.16.3" + "@babel/traverse" "^7.16.5" "@babel/types" "^7.16.0" -"@babel/helpers@^7.16.0", "@babel/helpers@^7.16.5": +"@babel/helpers@^7.12.5", "@babel/helpers@^7.16.5", "@babel/helpers@^7.9.0": version "7.16.5" resolved "https://registry.yarnpkg.com/@babel/helpers/-/helpers-7.16.5.tgz#29a052d4b827846dd76ece16f565b9634c554ebd" integrity sha512-TLgi6Lh71vvMZGEkFuIxzaPsyeYCHQ5jJOOX1f0xXn0uciFuE8cEk0wyBquMcCxBXZ5BJhE2aUB7pnWTD150Tw== @@ -485,16 +428,11 @@ chalk "^2.0.0" js-tokens "^4.0.0" -"@babel/parser@^7.1.0", "@babel/parser@^7.14.7", "@babel/parser@^7.16.0", "@babel/parser@^7.16.3", "@babel/parser@^7.16.5": +"@babel/parser@^7.1.0", "@babel/parser@^7.12.11", "@babel/parser@^7.12.7", "@babel/parser@^7.14.7", "@babel/parser@^7.16.0", "@babel/parser@^7.16.5", "@babel/parser@^7.9.0": version "7.16.6" resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.16.6.tgz#8f194828193e8fa79166f34a4b4e52f3e769a314" integrity sha512-Gr86ujcNuPDnNOY8mi383Hvi8IYrJVJYuf3XcuBM/Dgd+bINn/7tHqsj+tKkoreMbmGsFLsltI/JJd8fOFWGDQ== -"@babel/parser@^7.12.11", "@babel/parser@^7.12.7", "@babel/parser@^7.9.0": - version "7.16.4" - resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.16.4.tgz#d5f92f57cf2c74ffe9b37981c0e72fee7311372e" - integrity sha512-6V0qdPUaiVHH3RtZeLIsc+6pDhbYzHR8ogA8w+f+Wc77DuXto19g2QUwveINoS34Uw+W8/hQDGJCx+i4n7xcng== - "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression@^7.16.2": version "7.16.2" resolved "https://registry.yarnpkg.com/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression/-/plugin-bugfix-safari-id-destructuring-collision-in-function-expression-7.16.2.tgz#2977fca9b212db153c195674e57cfab807733183" @@ -511,13 +449,13 @@ "@babel/helper-skip-transparent-expression-wrappers" "^7.16.0" "@babel/plugin-proposal-optional-chaining" "^7.16.0" -"@babel/plugin-proposal-async-generator-functions@^7.16.4", "@babel/plugin-proposal-async-generator-functions@^7.8.3": - version "7.16.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.16.4.tgz#e606eb6015fec6fa5978c940f315eae4e300b081" - integrity sha512-/CUekqaAaZCQHleSK/9HajvcD/zdnJiKRiuUFq8ITE+0HsPzquf53cpFiqAwl/UfmJbR6n5uGPQSPdrmKOvHHg== +"@babel/plugin-proposal-async-generator-functions@^7.16.5", "@babel/plugin-proposal-async-generator-functions@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.16.5.tgz#fd3bd7e0d98404a3d4cbca15a72d533f8c9a2f67" + integrity sha512-C/FX+3HNLV6sz7AqbTQqEo1L9/kfrKjxcVtgyBCmvIgOjvuBVUWooDoi7trsLxOzCEo5FccjRvKHkfDsJFZlfA== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" - "@babel/helper-remap-async-to-generator" "^7.16.4" + "@babel/helper-plugin-utils" "^7.16.5" + "@babel/helper-remap-async-to-generator" "^7.16.5" "@babel/plugin-syntax-async-generators" "^7.8.4" "@babel/plugin-proposal-class-properties@7.8.3": @@ -528,21 +466,21 @@ "@babel/helper-create-class-features-plugin" "^7.8.3" "@babel/helper-plugin-utils" "^7.8.3" -"@babel/plugin-proposal-class-properties@^7.12.1", "@babel/plugin-proposal-class-properties@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-class-properties/-/plugin-proposal-class-properties-7.16.0.tgz#c029618267ddebc7280fa286e0f8ca2a278a2d1a" - integrity sha512-mCF3HcuZSY9Fcx56Lbn+CGdT44ioBMMvjNVldpKtj8tpniETdLjnxdHI1+sDWXIM1nNt+EanJOZ3IG9lzVjs7A== +"@babel/plugin-proposal-class-properties@^7.12.1", "@babel/plugin-proposal-class-properties@^7.16.0", "@babel/plugin-proposal-class-properties@^7.16.5": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-class-properties/-/plugin-proposal-class-properties-7.16.5.tgz#3269f44b89122110f6339806e05d43d84106468a" + integrity sha512-pJD3HjgRv83s5dv1sTnDbZOaTjghKEz8KUn1Kbh2eAIRhGuyQ1XSeI4xVXU3UlIEVA3DAyIdxqT1eRn7Wcn55A== dependencies: - "@babel/helper-create-class-features-plugin" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-create-class-features-plugin" "^7.16.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-proposal-class-static-block@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-class-static-block/-/plugin-proposal-class-static-block-7.16.0.tgz#5296942c564d8144c83eea347d0aa8a0b89170e7" - integrity sha512-mAy3sdcY9sKAkf3lQbDiv3olOfiLqI51c9DR9b19uMoR2Z6r5pmGl7dfNFqEvqOyqbf1ta4lknK4gc5PJn3mfA== +"@babel/plugin-proposal-class-static-block@^7.16.5": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-class-static-block/-/plugin-proposal-class-static-block-7.16.5.tgz#df58ab015a7d3b0963aafc8f20792dcd834952a9" + integrity sha512-EEFzuLZcm/rNJ8Q5krK+FRKdVkd6FjfzT9tuSZql9sQn64K0hHA2KLJ0DqVot9/iV6+SsuadC5yI39zWnm+nmQ== dependencies: - "@babel/helper-create-class-features-plugin" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-create-class-features-plugin" "^7.16.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-syntax-class-static-block" "^7.14.5" "@babel/plugin-proposal-decorators@7.8.3": @@ -555,52 +493,52 @@ "@babel/plugin-syntax-decorators" "^7.8.3" "@babel/plugin-proposal-decorators@^7.12.12": - version "7.16.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-decorators/-/plugin-proposal-decorators-7.16.4.tgz#9b35ce0716425a93b978e79099e5f7ba217c1364" - integrity sha512-RESBNX16eNqnBeEVR5sCJpnW0mHiNLNNvGA8PrRuK/4ZJ4TO+6bHleRUuGQYDERVySOKtOhSya/C4MIhwAMAgg== + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-decorators/-/plugin-proposal-decorators-7.16.5.tgz#4617420d3685078dfab8f68f859dca1448bbb3c7" + integrity sha512-XAiZll5oCdp2Dd2RbXA3LVPlFyIRhhcQy+G34p9ePpl6mjFkbqHAYHovyw2j5mqUrlBf0/+MtOIJ3JGYtz8qaw== dependencies: - "@babel/helper-create-class-features-plugin" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" - "@babel/plugin-syntax-decorators" "^7.16.0" + "@babel/helper-create-class-features-plugin" "^7.16.5" + "@babel/helper-plugin-utils" "^7.16.5" + "@babel/plugin-syntax-decorators" "^7.16.5" -"@babel/plugin-proposal-dynamic-import@^7.16.0", "@babel/plugin-proposal-dynamic-import@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-dynamic-import/-/plugin-proposal-dynamic-import-7.16.0.tgz#783eca61d50526202f9b296095453977e88659f1" - integrity sha512-QGSA6ExWk95jFQgwz5GQ2Dr95cf7eI7TKutIXXTb7B1gCLTCz5hTjFTQGfLFBBiC5WSNi7udNwWsqbbMh1c4yQ== +"@babel/plugin-proposal-dynamic-import@^7.16.5", "@babel/plugin-proposal-dynamic-import@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-dynamic-import/-/plugin-proposal-dynamic-import-7.16.5.tgz#2e0d19d5702db4dcb9bc846200ca02f2e9d60e9e" + integrity sha512-P05/SJZTTvHz79LNYTF8ff5xXge0kk5sIIWAypcWgX4BTRUgyHc8wRxJ/Hk+mU0KXldgOOslKaeqnhthcDJCJQ== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-syntax-dynamic-import" "^7.8.3" "@babel/plugin-proposal-export-default-from@^7.12.1": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-export-default-from/-/plugin-proposal-export-default-from-7.16.0.tgz#f8a07008ffcb0d3de4945f3eb52022ecc28b56ad" - integrity sha512-kFAhaIbh5qbBwETRNa/cgGmPJ/BicXhIyrZhAkyYhf/Z9LXCTRGO1mvUwczto0Hl1q4YtzP9cRtTKT4wujm38Q== + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-export-default-from/-/plugin-proposal-export-default-from-7.16.5.tgz#8771249ffc9c06c9eb27342cf5c072a83c6d3811" + integrity sha512-pU4aCS+AzGjDD/6LnwSmeelmtqfMSjzQxs7+/AS673bYsshK1XZm9eth6OkgivVscQM8XdkVYhrb6tPFVTBVHA== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" - "@babel/plugin-syntax-export-default-from" "^7.16.0" + "@babel/helper-plugin-utils" "^7.16.5" + "@babel/plugin-syntax-export-default-from" "^7.16.5" -"@babel/plugin-proposal-export-namespace-from@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-export-namespace-from/-/plugin-proposal-export-namespace-from-7.16.0.tgz#9c01dee40b9d6b847b656aaf4a3976a71740f222" - integrity sha512-CjI4nxM/D+5wCnhD11MHB1AwRSAYeDT+h8gCdcVJZ/OK7+wRzFsf7PFPWVpVpNRkHMmMkQWAHpTq+15IXQ1diA== +"@babel/plugin-proposal-export-namespace-from@^7.16.5": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-export-namespace-from/-/plugin-proposal-export-namespace-from-7.16.5.tgz#3b4dd28378d1da2fea33e97b9f25d1c2f5bf1ac9" + integrity sha512-i+sltzEShH1vsVydvNaTRsgvq2vZsfyrd7K7vPLUU/KgS0D5yZMe6uipM0+izminnkKrEfdUnz7CxMRb6oHZWw== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-syntax-export-namespace-from" "^7.8.3" -"@babel/plugin-proposal-json-strings@^7.16.0", "@babel/plugin-proposal-json-strings@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-json-strings/-/plugin-proposal-json-strings-7.16.0.tgz#cae35a95ed1d2a7fa29c4dc41540b84a72e9ab25" - integrity sha512-kouIPuiv8mSi5JkEhzApg5Gn6hFyKPnlkO0a9YSzqRurH8wYzSlf6RJdzluAsbqecdW5pBvDJDfyDIUR/vLxvg== +"@babel/plugin-proposal-json-strings@^7.16.5", "@babel/plugin-proposal-json-strings@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-json-strings/-/plugin-proposal-json-strings-7.16.5.tgz#1e726930fca139caab6b084d232a9270d9d16f9c" + integrity sha512-QQJueTFa0y9E4qHANqIvMsuxM/qcLQmKttBACtPCQzGUEizsXDACGonlPiSwynHfOa3vNw0FPMVvQzbuXwh4SQ== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-syntax-json-strings" "^7.8.3" -"@babel/plugin-proposal-logical-assignment-operators@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-logical-assignment-operators/-/plugin-proposal-logical-assignment-operators-7.16.0.tgz#a711b8ceb3ffddd3ef88d3a49e86dbd3cc7db3fd" - integrity sha512-pbW0fE30sVTYXXm9lpVQQ/Vc+iTeQKiXlaNRZPPN2A2VdlWyAtsUrsQ3xydSlDW00TFMK7a8m3cDTkBF5WnV3Q== +"@babel/plugin-proposal-logical-assignment-operators@^7.16.5": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-logical-assignment-operators/-/plugin-proposal-logical-assignment-operators-7.16.5.tgz#df1f2e4b5a0ec07abf061d2c18e53abc237d3ef5" + integrity sha512-xqibl7ISO2vjuQM+MzR3rkd0zfNWltk7n9QhaD8ghMmMceVguYrNDt7MikRyj4J4v3QehpnrU8RYLnC7z/gZLA== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-syntax-logical-assignment-operators" "^7.10.4" "@babel/plugin-proposal-nullish-coalescing-operator@7.8.3": @@ -611,12 +549,12 @@ "@babel/helper-plugin-utils" "^7.8.3" "@babel/plugin-syntax-nullish-coalescing-operator" "^7.8.0" -"@babel/plugin-proposal-nullish-coalescing-operator@^7.12.1", "@babel/plugin-proposal-nullish-coalescing-operator@^7.16.0", "@babel/plugin-proposal-nullish-coalescing-operator@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-nullish-coalescing-operator/-/plugin-proposal-nullish-coalescing-operator-7.16.0.tgz#44e1cce08fe2427482cf446a91bb451528ed0596" - integrity sha512-3bnHA8CAFm7cG93v8loghDYyQ8r97Qydf63BeYiGgYbjKKB/XP53W15wfRC7dvKfoiJ34f6Rbyyx2btExc8XsQ== +"@babel/plugin-proposal-nullish-coalescing-operator@^7.12.1", "@babel/plugin-proposal-nullish-coalescing-operator@^7.16.5", "@babel/plugin-proposal-nullish-coalescing-operator@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-nullish-coalescing-operator/-/plugin-proposal-nullish-coalescing-operator-7.16.5.tgz#652555bfeeeee2d2104058c6225dc6f75e2d0f07" + integrity sha512-YwMsTp/oOviSBhrjwi0vzCUycseCYwoXnLiXIL3YNjHSMBHicGTz7GjVU/IGgz4DtOEXBdCNG72pvCX22ehfqg== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-syntax-nullish-coalescing-operator" "^7.8.3" "@babel/plugin-proposal-numeric-separator@7.8.3": @@ -627,12 +565,12 @@ "@babel/helper-plugin-utils" "^7.8.3" "@babel/plugin-syntax-numeric-separator" "^7.8.3" -"@babel/plugin-proposal-numeric-separator@^7.16.0", "@babel/plugin-proposal-numeric-separator@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-numeric-separator/-/plugin-proposal-numeric-separator-7.16.0.tgz#5d418e4fbbf8b9b7d03125d3a52730433a373734" - integrity sha512-FAhE2I6mjispy+vwwd6xWPyEx3NYFS13pikDBWUAFGZvq6POGs5eNchw8+1CYoEgBl9n11I3NkzD7ghn25PQ9Q== +"@babel/plugin-proposal-numeric-separator@^7.16.5", "@babel/plugin-proposal-numeric-separator@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-numeric-separator/-/plugin-proposal-numeric-separator-7.16.5.tgz#edcb6379b6cf4570be64c45965d8da7a2debf039" + integrity sha512-DvB9l/TcsCRvsIV9v4jxR/jVP45cslTVC0PMVHvaJhhNuhn2Y1SOhCSFlPK777qLB5wb8rVDaNoqMTyOqtY5Iw== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-syntax-numeric-separator" "^7.10.4" "@babel/plugin-proposal-object-rest-spread@7.12.1": @@ -644,23 +582,23 @@ "@babel/plugin-syntax-object-rest-spread" "^7.8.0" "@babel/plugin-transform-parameters" "^7.12.1" -"@babel/plugin-proposal-object-rest-spread@^7.12.1", "@babel/plugin-proposal-object-rest-spread@^7.16.0", "@babel/plugin-proposal-object-rest-spread@^7.9.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.16.0.tgz#5fb32f6d924d6e6712810362a60e12a2609872e6" - integrity sha512-LU/+jp89efe5HuWJLmMmFG0+xbz+I2rSI7iLc1AlaeSMDMOGzWlc5yJrMN1d04osXN4sSfpo4O+azkBNBes0jg== +"@babel/plugin-proposal-object-rest-spread@^7.12.1", "@babel/plugin-proposal-object-rest-spread@^7.16.0", "@babel/plugin-proposal-object-rest-spread@^7.16.5", "@babel/plugin-proposal-object-rest-spread@^7.9.0": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.16.5.tgz#f30f80dacf7bc1404bf67f99c8d9c01665e830ad" + integrity sha512-UEd6KpChoyPhCoE840KRHOlGhEZFutdPDMGj+0I56yuTTOaT51GzmnEl/0uT41fB/vD2nT+Pci2KjezyE3HmUw== dependencies: - "@babel/compat-data" "^7.16.0" - "@babel/helper-compilation-targets" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/compat-data" "^7.16.4" + "@babel/helper-compilation-targets" "^7.16.3" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-syntax-object-rest-spread" "^7.8.3" - "@babel/plugin-transform-parameters" "^7.16.0" + "@babel/plugin-transform-parameters" "^7.16.5" -"@babel/plugin-proposal-optional-catch-binding@^7.16.0", "@babel/plugin-proposal-optional-catch-binding@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-optional-catch-binding/-/plugin-proposal-optional-catch-binding-7.16.0.tgz#5910085811ab4c28b00d6ebffa4ab0274d1e5f16" - integrity sha512-kicDo0A/5J0nrsCPbn89mTG3Bm4XgYi0CZtvex9Oyw7gGZE3HXGD0zpQNH+mo+tEfbo8wbmMvJftOwpmPy7aVw== +"@babel/plugin-proposal-optional-catch-binding@^7.16.5", "@babel/plugin-proposal-optional-catch-binding@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-optional-catch-binding/-/plugin-proposal-optional-catch-binding-7.16.5.tgz#1a5405765cf589a11a33a1fd75b2baef7d48b74e" + integrity sha512-ihCMxY1Iljmx4bWy/PIMJGXN4NS4oUj1MKynwO07kiKms23pNvIn1DMB92DNB2R0EA882sw0VXIelYGdtF7xEQ== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-syntax-optional-catch-binding" "^7.8.3" "@babel/plugin-proposal-optional-chaining@7.9.0": @@ -671,40 +609,40 @@ "@babel/helper-plugin-utils" "^7.8.3" "@babel/plugin-syntax-optional-chaining" "^7.8.0" -"@babel/plugin-proposal-optional-chaining@^7.12.7", "@babel/plugin-proposal-optional-chaining@^7.16.0", "@babel/plugin-proposal-optional-chaining@^7.9.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-optional-chaining/-/plugin-proposal-optional-chaining-7.16.0.tgz#56dbc3970825683608e9efb55ea82c2a2d6c8dc0" - integrity sha512-Y4rFpkZODfHrVo70Uaj6cC1JJOt3Pp0MdWSwIKtb8z1/lsjl9AmnB7ErRFV+QNGIfcY1Eruc2UMx5KaRnXjMyg== +"@babel/plugin-proposal-optional-chaining@^7.12.7", "@babel/plugin-proposal-optional-chaining@^7.16.0", "@babel/plugin-proposal-optional-chaining@^7.16.5", "@babel/plugin-proposal-optional-chaining@^7.9.0": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-optional-chaining/-/plugin-proposal-optional-chaining-7.16.5.tgz#a5fa61056194d5059366c0009cb9a9e66ed75c1f" + integrity sha512-kzdHgnaXRonttiTfKYnSVafbWngPPr2qKw9BWYBESl91W54e+9R5pP70LtWxV56g0f05f/SQrwHYkfvbwcdQ/A== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/helper-skip-transparent-expression-wrappers" "^7.16.0" "@babel/plugin-syntax-optional-chaining" "^7.8.3" -"@babel/plugin-proposal-private-methods@^7.12.1", "@babel/plugin-proposal-private-methods@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-private-methods/-/plugin-proposal-private-methods-7.16.0.tgz#b4dafb9c717e4301c5776b30d080d6383c89aff6" - integrity sha512-IvHmcTHDFztQGnn6aWq4t12QaBXTKr1whF/dgp9kz84X6GUcwq9utj7z2wFCUfeOup/QKnOlt2k0zxkGFx9ubg== +"@babel/plugin-proposal-private-methods@^7.12.1", "@babel/plugin-proposal-private-methods@^7.16.5": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-private-methods/-/plugin-proposal-private-methods-7.16.5.tgz#2086f7d78c1b0c712d49b5c3fbc2d1ca21a7ee12" + integrity sha512-+yFMO4BGT3sgzXo+lrq7orX5mAZt57DwUK6seqII6AcJnJOIhBJ8pzKH47/ql/d426uQ7YhN8DpUFirQzqYSUA== dependencies: - "@babel/helper-create-class-features-plugin" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-create-class-features-plugin" "^7.16.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-proposal-private-property-in-object@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.16.0.tgz#69e935b2c5c79d2488112d886f0c4e2790fee76f" - integrity sha512-3jQUr/HBbMVZmi72LpjQwlZ55i1queL8KcDTQEkAHihttJnAPrcvG9ZNXIfsd2ugpizZo595egYV6xy+pv4Ofw== +"@babel/plugin-proposal-private-property-in-object@^7.16.5": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.16.5.tgz#a42d4b56005db3d405b12841309dbca647e7a21b" + integrity sha512-+YGh5Wbw0NH3y/E5YMu6ci5qTDmAEVNoZ3I54aB6nVEOZ5BQ7QJlwKq5pYVucQilMByGn/bvX0af+uNaPRCabA== dependencies: "@babel/helper-annotate-as-pure" "^7.16.0" - "@babel/helper-create-class-features-plugin" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-create-class-features-plugin" "^7.16.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-syntax-private-property-in-object" "^7.14.5" -"@babel/plugin-proposal-unicode-property-regex@^7.16.0", "@babel/plugin-proposal-unicode-property-regex@^7.4.4", "@babel/plugin-proposal-unicode-property-regex@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-unicode-property-regex/-/plugin-proposal-unicode-property-regex-7.16.0.tgz#890482dfc5ea378e42e19a71e709728cabf18612" - integrity sha512-ti7IdM54NXv29cA4+bNNKEMS4jLMCbJgl+Drv+FgYy0erJLAxNAIXcNjNjrRZEcWq0xJHsNVwQezskMFpF8N9g== +"@babel/plugin-proposal-unicode-property-regex@^7.16.5", "@babel/plugin-proposal-unicode-property-regex@^7.4.4", "@babel/plugin-proposal-unicode-property-regex@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-unicode-property-regex/-/plugin-proposal-unicode-property-regex-7.16.5.tgz#35fe753afa7c572f322bd068ff3377bde0f37080" + integrity sha512-s5sKtlKQyFSatt781HQwv1hoM5BQ9qRH30r+dK56OLDsHmV74mzwJNX7R1yMuE7VZKG5O6q/gmOGSAO6ikTudg== dependencies: "@babel/helper-create-regexp-features-plugin" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-syntax-async-generators@^7.8.0", "@babel/plugin-syntax-async-generators@^7.8.4": version "7.8.4" @@ -734,12 +672,12 @@ dependencies: "@babel/helper-plugin-utils" "^7.14.5" -"@babel/plugin-syntax-decorators@^7.16.0", "@babel/plugin-syntax-decorators@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-decorators/-/plugin-syntax-decorators-7.16.0.tgz#eb8d811cdd1060f6ac3c00956bf3f6335505a32f" - integrity sha512-nxnnngZClvlY13nHJAIDow0S7Qzhq64fQ/NlqS+VER3kjW/4F0jLhXjeL8jcwSwz6Ca3rotT5NJD2T9I7lcv7g== +"@babel/plugin-syntax-decorators@^7.16.5", "@babel/plugin-syntax-decorators@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-decorators/-/plugin-syntax-decorators-7.16.5.tgz#8d397dee482716a79f1a22314f0b4770a5b67427" + integrity sha512-3CbYTXfflvyy8O819uhZcZSMedZG4J8yS/NLTc/8T24M9ke1GssTGvg8VZu3Yn2LU5IyQSv1CmPq0a9JWHXJwg== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-syntax-dynamic-import@^7.8.0", "@babel/plugin-syntax-dynamic-import@^7.8.3": version "7.8.3" @@ -748,12 +686,12 @@ dependencies: "@babel/helper-plugin-utils" "^7.8.0" -"@babel/plugin-syntax-export-default-from@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-export-default-from/-/plugin-syntax-export-default-from-7.16.0.tgz#648520667776781f9a0da178f245fff85bc9e36f" - integrity sha512-xllLOdBj77mFSw8s02I+2SSQGHOftbWTlGmagheuNk/gjQsk7IrYsR/EosXVAVpgIUFffLckB/iPRioQYLHSrQ== +"@babel/plugin-syntax-export-default-from@^7.16.5": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-export-default-from/-/plugin-syntax-export-default-from-7.16.5.tgz#bfc148b007cba23cd2ce2f3c16df223afb44ab30" + integrity sha512-tvY55nhq4mSG9WbM7IZcLIhdc5jzIZu0PQKJHtZ16+dF7oBxKbqV/Z0e9ta2zaLMvUjH+3rJv1hbZ0+lpXzuFQ== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-syntax-export-namespace-from@^7.8.3": version "7.8.3" @@ -762,12 +700,12 @@ dependencies: "@babel/helper-plugin-utils" "^7.8.3" -"@babel/plugin-syntax-flow@^7.16.0", "@babel/plugin-syntax-flow@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.16.0.tgz#07427021d093ed77019408221beaf0272bbcfaec" - integrity sha512-dH91yCo0RyqfzWgoM5Ji9ir8fQ+uFbt9KHM3d2x4jZOuHS6wNA+CRmRUP/BWCsHG2bjc7A2Way6AvH1eQk0wig== +"@babel/plugin-syntax-flow@^7.16.5", "@babel/plugin-syntax-flow@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.16.5.tgz#ca0d85e12d71b825b4e9fd1f8d29b64acdf1b46e" + integrity sha512-Nrx+7EAJx1BieBQseZa2pavVH2Rp7hADK2xn7coYqVbWRu9C2OFizYcsKo6TrrqJkJl+qF/+Qqzrk/+XDu4GnA== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-syntax-import-meta@^7.8.3": version "7.10.4" @@ -797,12 +735,12 @@ dependencies: "@babel/helper-plugin-utils" "^7.14.5" -"@babel/plugin-syntax-jsx@^7.12.13", "@babel/plugin-syntax-jsx@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.16.0.tgz#f9624394317365a9a88c82358d3f8471154698f1" - integrity sha512-8zv2+xiPHwly31RK4RmnEYY5zziuF3O7W2kIDW+07ewWDh6Oi0dRq8kwvulRkFgt6DB97RlKs5c1y068iPlCUg== +"@babel/plugin-syntax-jsx@^7.12.13", "@babel/plugin-syntax-jsx@^7.16.5": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.16.5.tgz#bf255d252f78bc8b77a17cadc37d1aa5b8ed4394" + integrity sha512-42OGssv9NPk4QHKVgIHlzeLgPOW5rGgfV5jzG90AhcXXIv6hu/eqj63w4VgvRxdvZY3AlYeDgPiSJ3BqAd1Y6Q== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-syntax-logical-assignment-operators@^7.10.4", "@babel/plugin-syntax-logical-assignment-operators@^7.8.3": version "7.10.4" @@ -861,91 +799,92 @@ "@babel/helper-plugin-utils" "^7.14.5" "@babel/plugin-syntax-typescript@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.16.0.tgz#2feeb13d9334cc582ea9111d3506f773174179bb" - integrity sha512-Xv6mEXqVdaqCBfJFyeab0fH2DnUoMsDmhamxsSi4j8nLd4Vtw213WMJr55xxqipC/YVWyPY3K0blJncPYji+dQ== + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.16.5.tgz#f47a33e4eee38554f00fb6b2f894fa1f5649b0b3" + integrity sha512-/d4//lZ1Vqb4mZ5xTep3dDK888j7BGM/iKqBmndBaoYAFPlPKrGU608VVBz5JeyAb6YQDjRu1UKqj86UhwWVgw== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-arrow-functions@^7.12.1", "@babel/plugin-transform-arrow-functions@^7.16.0", "@babel/plugin-transform-arrow-functions@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.16.0.tgz#951706f8b449c834ed07bd474c0924c944b95a8e" - integrity sha512-vIFb5250Rbh7roWARvCLvIJ/PtAU5Lhv7BtZ1u24COwpI9Ypjsh+bZcKk6rlIyalK+r0jOc1XQ8I4ovNxNrWrA== +"@babel/plugin-transform-arrow-functions@^7.12.1", "@babel/plugin-transform-arrow-functions@^7.16.5", "@babel/plugin-transform-arrow-functions@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.16.5.tgz#04c18944dd55397b521d9d7511e791acea7acf2d" + integrity sha512-8bTHiiZyMOyfZFULjsCnYOWG059FVMes0iljEHSfARhNgFfpsqE92OrCffv3veSw9rwMkYcFe9bj0ZoXU2IGtQ== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-async-to-generator@^7.16.0", "@babel/plugin-transform-async-to-generator@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.16.0.tgz#df12637f9630ddfa0ef9d7a11bc414d629d38604" - integrity sha512-PbIr7G9kR8tdH6g8Wouir5uVjklETk91GMVSUq+VaOgiinbCkBP6Q7NN/suM/QutZkMJMvcyAriogcYAdhg8Gw== +"@babel/plugin-transform-async-to-generator@^7.16.5", "@babel/plugin-transform-async-to-generator@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.16.5.tgz#89c9b501e65bb14c4579a6ce9563f859de9b34e4" + integrity sha512-TMXgfioJnkXU+XRoj7P2ED7rUm5jbnDWwlCuFVTpQboMfbSya5WrmubNBAMlk7KXvywpo8rd8WuYZkis1o2H8w== dependencies: "@babel/helper-module-imports" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" - "@babel/helper-remap-async-to-generator" "^7.16.0" + "@babel/helper-plugin-utils" "^7.16.5" + "@babel/helper-remap-async-to-generator" "^7.16.5" -"@babel/plugin-transform-block-scoped-functions@^7.16.0", "@babel/plugin-transform-block-scoped-functions@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.16.0.tgz#c618763233ad02847805abcac4c345ce9de7145d" - integrity sha512-V14As3haUOP4ZWrLJ3VVx5rCnrYhMSHN/jX7z6FAt5hjRkLsb0snPCmJwSOML5oxkKO4FNoNv7V5hw/y2bjuvg== +"@babel/plugin-transform-block-scoped-functions@^7.16.5", "@babel/plugin-transform-block-scoped-functions@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.16.5.tgz#af087494e1c387574260b7ee9b58cdb5a4e9b0b0" + integrity sha512-BxmIyKLjUGksJ99+hJyL/HIxLIGnLKtw772zYDER7UuycDZ+Xvzs98ZQw6NGgM2ss4/hlFAaGiZmMNKvValEjw== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-block-scoping@^7.12.12", "@babel/plugin-transform-block-scoping@^7.16.0", "@babel/plugin-transform-block-scoping@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.16.0.tgz#bcf433fb482fe8c3d3b4e8a66b1c4a8e77d37c16" - integrity sha512-27n3l67/R3UrXfizlvHGuTwsRIFyce3D/6a37GRxn28iyTPvNXaW4XvznexRh1zUNLPjbLL22Id0XQElV94ruw== +"@babel/plugin-transform-block-scoping@^7.12.12", "@babel/plugin-transform-block-scoping@^7.16.5", "@babel/plugin-transform-block-scoping@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.16.5.tgz#b91f254fe53e210eabe4dd0c40f71c0ed253c5e7" + integrity sha512-JxjSPNZSiOtmxjX7PBRBeRJTUKTyJ607YUYeT0QJCNdsedOe+/rXITjP08eG8xUpsLfPirgzdCFN+h0w6RI+pQ== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-classes@^7.12.1", "@babel/plugin-transform-classes@^7.16.0", "@babel/plugin-transform-classes@^7.9.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-classes/-/plugin-transform-classes-7.16.0.tgz#54cf5ff0b2242c6573d753cd4bfc7077a8b282f5" - integrity sha512-HUxMvy6GtAdd+GKBNYDWCIA776byUQH8zjnfjxwT1P1ARv/wFu8eBDpmXQcLS/IwRtrxIReGiplOwMeyO7nsDQ== +"@babel/plugin-transform-classes@^7.12.1", "@babel/plugin-transform-classes@^7.16.5", "@babel/plugin-transform-classes@^7.9.0": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-classes/-/plugin-transform-classes-7.16.5.tgz#6acf2ec7adb50fb2f3194dcd2909dbd056dcf216" + integrity sha512-DzJ1vYf/7TaCYy57J3SJ9rV+JEuvmlnvvyvYKFbk5u46oQbBvuB9/0w+YsVsxkOv8zVWKpDmUoj4T5ILHoXevA== dependencies: "@babel/helper-annotate-as-pure" "^7.16.0" + "@babel/helper-environment-visitor" "^7.16.5" "@babel/helper-function-name" "^7.16.0" "@babel/helper-optimise-call-expression" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" - "@babel/helper-replace-supers" "^7.16.0" + "@babel/helper-plugin-utils" "^7.16.5" + "@babel/helper-replace-supers" "^7.16.5" "@babel/helper-split-export-declaration" "^7.16.0" globals "^11.1.0" -"@babel/plugin-transform-computed-properties@^7.16.0", "@babel/plugin-transform-computed-properties@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.16.0.tgz#e0c385507d21e1b0b076d66bed6d5231b85110b7" - integrity sha512-63l1dRXday6S8V3WFY5mXJwcRAnPYxvFfTlt67bwV1rTyVTM5zrp0DBBb13Kl7+ehkCVwIZPumPpFP/4u70+Tw== +"@babel/plugin-transform-computed-properties@^7.16.5", "@babel/plugin-transform-computed-properties@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.16.5.tgz#2af91ebf0cceccfcc701281ada7cfba40a9b322a" + integrity sha512-n1+O7xtU5lSLraRzX88CNcpl7vtGdPakKzww74bVwpAIRgz9JVLJJpOLb0uYqcOaXVM0TL6X0RVeIJGD2CnCkg== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-destructuring@^7.12.1", "@babel/plugin-transform-destructuring@^7.16.0", "@babel/plugin-transform-destructuring@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.16.0.tgz#ad3d7e74584ad5ea4eadb1e6642146c590dee33c" - integrity sha512-Q7tBUwjxLTsHEoqktemHBMtb3NYwyJPTJdM+wDwb0g8PZ3kQUIzNvwD5lPaqW/p54TXBc/MXZu9Jr7tbUEUM8Q== +"@babel/plugin-transform-destructuring@^7.12.1", "@babel/plugin-transform-destructuring@^7.16.5", "@babel/plugin-transform-destructuring@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.16.5.tgz#89ebc87499ac4a81b897af53bb5d3eed261bd568" + integrity sha512-GuRVAsjq+c9YPK6NeTkRLWyQskDC099XkBSVO+6QzbnOnH2d/4mBVXYStaPrZD3dFRfg00I6BFJ9Atsjfs8mlg== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-dotall-regex@^7.16.0", "@babel/plugin-transform-dotall-regex@^7.4.4", "@babel/plugin-transform-dotall-regex@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.16.0.tgz#50bab00c1084b6162d0a58a818031cf57798e06f" - integrity sha512-FXlDZfQeLILfJlC6I1qyEwcHK5UpRCFkaoVyA1nk9A1L1Yu583YO4un2KsLBsu3IJb4CUbctZks8tD9xPQubLw== +"@babel/plugin-transform-dotall-regex@^7.16.5", "@babel/plugin-transform-dotall-regex@^7.4.4", "@babel/plugin-transform-dotall-regex@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.16.5.tgz#b40739c00b6686820653536d6d143e311de67936" + integrity sha512-iQiEMt8Q4/5aRGHpGVK2Zc7a6mx7qEAO7qehgSug3SDImnuMzgmm/wtJALXaz25zUj1PmnNHtShjFgk4PDx4nw== dependencies: "@babel/helper-create-regexp-features-plugin" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-duplicate-keys@^7.16.0", "@babel/plugin-transform-duplicate-keys@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-7.16.0.tgz#8bc2e21813e3e89e5e5bf3b60aa5fc458575a176" - integrity sha512-LIe2kcHKAZOJDNxujvmp6z3mfN6V9lJxubU4fJIGoQCkKe3Ec2OcbdlYP+vW++4MpxwG0d1wSDOJtQW5kLnkZQ== +"@babel/plugin-transform-duplicate-keys@^7.16.5", "@babel/plugin-transform-duplicate-keys@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-7.16.5.tgz#2450f2742325412b746d7d005227f5e8973b512a" + integrity sha512-81tijpDg2a6I1Yhj4aWY1l3O1J4Cg/Pd7LfvuaH2VVInAkXtzibz9+zSPdUM1WvuUi128ksstAP0hM5w48vQgg== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-exponentiation-operator@^7.16.0", "@babel/plugin-transform-exponentiation-operator@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.16.0.tgz#a180cd2881e3533cef9d3901e48dad0fbeff4be4" - integrity sha512-OwYEvzFI38hXklsrbNivzpO3fh87skzx8Pnqi4LoSYeav0xHlueSoCJrSgTPfnbyzopo5b3YVAJkFIcUpK2wsw== +"@babel/plugin-transform-exponentiation-operator@^7.16.5", "@babel/plugin-transform-exponentiation-operator@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.16.5.tgz#36e261fa1ab643cfaf30eeab38e00ed1a76081e2" + integrity sha512-12rba2HwemQPa7BLIKCzm1pT2/RuQHtSFHdNl41cFiC6oi4tcrp7gjB07pxQvFpcADojQywSjblQth6gJyE6CA== dependencies: - "@babel/helper-builder-binary-assignment-operator-visitor" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-builder-binary-assignment-operator-visitor" "^7.16.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-transform-flow-strip-types@7.9.0": version "7.9.0" @@ -955,116 +894,116 @@ "@babel/helper-plugin-utils" "^7.8.3" "@babel/plugin-syntax-flow" "^7.8.3" -"@babel/plugin-transform-flow-strip-types@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-flow-strip-types/-/plugin-transform-flow-strip-types-7.16.0.tgz#edd968dc2041c1b69e451a262e948d6654a79dc2" - integrity sha512-vs/F5roOaO/+WxKfp9PkvLsAyj0G+Q0zbFimHm9X2KDgabN2XmNFoAafmeGEYspUlIF9+MvVmyek9UyHiqeG/w== +"@babel/plugin-transform-flow-strip-types@^7.16.5": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-flow-strip-types/-/plugin-transform-flow-strip-types-7.16.5.tgz#8ceb65ab6ca4a349e04d1887e2470a5bfe8f046f" + integrity sha512-skE02E/MptkZdBS4HwoRhjWXqeKQj0BWKEAPfPC+8R4/f6bjQqQ9Nftv/+HkxWwnVxh/E2NV9TNfzLN5H/oiBw== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" - "@babel/plugin-syntax-flow" "^7.16.0" + "@babel/helper-plugin-utils" "^7.16.5" + "@babel/plugin-syntax-flow" "^7.16.5" -"@babel/plugin-transform-for-of@^7.12.1", "@babel/plugin-transform-for-of@^7.16.0", "@babel/plugin-transform-for-of@^7.9.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.16.0.tgz#f7abaced155260e2461359bbc7c7248aca5e6bd2" - integrity sha512-5QKUw2kO+GVmKr2wMYSATCTTnHyscl6sxFRAY+rvN7h7WB0lcG0o4NoV6ZQU32OZGVsYUsfLGgPQpDFdkfjlJQ== +"@babel/plugin-transform-for-of@^7.12.1", "@babel/plugin-transform-for-of@^7.16.5", "@babel/plugin-transform-for-of@^7.9.0": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.16.5.tgz#9b544059c6ca11d565457c0ff1f08e13ce225261" + integrity sha512-+DpCAJFPAvViR17PIMi9x2AE34dll5wNlXO43wagAX2YcRGgEVHCNFC4azG85b4YyyFarvkc/iD5NPrz4Oneqw== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-function-name@^7.16.0", "@babel/plugin-transform-function-name@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-function-name/-/plugin-transform-function-name-7.16.0.tgz#02e3699c284c6262236599f751065c5d5f1f400e" - integrity sha512-lBzMle9jcOXtSOXUpc7tvvTpENu/NuekNJVova5lCCWCV9/U1ho2HH2y0p6mBg8fPm/syEAbfaaemYGOHCY3mg== +"@babel/plugin-transform-function-name@^7.16.5", "@babel/plugin-transform-function-name@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-function-name/-/plugin-transform-function-name-7.16.5.tgz#6896ebb6a5538a75d6a4086a277752f655a7bd15" + integrity sha512-Fuec/KPSpVLbGo6z1RPw4EE1X+z9gZk1uQmnYy7v4xr4TO9p41v1AoUuXEtyqAI7H+xNJYSICzRqZBhDEkd3kQ== dependencies: "@babel/helper-function-name" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-literals@^7.16.0", "@babel/plugin-transform-literals@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-literals/-/plugin-transform-literals-7.16.0.tgz#79711e670ffceb31bd298229d50f3621f7980cac" - integrity sha512-gQDlsSF1iv9RU04clgXqRjrPyyoJMTclFt3K1cjLmTKikc0s/6vE3hlDeEVC71wLTRu72Fq7650kABrdTc2wMQ== +"@babel/plugin-transform-literals@^7.16.5", "@babel/plugin-transform-literals@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-literals/-/plugin-transform-literals-7.16.5.tgz#af392b90e3edb2bd6dc316844cbfd6b9e009d320" + integrity sha512-B1j9C/IfvshnPcklsc93AVLTrNVa69iSqztylZH6qnmiAsDDOmmjEYqOm3Ts2lGSgTSywnBNiqC949VdD0/gfw== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-member-expression-literals@^7.16.0", "@babel/plugin-transform-member-expression-literals@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-7.16.0.tgz#5251b4cce01eaf8314403d21aedb269d79f5e64b" - integrity sha512-WRpw5HL4Jhnxw8QARzRvwojp9MIE7Tdk3ez6vRyUk1MwgjJN0aNpRoXainLR5SgxmoXx/vsXGZ6OthP6t/RbUg== +"@babel/plugin-transform-member-expression-literals@^7.16.5", "@babel/plugin-transform-member-expression-literals@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-7.16.5.tgz#4bd6ecdc11932361631097b779ca5c7570146dd5" + integrity sha512-d57i3vPHWgIde/9Y8W/xSFUndhvhZN5Wu2TjRrN1MVz5KzdUihKnfDVlfP1U7mS5DNj/WHHhaE4/tTi4hIyHwQ== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-modules-amd@^7.16.0", "@babel/plugin-transform-modules-amd@^7.9.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-7.16.0.tgz#09abd41e18dcf4fd479c598c1cef7bd39eb1337e" - integrity sha512-rWFhWbCJ9Wdmzln1NmSCqn7P0RAD+ogXG/bd9Kg5c7PKWkJtkiXmYsMBeXjDlzHpVTJ4I/hnjs45zX4dEv81xw== +"@babel/plugin-transform-modules-amd@^7.16.5", "@babel/plugin-transform-modules-amd@^7.9.0": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-7.16.5.tgz#92c0a3e83f642cb7e75fada9ab497c12c2616527" + integrity sha512-oHI15S/hdJuSCfnwIz+4lm6wu/wBn7oJ8+QrkzPPwSFGXk8kgdI/AIKcbR/XnD1nQVMg/i6eNaXpszbGuwYDRQ== dependencies: - "@babel/helper-module-transforms" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-module-transforms" "^7.16.5" + "@babel/helper-plugin-utils" "^7.16.5" babel-plugin-dynamic-import-node "^2.3.3" -"@babel/plugin-transform-modules-commonjs@^7.16.0", "@babel/plugin-transform-modules-commonjs@^7.9.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.16.0.tgz#add58e638c8ddc4875bd9a9ecb5c594613f6c922" - integrity sha512-Dzi+NWqyEotgzk/sb7kgQPJQf7AJkQBWsVp1N6JWc1lBVo0vkElUnGdr1PzUBmfsCCN5OOFya3RtpeHk15oLKQ== +"@babel/plugin-transform-modules-commonjs@^7.16.5", "@babel/plugin-transform-modules-commonjs@^7.9.0": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.16.5.tgz#4ee03b089536f076b2773196529d27c32b9d7bde" + integrity sha512-ABhUkxvoQyqhCWyb8xXtfwqNMJD7tx+irIRnUh6lmyFud7Jln1WzONXKlax1fg/ey178EXbs4bSGNd6PngO+SQ== dependencies: - "@babel/helper-module-transforms" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-module-transforms" "^7.16.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/helper-simple-access" "^7.16.0" babel-plugin-dynamic-import-node "^2.3.3" -"@babel/plugin-transform-modules-systemjs@^7.16.0", "@babel/plugin-transform-modules-systemjs@^7.9.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.16.0.tgz#a92cf240afeb605f4ca16670453024425e421ea4" - integrity sha512-yuGBaHS3lF1m/5R+6fjIke64ii5luRUg97N2wr+z1sF0V+sNSXPxXDdEEL/iYLszsN5VKxVB1IPfEqhzVpiqvg== +"@babel/plugin-transform-modules-systemjs@^7.16.5", "@babel/plugin-transform-modules-systemjs@^7.9.0": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.16.5.tgz#07078ba2e3cc94fbdd06836e355c246e98ad006b" + integrity sha512-53gmLdScNN28XpjEVIm7LbWnD/b/TpbwKbLk6KV4KqC9WyU6rq1jnNmVG6UgAdQZVVGZVoik3DqHNxk4/EvrjA== dependencies: "@babel/helper-hoist-variables" "^7.16.0" - "@babel/helper-module-transforms" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-module-transforms" "^7.16.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/helper-validator-identifier" "^7.15.7" babel-plugin-dynamic-import-node "^2.3.3" -"@babel/plugin-transform-modules-umd@^7.16.0", "@babel/plugin-transform-modules-umd@^7.9.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-7.16.0.tgz#195f26c2ad6d6a391b70880effce18ce625e06a7" - integrity sha512-nx4f6no57himWiHhxDM5pjwhae5vLpTK2zCnDH8+wNLJy0TVER/LJRHl2bkt6w9Aad2sPD5iNNoUpY3X9sTGDg== +"@babel/plugin-transform-modules-umd@^7.16.5", "@babel/plugin-transform-modules-umd@^7.9.0": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-7.16.5.tgz#caa9c53d636fb4e3c99fd35a4c9ba5e5cd7e002e" + integrity sha512-qTFnpxHMoenNHkS3VoWRdwrcJ3FhX567GvDA3hRZKF0Dj8Fmg0UzySZp3AP2mShl/bzcywb/UWAMQIjA1bhXvw== dependencies: - "@babel/helper-module-transforms" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-module-transforms" "^7.16.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-named-capturing-groups-regex@^7.16.0", "@babel/plugin-transform-named-capturing-groups-regex@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.16.0.tgz#d3db61cc5d5b97986559967cd5ea83e5c32096ca" - integrity sha512-LogN88uO+7EhxWc8WZuQ8vxdSyVGxhkh8WTC3tzlT8LccMuQdA81e9SGV6zY7kY2LjDhhDOFdQVxdGwPyBCnvg== +"@babel/plugin-transform-named-capturing-groups-regex@^7.16.5", "@babel/plugin-transform-named-capturing-groups-regex@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.16.5.tgz#4afd8cdee377ce3568f4e8a9ee67539b69886a3c" + integrity sha512-/wqGDgvFUeKELW6ex6QB7dLVRkd5ehjw34tpXu1nhKC0sFfmaLabIswnpf8JgDyV2NeDmZiwoOb0rAmxciNfjA== dependencies: "@babel/helper-create-regexp-features-plugin" "^7.16.0" -"@babel/plugin-transform-new-target@^7.16.0", "@babel/plugin-transform-new-target@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-new-target/-/plugin-transform-new-target-7.16.0.tgz#af823ab576f752215a49937779a41ca65825ab35" - integrity sha512-fhjrDEYv2DBsGN/P6rlqakwRwIp7rBGLPbrKxwh7oVt5NNkIhZVOY2GRV+ULLsQri1bDqwDWnU3vhlmx5B2aCw== +"@babel/plugin-transform-new-target@^7.16.5", "@babel/plugin-transform-new-target@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-new-target/-/plugin-transform-new-target-7.16.5.tgz#759ea9d6fbbc20796056a5d89d13977626384416" + integrity sha512-ZaIrnXF08ZC8jnKR4/5g7YakGVL6go6V9ql6Jl3ecO8PQaQqFE74CuM384kezju7Z9nGCCA20BqZaR1tJ/WvHg== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-object-super@^7.16.0", "@babel/plugin-transform-object-super@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.16.0.tgz#fb20d5806dc6491a06296ac14ea8e8d6fedda72b" - integrity sha512-fds+puedQHn4cPLshoHcR1DTMN0q1V9ou0mUjm8whx9pGcNvDrVVrgw+KJzzCaiTdaYhldtrUps8DWVMgrSEyg== +"@babel/plugin-transform-object-super@^7.16.5", "@babel/plugin-transform-object-super@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.16.5.tgz#8ccd9a1bcd3e7732ff8aa1702d067d8cd70ce380" + integrity sha512-tded+yZEXuxt9Jdtkc1RraW1zMF/GalVxaVVxh41IYwirdRgyAxxxCKZ9XB7LxZqmsjfjALxupNE1MIz9KH+Zg== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" - "@babel/helper-replace-supers" "^7.16.0" + "@babel/helper-plugin-utils" "^7.16.5" + "@babel/helper-replace-supers" "^7.16.5" -"@babel/plugin-transform-parameters@^7.12.1", "@babel/plugin-transform-parameters@^7.16.0", "@babel/plugin-transform-parameters@^7.16.3", "@babel/plugin-transform-parameters@^7.8.7": - version "7.16.3" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.16.3.tgz#fa9e4c874ee5223f891ee6fa8d737f4766d31d15" - integrity sha512-3MaDpJrOXT1MZ/WCmkOFo7EtmVVC8H4EUZVrHvFOsmwkk4lOjQj8rzv8JKUZV4YoQKeoIgk07GO+acPU9IMu/w== +"@babel/plugin-transform-parameters@^7.12.1", "@babel/plugin-transform-parameters@^7.16.5", "@babel/plugin-transform-parameters@^7.8.7": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.16.5.tgz#4fc74b18a89638bd90aeec44a11793ecbe031dde" + integrity sha512-B3O6AL5oPop1jAVg8CV+haeUte9oFuY85zu0jwnRNZZi3tVAbJriu5tag/oaO2kGaQM/7q7aGPBlTI5/sr9enA== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-property-literals@^7.16.0", "@babel/plugin-transform-property-literals@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.16.0.tgz#a95c552189a96a00059f6776dc4e00e3690c78d1" - integrity sha512-XLldD4V8+pOqX2hwfWhgwXzGdnDOThxaNTgqagOcpBgIxbUvpgU2FMvo5E1RyHbk756WYgdbS0T8y0Cj9FKkWQ== +"@babel/plugin-transform-property-literals@^7.16.5", "@babel/plugin-transform-property-literals@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.16.5.tgz#58f1465a7202a2bb2e6b003905212dd7a79abe3f" + integrity sha512-+IRcVW71VdF9pEH/2R/Apab4a19LVvdVsr/gEeotH00vSDVlKD+XgfSIw+cgGWsjDB/ziqGv/pGoQZBIiQVXHg== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-transform-react-display-name@7.8.3": version "7.8.3" @@ -1073,66 +1012,66 @@ dependencies: "@babel/helper-plugin-utils" "^7.8.3" -"@babel/plugin-transform-react-display-name@^7.16.0", "@babel/plugin-transform-react-display-name@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-display-name/-/plugin-transform-react-display-name-7.16.0.tgz#9a0ad8aa8e8790883a7bd2736f66229a58125676" - integrity sha512-FJFdJAqaCpndL+pIf0aeD/qlQwT7QXOvR6Cc8JPvNhKJBi2zc/DPc4g05Y3fbD/0iWAMQFGij4+Xw+4L/BMpTg== +"@babel/plugin-transform-react-display-name@^7.16.5", "@babel/plugin-transform-react-display-name@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-display-name/-/plugin-transform-react-display-name-7.16.5.tgz#d5e910327d7931fb9f8f9b6c6999473ceae5a286" + integrity sha512-dHYCOnzSsXFz8UcdNQIHGvg94qPL/teF7CCiCEMRxmA1G2p5Mq4JnKVowCDxYfiQ9D7RstaAp9kwaSI+sXbnhw== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-react-jsx-development@^7.16.0", "@babel/plugin-transform-react-jsx-development@^7.9.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx-development/-/plugin-transform-react-jsx-development-7.16.0.tgz#1cb52874678d23ab11d0d16488d54730807303ef" - integrity sha512-qq65iSqBRq0Hr3wq57YG2AmW0H6wgTnIzpffTphrUWUgLCOK+zf1f7G0vuOiXrp7dU1qq+fQBoqZ3wCDAkhFzw== +"@babel/plugin-transform-react-jsx-development@^7.16.5", "@babel/plugin-transform-react-jsx-development@^7.9.0": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx-development/-/plugin-transform-react-jsx-development-7.16.5.tgz#87da9204c275ffb57f45d192a1120cf104bc1e86" + integrity sha512-uQSLacMZSGLCxOw20dzo1dmLlKkd+DsayoV54q3MHXhbqgPzoiGerZQgNPl/Ro8/OcXV2ugfnkx+rxdS0sN5Uw== dependencies: - "@babel/plugin-transform-react-jsx" "^7.16.0" + "@babel/plugin-transform-react-jsx" "^7.16.5" "@babel/plugin-transform-react-jsx-self@^7.9.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.16.0.tgz#09202158abbc716a08330f392bfb98d6b9acfa0c" - integrity sha512-97yCFY+2GvniqOThOSjPor8xUoDiQ0STVWAQMl3pjhJoFVe5DuXDLZCRSZxu9clx+oRCbTiXGgKEG/Yoyo6Y+w== + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.16.5.tgz#e16bf9cd52f2e8ea11f9d7edfb48458586c760bf" + integrity sha512-fvwq+jir1Vn4f5oBS0H/J/gD5CneTD53MHs+NMjlHcha4Sq35fwxI5RtmJGEBXO+M93f/eeD9cAhRPhmLyJiVw== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-transform-react-jsx-source@^7.9.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.16.0.tgz#d40c959d7803aae38224594585748693e84c0a22" - integrity sha512-8yvbGGrHOeb/oyPc9tzNoe9/lmIjz3HLa9Nc5dMGDyNpGjfFrk8D2KdEq9NRkftZzeoQEW6yPQ29TMZtrLiUUA== + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.16.5.tgz#7c2aeb6539780f3312266de3348bbb74ce9d3ce1" + integrity sha512-/eP+nZywJntGLjSPjksAnM9/ELIs3RbiEuTu2/zAOzwwBcfiu+m/iptEq1lERUUtSXubYSHVnVHMr13GR+TwPw== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-react-jsx@^7.12.12", "@babel/plugin-transform-react-jsx@^7.16.0", "@babel/plugin-transform-react-jsx@^7.9.1": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.16.0.tgz#55b797d4960c3de04e07ad1c0476e2bc6a4889f1" - integrity sha512-rqDgIbukZ44pqq7NIRPGPGNklshPkvlmvqjdx3OZcGPk4zGIenYkxDTvl3LsSL8gqcc3ZzGmXPE6hR/u/voNOw== +"@babel/plugin-transform-react-jsx@^7.12.12", "@babel/plugin-transform-react-jsx@^7.16.5", "@babel/plugin-transform-react-jsx@^7.9.1": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.16.5.tgz#5298aedc5f81e02b1cb702e597e8d6a346675765" + integrity sha512-+arLIz1d7kmwX0fKxTxbnoeG85ONSnLpvdODa4P3pc1sS7CV1hfmtYWufkW/oYsPnkDrEeQFxhUWcFnrXW7jQQ== dependencies: "@babel/helper-annotate-as-pure" "^7.16.0" "@babel/helper-module-imports" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" - "@babel/plugin-syntax-jsx" "^7.16.0" + "@babel/helper-plugin-utils" "^7.16.5" + "@babel/plugin-syntax-jsx" "^7.16.5" "@babel/types" "^7.16.0" -"@babel/plugin-transform-react-pure-annotations@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-pure-annotations/-/plugin-transform-react-pure-annotations-7.16.0.tgz#23db6ddf558d8abde41b8ad9d59f48ad5532ccab" - integrity sha512-NC/Bj2MG+t8Ef5Pdpo34Ay74X4Rt804h5y81PwOpfPtmAK3i6CizmQqwyBQzIepz1Yt8wNr2Z2L7Lu3qBMfZMA== +"@babel/plugin-transform-react-pure-annotations@^7.16.5": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-pure-annotations/-/plugin-transform-react-pure-annotations-7.16.5.tgz#6535d0fe67c7a3a26c5105f92c8cbcbe844cd94b" + integrity sha512-0nYU30hCxnCVCbRjSy9ahlhWZ2Sn6khbY4FqR91W+2RbSqkWEbVu2gXh45EqNy4Bq7sRU+H4i0/6YKwOSzh16A== dependencies: "@babel/helper-annotate-as-pure" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-regenerator@^7.16.0", "@babel/plugin-transform-regenerator@^7.8.7": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.16.0.tgz#eaee422c84b0232d03aea7db99c97deeaf6125a4" - integrity sha512-JAvGxgKuwS2PihiSFaDrp94XOzzTUeDeOQlcKzVAyaPap7BnZXK/lvMDiubkPTdotPKOIZq9xWXWnggUMYiExg== +"@babel/plugin-transform-regenerator@^7.16.5", "@babel/plugin-transform-regenerator@^7.8.7": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.16.5.tgz#704cc6d8dd3dd4758267621ab7b36375238cef13" + integrity sha512-2z+it2eVWU8TtQQRauvGUqZwLy4+7rTfo6wO4npr+fvvN1SW30ZF3O/ZRCNmTuu4F5MIP8OJhXAhRV5QMJOuYg== dependencies: regenerator-transform "^0.14.2" -"@babel/plugin-transform-reserved-words@^7.16.0", "@babel/plugin-transform-reserved-words@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-7.16.0.tgz#fff4b9dcb19e12619394bda172d14f2d04c0379c" - integrity sha512-Dgs8NNCehHSvXdhEhln8u/TtJxfVwGYCgP2OOr5Z3Ar+B+zXicEOKNTyc+eca2cuEOMtjW6m9P9ijOt8QdqWkg== +"@babel/plugin-transform-reserved-words@^7.16.5", "@babel/plugin-transform-reserved-words@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-7.16.5.tgz#db95e98799675e193dc2b47d3e72a7c0651d0c30" + integrity sha512-aIB16u8lNcf7drkhXJRoggOxSTUAuihTSTfAcpynowGJOZiGf+Yvi7RuTwFzVYSYPmWyARsPqUGoZWWWxLiknw== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/plugin-transform-runtime@7.9.0": version "7.9.0" @@ -1145,54 +1084,54 @@ semver "^5.5.1" "@babel/plugin-transform-runtime@^7.16.0": - version "7.16.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.16.4.tgz#f9ba3c7034d429c581e1bd41b4952f3db3c2c7e8" - integrity sha512-pru6+yHANMTukMtEZGC4fs7XPwg35v8sj5CIEmE+gEkFljFiVJxEWxx/7ZDkTK+iZRYo1bFXBtfIN95+K3cJ5A== + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.16.5.tgz#0cc3f01d69f299d5a42cd9ec43b92ea7a777b8db" + integrity sha512-gxpfS8XQWDbQ8oP5NcmpXxtEgCJkbO+W9VhZlOhr0xPyVaRjAQPOv7ZDj9fg0d5s9+NiVvMCE6gbkEkcsxwGRw== dependencies: "@babel/helper-module-imports" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" babel-plugin-polyfill-corejs2 "^0.3.0" babel-plugin-polyfill-corejs3 "^0.4.0" babel-plugin-polyfill-regenerator "^0.3.0" semver "^6.3.0" -"@babel/plugin-transform-shorthand-properties@^7.12.1", "@babel/plugin-transform-shorthand-properties@^7.16.0", "@babel/plugin-transform-shorthand-properties@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.16.0.tgz#090372e3141f7cc324ed70b3daf5379df2fa384d" - integrity sha512-iVb1mTcD8fuhSv3k99+5tlXu5N0v8/DPm2mO3WACLG6al1CGZH7v09HJyUb1TtYl/Z+KrM6pHSIJdZxP5A+xow== +"@babel/plugin-transform-shorthand-properties@^7.12.1", "@babel/plugin-transform-shorthand-properties@^7.16.5", "@babel/plugin-transform-shorthand-properties@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.16.5.tgz#ccb60b1a23b799f5b9a14d97c5bc81025ffd96d7" + integrity sha512-ZbuWVcY+MAXJuuW7qDoCwoxDUNClfZxoo7/4swVbOW1s/qYLOMHlm9YRWMsxMFuLs44eXsv4op1vAaBaBaDMVg== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-spread@^7.12.1", "@babel/plugin-transform-spread@^7.16.0", "@babel/plugin-transform-spread@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-spread/-/plugin-transform-spread-7.16.0.tgz#d21ca099bbd53ab307a8621e019a7bd0f40cdcfb" - integrity sha512-Ao4MSYRaLAQczZVp9/7E7QHsCuK92yHRrmVNRe/SlEJjhzivq0BSn8mEraimL8wizHZ3fuaHxKH0iwzI13GyGg== +"@babel/plugin-transform-spread@^7.12.1", "@babel/plugin-transform-spread@^7.16.5", "@babel/plugin-transform-spread@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-spread/-/plugin-transform-spread-7.16.5.tgz#912b06cff482c233025d3e69cf56d3e8fa166c29" + integrity sha512-5d6l/cnG7Lw4tGHEoga4xSkYp1euP7LAtrah1h1PgJ3JY7yNsjybsxQAnVK4JbtReZ/8z6ASVmd3QhYYKLaKZw== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/helper-skip-transparent-expression-wrappers" "^7.16.0" -"@babel/plugin-transform-sticky-regex@^7.16.0", "@babel/plugin-transform-sticky-regex@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.16.0.tgz#c35ea31a02d86be485f6aa510184b677a91738fd" - integrity sha512-/ntT2NljR9foobKk4E/YyOSwcGUXtYWv5tinMK/3RkypyNBNdhHUaq6Orw5DWq9ZcNlS03BIlEALFeQgeVAo4Q== +"@babel/plugin-transform-sticky-regex@^7.16.5", "@babel/plugin-transform-sticky-regex@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.16.5.tgz#593579bb2b5a8adfbe02cb43823275d9098f75f9" + integrity sha512-usYsuO1ID2LXxzuUxifgWtJemP7wL2uZtyrTVM4PKqsmJycdS4U4mGovL5xXkfUheds10Dd2PjoQLXw6zCsCbg== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-template-literals@^7.12.1", "@babel/plugin-transform-template-literals@^7.16.0", "@babel/plugin-transform-template-literals@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.16.0.tgz#a8eced3a8e7b8e2d40ec4ec4548a45912630d302" - integrity sha512-Rd4Ic89hA/f7xUSJQk5PnC+4so50vBoBfxjdQAdvngwidM8jYIBVxBZ/sARxD4e0yMXRbJVDrYf7dyRtIIKT6Q== +"@babel/plugin-transform-template-literals@^7.12.1", "@babel/plugin-transform-template-literals@^7.16.5", "@babel/plugin-transform-template-literals@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.16.5.tgz#343651385fd9923f5aa2275ca352c5d9183e1773" + integrity sha512-gnyKy9RyFhkovex4BjKWL3BVYzUDG6zC0gba7VMLbQoDuqMfJ1SDXs8k/XK41Mmt1Hyp4qNAvGFb9hKzdCqBRQ== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-typeof-symbol@^7.16.0", "@babel/plugin-transform-typeof-symbol@^7.8.4": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.16.0.tgz#8b19a244c6f8c9d668dca6a6f754ad6ead1128f2" - integrity sha512-++V2L8Bdf4vcaHi2raILnptTBjGEFxn5315YU+e8+EqXIucA+q349qWngCLpUYqqv233suJ6NOienIVUpS9cqg== +"@babel/plugin-transform-typeof-symbol@^7.16.5", "@babel/plugin-transform-typeof-symbol@^7.8.4": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.16.5.tgz#a1d1bf2c71573fe30965d0e4cd6a3291202e20ed" + integrity sha512-ldxCkW180qbrvyCVDzAUZqB0TAeF8W/vGJoRcaf75awm6By+PxfJKvuqVAnq8N9wz5Xa6mSpM19OfVKKVmGHSQ== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-typescript@^7.16.0", "@babel/plugin-transform-typescript@^7.9.0": +"@babel/plugin-transform-typescript@^7.16.1", "@babel/plugin-transform-typescript@^7.9.0": version "7.16.1" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.16.1.tgz#cc0670b2822b0338355bc1b3d2246a42b8166409" integrity sha512-NO4XoryBng06jjw/qWEU2LhcLJr1tWkhpMam/H4eas/CDKMX/b2/Ylb6EI256Y7+FVPCawwSM1rrJNOpDiz+Lg== @@ -1201,20 +1140,20 @@ "@babel/helper-plugin-utils" "^7.14.5" "@babel/plugin-syntax-typescript" "^7.16.0" -"@babel/plugin-transform-unicode-escapes@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-unicode-escapes/-/plugin-transform-unicode-escapes-7.16.0.tgz#1a354064b4c45663a32334f46fa0cf6100b5b1f3" - integrity sha512-VFi4dhgJM7Bpk8lRc5CMaRGlKZ29W9C3geZjt9beuzSUrlJxsNwX7ReLwaL6WEvsOf2EQkyIJEPtF8EXjB/g2A== +"@babel/plugin-transform-unicode-escapes@^7.16.5": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-unicode-escapes/-/plugin-transform-unicode-escapes-7.16.5.tgz#80507c225af49b4f4ee647e2a0ce53d2eeff9e85" + integrity sha512-shiCBHTIIChGLdyojsKQjoAyB8MBwat25lKM7MJjbe1hE0bgIppD+LX9afr41lLHOhqceqeWl4FkLp+Bgn9o1Q== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" -"@babel/plugin-transform-unicode-regex@^7.16.0", "@babel/plugin-transform-unicode-regex@^7.8.3": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.16.0.tgz#293b80950177c8c85aede87cef280259fb995402" - integrity sha512-jHLK4LxhHjvCeZDWyA9c+P9XH1sOxRd1RO9xMtDVRAOND/PczPqizEtVdx4TQF/wyPaewqpT+tgQFYMnN/P94A== +"@babel/plugin-transform-unicode-regex@^7.16.5", "@babel/plugin-transform-unicode-regex@^7.8.3": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.16.5.tgz#ac84d6a1def947d71ffb832426aa53b83d7ed49e" + integrity sha512-GTJ4IW012tiPEMMubd7sD07iU9O/LOo8Q/oU4xNhcaq0Xn8+6TcUQaHtC8YxySo1T+ErQ8RaWogIEeFhKGNPzw== dependencies: "@babel/helper-create-regexp-features-plugin" "^7.16.0" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/preset-env@7.9.0": version "7.9.0" @@ -1283,31 +1222,31 @@ semver "^5.5.0" "@babel/preset-env@^7.12.11", "@babel/preset-env@^7.16.0": - version "7.16.4" - resolved "https://registry.yarnpkg.com/@babel/preset-env/-/preset-env-7.16.4.tgz#4f6ec33b2a3fe72d6bfdcdf3859500232563a2e3" - integrity sha512-v0QtNd81v/xKj4gNKeuAerQ/azeNn/G1B1qMLeXOcV8+4TWlD2j3NV1u8q29SDFBXx/NBq5kyEAO+0mpRgacjA== + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/preset-env/-/preset-env-7.16.5.tgz#2e94d922f4a890979af04ffeb6a6b4e44ba90847" + integrity sha512-MiJJW5pwsktG61NDxpZ4oJ1CKxM1ncam9bzRtx9g40/WkLRkxFP6mhpkYV0/DxcciqoiHicx291+eUQrXb/SfQ== dependencies: "@babel/compat-data" "^7.16.4" "@babel/helper-compilation-targets" "^7.16.3" - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/helper-validator-option" "^7.14.5" "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression" "^7.16.2" "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining" "^7.16.0" - "@babel/plugin-proposal-async-generator-functions" "^7.16.4" - "@babel/plugin-proposal-class-properties" "^7.16.0" - "@babel/plugin-proposal-class-static-block" "^7.16.0" - "@babel/plugin-proposal-dynamic-import" "^7.16.0" - "@babel/plugin-proposal-export-namespace-from" "^7.16.0" - "@babel/plugin-proposal-json-strings" "^7.16.0" - "@babel/plugin-proposal-logical-assignment-operators" "^7.16.0" - "@babel/plugin-proposal-nullish-coalescing-operator" "^7.16.0" - "@babel/plugin-proposal-numeric-separator" "^7.16.0" - "@babel/plugin-proposal-object-rest-spread" "^7.16.0" - "@babel/plugin-proposal-optional-catch-binding" "^7.16.0" - "@babel/plugin-proposal-optional-chaining" "^7.16.0" - "@babel/plugin-proposal-private-methods" "^7.16.0" - "@babel/plugin-proposal-private-property-in-object" "^7.16.0" - "@babel/plugin-proposal-unicode-property-regex" "^7.16.0" + "@babel/plugin-proposal-async-generator-functions" "^7.16.5" + "@babel/plugin-proposal-class-properties" "^7.16.5" + "@babel/plugin-proposal-class-static-block" "^7.16.5" + "@babel/plugin-proposal-dynamic-import" "^7.16.5" + "@babel/plugin-proposal-export-namespace-from" "^7.16.5" + "@babel/plugin-proposal-json-strings" "^7.16.5" + "@babel/plugin-proposal-logical-assignment-operators" "^7.16.5" + "@babel/plugin-proposal-nullish-coalescing-operator" "^7.16.5" + "@babel/plugin-proposal-numeric-separator" "^7.16.5" + "@babel/plugin-proposal-object-rest-spread" "^7.16.5" + "@babel/plugin-proposal-optional-catch-binding" "^7.16.5" + "@babel/plugin-proposal-optional-chaining" "^7.16.5" + "@babel/plugin-proposal-private-methods" "^7.16.5" + "@babel/plugin-proposal-private-property-in-object" "^7.16.5" + "@babel/plugin-proposal-unicode-property-regex" "^7.16.5" "@babel/plugin-syntax-async-generators" "^7.8.4" "@babel/plugin-syntax-class-properties" "^7.12.13" "@babel/plugin-syntax-class-static-block" "^7.14.5" @@ -1322,38 +1261,38 @@ "@babel/plugin-syntax-optional-chaining" "^7.8.3" "@babel/plugin-syntax-private-property-in-object" "^7.14.5" "@babel/plugin-syntax-top-level-await" "^7.14.5" - "@babel/plugin-transform-arrow-functions" "^7.16.0" - "@babel/plugin-transform-async-to-generator" "^7.16.0" - "@babel/plugin-transform-block-scoped-functions" "^7.16.0" - "@babel/plugin-transform-block-scoping" "^7.16.0" - "@babel/plugin-transform-classes" "^7.16.0" - "@babel/plugin-transform-computed-properties" "^7.16.0" - "@babel/plugin-transform-destructuring" "^7.16.0" - "@babel/plugin-transform-dotall-regex" "^7.16.0" - "@babel/plugin-transform-duplicate-keys" "^7.16.0" - "@babel/plugin-transform-exponentiation-operator" "^7.16.0" - "@babel/plugin-transform-for-of" "^7.16.0" - "@babel/plugin-transform-function-name" "^7.16.0" - "@babel/plugin-transform-literals" "^7.16.0" - "@babel/plugin-transform-member-expression-literals" "^7.16.0" - "@babel/plugin-transform-modules-amd" "^7.16.0" - "@babel/plugin-transform-modules-commonjs" "^7.16.0" - "@babel/plugin-transform-modules-systemjs" "^7.16.0" - "@babel/plugin-transform-modules-umd" "^7.16.0" - "@babel/plugin-transform-named-capturing-groups-regex" "^7.16.0" - "@babel/plugin-transform-new-target" "^7.16.0" - "@babel/plugin-transform-object-super" "^7.16.0" - "@babel/plugin-transform-parameters" "^7.16.3" - "@babel/plugin-transform-property-literals" "^7.16.0" - "@babel/plugin-transform-regenerator" "^7.16.0" - "@babel/plugin-transform-reserved-words" "^7.16.0" - "@babel/plugin-transform-shorthand-properties" "^7.16.0" - "@babel/plugin-transform-spread" "^7.16.0" - "@babel/plugin-transform-sticky-regex" "^7.16.0" - "@babel/plugin-transform-template-literals" "^7.16.0" - "@babel/plugin-transform-typeof-symbol" "^7.16.0" - "@babel/plugin-transform-unicode-escapes" "^7.16.0" - "@babel/plugin-transform-unicode-regex" "^7.16.0" + "@babel/plugin-transform-arrow-functions" "^7.16.5" + "@babel/plugin-transform-async-to-generator" "^7.16.5" + "@babel/plugin-transform-block-scoped-functions" "^7.16.5" + "@babel/plugin-transform-block-scoping" "^7.16.5" + "@babel/plugin-transform-classes" "^7.16.5" + "@babel/plugin-transform-computed-properties" "^7.16.5" + "@babel/plugin-transform-destructuring" "^7.16.5" + "@babel/plugin-transform-dotall-regex" "^7.16.5" + "@babel/plugin-transform-duplicate-keys" "^7.16.5" + "@babel/plugin-transform-exponentiation-operator" "^7.16.5" + "@babel/plugin-transform-for-of" "^7.16.5" + "@babel/plugin-transform-function-name" "^7.16.5" + "@babel/plugin-transform-literals" "^7.16.5" + "@babel/plugin-transform-member-expression-literals" "^7.16.5" + "@babel/plugin-transform-modules-amd" "^7.16.5" + "@babel/plugin-transform-modules-commonjs" "^7.16.5" + "@babel/plugin-transform-modules-systemjs" "^7.16.5" + "@babel/plugin-transform-modules-umd" "^7.16.5" + "@babel/plugin-transform-named-capturing-groups-regex" "^7.16.5" + "@babel/plugin-transform-new-target" "^7.16.5" + "@babel/plugin-transform-object-super" "^7.16.5" + "@babel/plugin-transform-parameters" "^7.16.5" + "@babel/plugin-transform-property-literals" "^7.16.5" + "@babel/plugin-transform-regenerator" "^7.16.5" + "@babel/plugin-transform-reserved-words" "^7.16.5" + "@babel/plugin-transform-shorthand-properties" "^7.16.5" + "@babel/plugin-transform-spread" "^7.16.5" + "@babel/plugin-transform-sticky-regex" "^7.16.5" + "@babel/plugin-transform-template-literals" "^7.16.5" + "@babel/plugin-transform-typeof-symbol" "^7.16.5" + "@babel/plugin-transform-unicode-escapes" "^7.16.5" + "@babel/plugin-transform-unicode-regex" "^7.16.5" "@babel/preset-modules" "^0.1.5" "@babel/types" "^7.16.0" babel-plugin-polyfill-corejs2 "^0.3.0" @@ -1363,13 +1302,13 @@ semver "^6.3.0" "@babel/preset-flow@^7.12.1": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/preset-flow/-/preset-flow-7.16.0.tgz#9f1f6e72714d79460d48058cb5658fc87da7150b" - integrity sha512-e5NE1EoPMpoHFkyFkMSj2h9tu7OolARcUHki8mnBv4NiFK9so+UrhbvT9mV99tMJOUEx8BOj67T6dXvGcTeYeQ== + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/preset-flow/-/preset-flow-7.16.5.tgz#fed36ad84ed09f6df41a37b372d3933fc58d0885" + integrity sha512-rmC6Nznp4V55N4Zfec87jwd14TdREqwKVJFM/6Z2wTwoeZQr56czjaPRCezqzqc8TsHF7aLP1oczjadIQ058gw== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/helper-validator-option" "^7.14.5" - "@babel/plugin-transform-flow-strip-types" "^7.16.0" + "@babel/plugin-transform-flow-strip-types" "^7.16.5" "@babel/preset-modules@^0.1.3", "@babel/preset-modules@^0.1.5": version "0.1.5" @@ -1395,16 +1334,16 @@ "@babel/plugin-transform-react-jsx-source" "^7.9.0" "@babel/preset-react@^7.12.10", "@babel/preset-react@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/preset-react/-/preset-react-7.16.0.tgz#f71d3e8dff5218478011df037fad52660ee6d82a" - integrity sha512-d31IFW2bLRB28uL1WoElyro8RH5l6531XfxMtCeCmp6RVAF1uTfxxUA0LH1tXl+psZdwfmIbwoG4U5VwgbhtLw== + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/preset-react/-/preset-react-7.16.5.tgz#09df3b7a6522cb3e6682dc89b4dfebb97d22031b" + integrity sha512-3kzUOQeaxY/2vhPDS7CX/KGEGu/1bOYGvdRDJ2U5yjEz5o5jmIeTPLoiQBPGjfhPascLuW5OlMiPzwOOuB6txg== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/helper-validator-option" "^7.14.5" - "@babel/plugin-transform-react-display-name" "^7.16.0" - "@babel/plugin-transform-react-jsx" "^7.16.0" - "@babel/plugin-transform-react-jsx-development" "^7.16.0" - "@babel/plugin-transform-react-pure-annotations" "^7.16.0" + "@babel/plugin-transform-react-display-name" "^7.16.5" + "@babel/plugin-transform-react-jsx" "^7.16.5" + "@babel/plugin-transform-react-jsx-development" "^7.16.5" + "@babel/plugin-transform-react-pure-annotations" "^7.16.5" "@babel/preset-typescript@7.9.0": version "7.9.0" @@ -1415,18 +1354,18 @@ "@babel/plugin-transform-typescript" "^7.9.0" "@babel/preset-typescript@^7.12.7", "@babel/preset-typescript@^7.15.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/preset-typescript/-/preset-typescript-7.16.0.tgz#b0b4f105b855fb3d631ec036cdc9d1ffd1fa5eac" - integrity sha512-txegdrZYgO9DlPbv+9QOVpMnKbOtezsLHWsnsRF4AjbSIsVaujrq1qg8HK0mxQpWv0jnejt0yEoW1uWpvbrDTg== + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/preset-typescript/-/preset-typescript-7.16.5.tgz#b86a5b0ae739ba741347d2f58c52f52e63cf1ba1" + integrity sha512-lmAWRoJ9iOSvs3DqOndQpj8XqXkzaiQs50VG/zESiI9D3eoZhGriU675xNCr0UwvsuXrhMAGvyk1w+EVWF3u8Q== dependencies: - "@babel/helper-plugin-utils" "^7.14.5" + "@babel/helper-plugin-utils" "^7.16.5" "@babel/helper-validator-option" "^7.14.5" - "@babel/plugin-transform-typescript" "^7.16.0" + "@babel/plugin-transform-typescript" "^7.16.1" "@babel/register@^7.12.1": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/register/-/register-7.16.0.tgz#f5d2aa14df37cf7146b9759f7c53818360f24ec6" - integrity sha512-lzl4yfs0zVXnooeLE0AAfYaT7F3SPA8yB2Bj4W1BiZwLbMS3MZH35ZvCWSRHvneUugwuM+Wsnrj7h0F7UmU3NQ== + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/register/-/register-7.16.5.tgz#657d28b7ca68190de8f6159245b5ed1cfa181640" + integrity sha512-NpluD+cToBiZiDsG3y9rtIcqDyivsahpaM9csfyfiq1qQWduSmihUZ+ruIqqSDGjZKZMJfgAElo9x2YWlOQuRw== dependencies: clone-deep "^4.0.1" find-cache-dir "^2.0.0" @@ -1435,9 +1374,9 @@ source-map-support "^0.5.16" "@babel/runtime-corejs3@^7.10.2": - version "7.16.3" - resolved "https://registry.yarnpkg.com/@babel/runtime-corejs3/-/runtime-corejs3-7.16.3.tgz#1e25de4fa994c57c18e5fdda6cc810dac70f5590" - integrity sha512-IAdDC7T0+wEB4y2gbIL0uOXEYpiZEeuFUTVbdGq+UwCcF35T/tS8KrmMomEwEc5wBbyfH3PJVpTSUqrhPDXFcQ== + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/runtime-corejs3/-/runtime-corejs3-7.16.5.tgz#9057d879720c136193f0440bc400088212a74894" + integrity sha512-F1pMwvTiUNSAM8mc45kccMQxj31x3y3P+tA/X8hKNWp3/hUsxdGxZ3D3H8JIkxtfA8qGkaBTKvcmvStaYseAFw== dependencies: core-js-pure "^3.19.0" regenerator-runtime "^0.13.4" @@ -1456,14 +1395,7 @@ dependencies: regenerator-runtime "^0.13.4" -"@babel/runtime@^7.0.0", "@babel/runtime@^7.1.2", "@babel/runtime@^7.10.2", "@babel/runtime@^7.10.3", "@babel/runtime@^7.11.2", "@babel/runtime@^7.12.0", "@babel/runtime@^7.12.5", "@babel/runtime@^7.13.10", "@babel/runtime@^7.13.17", "@babel/runtime@^7.13.8", "@babel/runtime@^7.14.5", "@babel/runtime@^7.14.6", "@babel/runtime@^7.14.8", "@babel/runtime@^7.15.3", "@babel/runtime@^7.16.0", "@babel/runtime@^7.16.3", "@babel/runtime@^7.2.0", "@babel/runtime@^7.3.1", "@babel/runtime@^7.5.0", "@babel/runtime@^7.7.2", "@babel/runtime@^7.7.6", "@babel/runtime@^7.8.4", "@babel/runtime@^7.9.2": - version "7.16.3" - resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.16.3.tgz#b86f0db02a04187a3c17caa77de69840165d42d5" - integrity sha512-WBwekcqacdY2e9AF/Q7WLFUWmdJGJTkbjqTjoMDgXkVZ3ZRUvOPsLb5KdwISoQVsbP+DQzVZW4Zhci0DvpbNTQ== - dependencies: - regenerator-runtime "^0.13.4" - -"@babel/runtime@^7.13.16", "@babel/runtime@^7.14.0", "@babel/runtime@^7.5.5", "@babel/runtime@^7.6.2", "@babel/runtime@^7.6.3", "@babel/runtime@^7.8.7": +"@babel/runtime@^7.0.0", "@babel/runtime@^7.1.2", "@babel/runtime@^7.10.2", "@babel/runtime@^7.10.3", "@babel/runtime@^7.11.2", "@babel/runtime@^7.12.0", "@babel/runtime@^7.12.5", "@babel/runtime@^7.13.10", "@babel/runtime@^7.13.16", "@babel/runtime@^7.13.17", "@babel/runtime@^7.13.8", "@babel/runtime@^7.14.0", "@babel/runtime@^7.14.5", "@babel/runtime@^7.14.6", "@babel/runtime@^7.14.8", "@babel/runtime@^7.15.3", "@babel/runtime@^7.16.0", "@babel/runtime@^7.16.3", "@babel/runtime@^7.2.0", "@babel/runtime@^7.3.1", "@babel/runtime@^7.5.0", "@babel/runtime@^7.5.5", "@babel/runtime@^7.6.2", "@babel/runtime@^7.6.3", "@babel/runtime@^7.7.2", "@babel/runtime@^7.7.6", "@babel/runtime@^7.8.4", "@babel/runtime@^7.8.7", "@babel/runtime@^7.9.2": version "7.16.5" resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.16.5.tgz#7f3e34bf8bdbbadf03fbb7b1ea0d929569c9487a" integrity sha512-TXWihFIS3Pyv5hzR7j6ihmeLkZfrXGxAr5UfSl8CHf+6q/wpiYDkUau0czckpYG8QmnCIuPpdLtuA9VmuGGyMA== @@ -1477,35 +1409,20 @@ dependencies: "@babel/code-frame" "^7.16.0" "@babel/parser" "^7.16.0" - "@babel/types" "^7.16.0" - -"@babel/traverse@^7.1.0", "@babel/traverse@^7.16.0", "@babel/traverse@^7.16.3", "@babel/traverse@^7.16.5": - version "7.16.5" - resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.16.5.tgz#d7d400a8229c714a59b87624fc67b0f1fbd4b2b3" - integrity sha512-FOCODAzqUMROikDYLYxl4nmwiLlu85rNqBML/A5hKRVXG2LV8d0iMqgPzdYTcIpjZEBB7D6UDU9vxRZiriASdQ== - dependencies: - "@babel/code-frame" "^7.16.0" - "@babel/generator" "^7.16.5" - "@babel/helper-environment-visitor" "^7.16.5" - "@babel/helper-function-name" "^7.16.0" - "@babel/helper-hoist-variables" "^7.16.0" - "@babel/helper-split-export-declaration" "^7.16.0" - "@babel/parser" "^7.16.5" - "@babel/types" "^7.16.0" - debug "^4.1.0" - globals "^11.1.0" + "@babel/types" "^7.16.0" -"@babel/traverse@^7.1.6", "@babel/traverse@^7.12.11", "@babel/traverse@^7.12.9", "@babel/traverse@^7.13.0", "@babel/traverse@^7.9.0": - version "7.16.3" - resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.16.3.tgz#f63e8a938cc1b780f66d9ed3c54f532ca2d14787" - integrity sha512-eolumr1vVMjqevCpwVO99yN/LoGL0EyHiLO5I043aYQvwOJ9eR5UsZSClHVCzfhBduMAsSzgA/6AyqPjNayJag== +"@babel/traverse@^7.1.0", "@babel/traverse@^7.1.6", "@babel/traverse@^7.12.11", "@babel/traverse@^7.12.9", "@babel/traverse@^7.13.0", "@babel/traverse@^7.16.5", "@babel/traverse@^7.9.0": + version "7.16.5" + resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.16.5.tgz#d7d400a8229c714a59b87624fc67b0f1fbd4b2b3" + integrity sha512-FOCODAzqUMROikDYLYxl4nmwiLlu85rNqBML/A5hKRVXG2LV8d0iMqgPzdYTcIpjZEBB7D6UDU9vxRZiriASdQ== dependencies: "@babel/code-frame" "^7.16.0" - "@babel/generator" "^7.16.0" + "@babel/generator" "^7.16.5" + "@babel/helper-environment-visitor" "^7.16.5" "@babel/helper-function-name" "^7.16.0" "@babel/helper-hoist-variables" "^7.16.0" "@babel/helper-split-export-declaration" "^7.16.0" - "@babel/parser" "^7.16.3" + "@babel/parser" "^7.16.5" "@babel/types" "^7.16.0" debug "^4.1.0" globals "^11.1.0" @@ -1555,9 +1472,9 @@ minimist "^1.2.0" "@corex/deepmerge@^2.6.34": - version "2.6.34" - resolved "https://registry.yarnpkg.com/@corex/deepmerge/-/deepmerge-2.6.34.tgz#8dd084f2bcc9cf54f6b1210a1aebd25206de2a84" - integrity sha512-5l3bQRGOoCJ1nYTxEaOW/MRuwNDq32KYatWO5rwOlOzxY4beVCrxDBaDBX5wpDn0PYm0QAul/vAC9GDHShEbTw== + version "2.6.148" + resolved "https://registry.yarnpkg.com/@corex/deepmerge/-/deepmerge-2.6.148.tgz#8fa825d53ffd1cbcafce1b6a830eefd3dcc09dd5" + integrity sha512-6QMz0/2h5C3ua51iAnXMPWFbb1QOU1UvSM4bKBw5mzdT+WtLgjbETBBIQZ+Sh9WvEcGwlAt/DEdRpIC3XlDBMA== "@cypress/browserify-preprocessor@3.0.2": version "3.0.2" @@ -1598,7 +1515,7 @@ js-yaml "3.14.1" nyc "15.1.0" -"@cypress/request@^2.88.7": +"@cypress/request@^2.88.10": version "2.88.10" resolved "https://registry.yarnpkg.com/@cypress/request/-/request-2.88.10.tgz#b66d76b07f860d3a4b8d7a0604d020c662752cce" integrity sha512-Zp7F+R93N0yZyG34GutyTNr+okam7s/Fzc1+i3kcqOP8vk6OuajuE9qZJ6Rs+10/1JFtXFYMdyarnU1rZuJesg== @@ -1623,12 +1540,12 @@ uuid "^8.3.2" "@cypress/webpack-preprocessor@^5.4.1": - version "5.10.0" - resolved "https://registry.yarnpkg.com/@cypress/webpack-preprocessor/-/webpack-preprocessor-5.10.0.tgz#477eee82c04caec956a07e51d2d90a9947ed6d7e" - integrity sha512-KzcDBjos3rIw58imyvATYTNi9CB+Co0SFUhexmuH2c+Wk1ksSM3g4XmxUUIaJJvDwmIK4tcoBMYd9Lzle8bR7A== + version "5.11.0" + resolved "https://registry.yarnpkg.com/@cypress/webpack-preprocessor/-/webpack-preprocessor-5.11.0.tgz#f616a208b12b83636331d3421caa1574a7e0bd0c" + integrity sha512-0VMEodVAOkYYhCGKQ2wilI28RtISc3rCre9wlFhishwtnT0B1onJJ8fwhWmcT3Y2/K88WP+cyVO2ZaQPcsEFQg== dependencies: - bluebird "^3.7.1" - debug "4.3.2" + bluebird "3.7.1" + debug "^4.3.2" lodash "^4.17.20" "@cypress/xvfb@^1.2.4": @@ -1645,9 +1562,9 @@ integrity sha512-ws57AidsDvREKrZKYffXddNkyaF14iHNHm8VQnZH6t99E8gczjNN0GpvcGny0imC80yQ0tHz1xVUKk/KFQSUyA== "@emotion/babel-plugin@^11.3.0": - version "11.3.0" - resolved "https://registry.yarnpkg.com/@emotion/babel-plugin/-/babel-plugin-11.3.0.tgz#3a16850ba04d8d9651f07f3fb674b3436a4fb9d7" - integrity sha512-UZKwBV2rADuhRp+ZOGgNWg2eYgbzKzQXfQPtJbu/PLy8onurxlNCLvxMQEvlr1/GudguPI5IU9qIY1+2z1M5bA== + version "11.7.2" + resolved "https://registry.yarnpkg.com/@emotion/babel-plugin/-/babel-plugin-11.7.2.tgz#fec75f38a6ab5b304b0601c74e2a5e77c95e5fa0" + integrity sha512-6mGSCWi9UzXut/ZAN6lGFu33wGR3SJisNl3c0tvlmb8XChH1b2SUvxvnOh7hvLpqyRdHHU9AiazV3Cwbk5SXKQ== dependencies: "@babel/helper-module-imports" "^7.12.13" "@babel/plugin-syntax-jsx" "^7.12.13" @@ -1660,7 +1577,7 @@ escape-string-regexp "^4.0.0" find-root "^1.1.0" source-map "^0.5.7" - stylis "^4.0.3" + stylis "4.0.13" "@emotion/cache@^10.0.27": version "10.0.29" @@ -1672,21 +1589,21 @@ "@emotion/utils" "0.11.3" "@emotion/weak-memoize" "0.2.5" -"@emotion/cache@^11.4.0", "@emotion/cache@^11.6.0": - version "11.6.0" - resolved "https://registry.yarnpkg.com/@emotion/cache/-/cache-11.6.0.tgz#65fbdbbe4382f1991d8b20853c38e63ecccec9a1" - integrity sha512-ElbsWY1KMwEowkv42vGo0UPuLgtPYfIs9BxxVrmvsaJVvktknsHYYlx5NQ5g6zLDcOTyamlDc7FkRg2TAcQDKQ== +"@emotion/cache@^11.4.0", "@emotion/cache@^11.7.1": + version "11.7.1" + resolved "https://registry.yarnpkg.com/@emotion/cache/-/cache-11.7.1.tgz#08d080e396a42e0037848214e8aa7bf879065539" + integrity sha512-r65Zy4Iljb8oyjtLeCuBH8Qjiy107dOYC6SJq7g7GV5UCQWMObY4SJDPGFjiiVpPrOJ2hmJOoBiYTC7hwx9E2A== dependencies: "@emotion/memoize" "^0.7.4" "@emotion/sheet" "^1.1.0" "@emotion/utils" "^1.0.0" "@emotion/weak-memoize" "^0.2.5" - stylis "^4.0.10" + stylis "4.0.13" "@emotion/core@^10.1.1": - version "10.3.0" - resolved "https://registry.yarnpkg.com/@emotion/core/-/core-10.3.0.tgz#d027fce912e2f8e03eb61cb67e52df964e52950f" - integrity sha512-C4+RI1gNycUbfg2Zojt3lcVQVWocMLK4jiwl5tO/Z5I3zyGmG+oKJl6+/uPtQeUDPN7WXHN8TQ7bqc+dnljZ0w== + version "10.3.1" + resolved "https://registry.yarnpkg.com/@emotion/core/-/core-10.3.1.tgz#4021b6d8b33b3304d48b0bb478485e7d7421c69d" + integrity sha512-447aUEjPIm0MnE6QYIaFz9VQOHSXf4Iu6EWOIqq11EAPqinkSZmfymPTmlOE3QjLv846lH4JVZBUOtwGbuQoww== dependencies: "@babel/runtime" "^7.5.5" "@emotion/cache" "^10.0.27" @@ -1734,12 +1651,12 @@ integrity sha512-igX9a37DR2ZPGYtV6suZ6whr8pTFtyHL3K/oLUotxpSVO2ASaprmAe2Dkq7tBo7CRY7MMDrAa9nuQP9/YG8FxQ== "@emotion/react@^11.4.1": - version "11.7.0" - resolved "https://registry.yarnpkg.com/@emotion/react/-/react-11.7.0.tgz#b179da970ac0e8415de3ac165deadf8d9c4bf89f" - integrity sha512-WL93hf9+/2s3cA1JVJlz8+Uy6p6QWukqQFOm2OZO5ki51hfucHMOmbSjiyC3t2Y4RI8XUmBoepoc/24ny/VBbA== + version "11.7.1" + resolved "https://registry.yarnpkg.com/@emotion/react/-/react-11.7.1.tgz#3f800ce9b20317c13e77b8489ac4a0b922b2fe07" + integrity sha512-DV2Xe3yhkF1yT4uAUoJcYL1AmrnO5SVsdfvu+fBuS7IbByDeTVx9+wFmvx9Idzv7/78+9Mgx2Hcmr7Fex3tIyw== dependencies: "@babel/runtime" "^7.13.10" - "@emotion/cache" "^11.6.0" + "@emotion/cache" "^11.7.1" "@emotion/serialize" "^1.0.2" "@emotion/sheet" "^1.1.0" "@emotion/utils" "^1.0.0" @@ -1988,9 +1905,9 @@ resolve-from "^5.0.0" "@istanbuljs/nyc-config-typescript@^1.0.1": - version "1.0.1" - resolved "https://registry.yarnpkg.com/@istanbuljs/nyc-config-typescript/-/nyc-config-typescript-1.0.1.tgz#55172f5663b3635586add21b14d42ca94a163d58" - integrity sha512-/gz6LgVpky205LuoOfwEZmnUtaSmdk0QIMcNFj9OvxhiMhPpKftMgZmGN7jNj7jR+lr8IB1Yks3QSSSNSxfoaQ== + version "1.0.2" + resolved "https://registry.yarnpkg.com/@istanbuljs/nyc-config-typescript/-/nyc-config-typescript-1.0.2.tgz#1f5235b28540a07219ae0dd42014912a0b19cf89" + integrity sha512-iKGIyMoyJuFnJRSVTZ78POIRvNnwZaWIf8vG4ZS3rQq58MMDrqEX2nnzx0R28V2X8JvmKYiqY9FP2hlJsm8A0w== dependencies: "@istanbuljs/schema" "^0.1.2" @@ -2335,36 +2252,36 @@ outvariant "^1.2.0" strict-event-emitter "^0.2.0" -"@mui/base@5.0.0-alpha.58": - version "5.0.0-alpha.58" - resolved "https://registry.yarnpkg.com/@mui/base/-/base-5.0.0-alpha.58.tgz#01ab59a028f314e2f9a79f903a8336ac45853652" - integrity sha512-YZorCbbzkokQZUnj+sdjUWIe+jaesuSVpKgwWS2mWdE50v1Ti/qMmevIrOT1lvFAilpj80Bkcg4KtlGWBJ6utQ== +"@mui/base@5.0.0-alpha.62": + version "5.0.0-alpha.62" + resolved "https://registry.yarnpkg.com/@mui/base/-/base-5.0.0-alpha.62.tgz#d86ff07f33d7b49ebb545f29e184750c0270c3f8" + integrity sha512-ItmdSZwHKQbLbAsS3sWguR7OHqYqh2cYWahoVmHb13Kc6bMdmVUTY4x57IlDSU712B0yuA0Q/gPTq7xADKnFow== dependencies: "@babel/runtime" "^7.16.3" "@emotion/is-prop-valid" "^1.1.1" - "@mui/utils" "^5.2.2" + "@mui/utils" "^5.2.3" "@popperjs/core" "^2.4.4" clsx "^1.1.1" prop-types "^15.7.2" react-is "^17.0.2" "@mui/icons-material@^5.0.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@mui/icons-material/-/icons-material-5.2.0.tgz#6c6135bb2d7891e29d6f9419df402b82dd663517" - integrity sha512-NvyrVaGKpP4R1yFw8BCnE0QcsQ67RtpgxPr4FtH8q60MDYPuPVczLOn5Ash5CFavoDWur/NfM/4DpT54yf3InA== + version "5.2.5" + resolved "https://registry.yarnpkg.com/@mui/icons-material/-/icons-material-5.2.5.tgz#c6575430b565c023232147934c45775630a53f02" + integrity sha512-uQiUz+l0xy+2jExyKyU19MkMAR2F7bQFcsQ5hdqAtsB14Jw2zlmIAD55mV6f0NxKCut7Rx6cA3ZpfzlzAfoK8Q== dependencies: "@babel/runtime" "^7.16.3" "@mui/material@^5.0.0": - version "5.2.2" - resolved "https://registry.yarnpkg.com/@mui/material/-/material-5.2.2.tgz#4dfbc9186a83e16a9dcdcc10e4a70ecaf641b1a3" - integrity sha512-vqmZq+v59CT4V84WcvYkYldnjC6uRddYx0TJqgl2h5YRbbPYCGVVywVvg9cBwxy4j5xI3F2WH6z7WGkHqkJIQA== + version "5.2.6" + resolved "https://registry.yarnpkg.com/@mui/material/-/material-5.2.6.tgz#fda165759281fe7d6f0ec2744a255f283e17b7aa" + integrity sha512-yF2bRqyJMo6bYXT7TPA9IU/XLaXHi47Xvmj8duQa5ha3bCpFMXLfGoZcAUl6ZDjjGEz1nCFS+c1qx219xD/aeQ== dependencies: "@babel/runtime" "^7.16.3" - "@mui/base" "5.0.0-alpha.58" - "@mui/system" "^5.2.2" + "@mui/base" "5.0.0-alpha.62" + "@mui/system" "^5.2.6" "@mui/types" "^7.1.0" - "@mui/utils" "^5.2.2" + "@mui/utils" "^5.2.3" "@types/react-transition-group" "^4.4.4" clsx "^1.1.1" csstype "^3.0.10" @@ -2373,34 +2290,34 @@ react-is "^17.0.2" react-transition-group "^4.4.2" -"@mui/private-theming@^5.2.2": - version "5.2.2" - resolved "https://registry.yarnpkg.com/@mui/private-theming/-/private-theming-5.2.2.tgz#ede801bc4b6939aedf5900edcece981fde8fa210" - integrity sha512-BfTjZ5ao6KY4Sg11lgaVuQ9uUq8unaM2u9/RKDD12If0B2Vp/AhRSe7i5OTd+wErmK2guTX0kPSraGZzwDEIVg== +"@mui/private-theming@^5.2.3": + version "5.2.3" + resolved "https://registry.yarnpkg.com/@mui/private-theming/-/private-theming-5.2.3.tgz#6d4e7d8309adc932b444fdd091caec339c430be4" + integrity sha512-Lc1Cmu8lSsYZiXADi9PBb17Ho82ZbseHQujUFAcp6bCJ5x/d+87JYCIpCBMagPu/isRlFCwbziuXPmz7WOzJPQ== dependencies: "@babel/runtime" "^7.16.3" - "@mui/utils" "^5.2.2" + "@mui/utils" "^5.2.3" prop-types "^15.7.2" -"@mui/styled-engine@^5.2.0": - version "5.2.0" - resolved "https://registry.yarnpkg.com/@mui/styled-engine/-/styled-engine-5.2.0.tgz#5c97e2b1b6c4c2d9991f07517ed862972d362b85" - integrity sha512-NZ4pWYQcM5wreUfiXRd7IMFRF+Nq1vMzsIdXtXNjgctJTKHunrofasoBqv+cqevO+hqT75ezSbNHyaXzOXp6Mg== +"@mui/styled-engine@^5.2.6": + version "5.2.6" + resolved "https://registry.yarnpkg.com/@mui/styled-engine/-/styled-engine-5.2.6.tgz#eac4a98b05b17190c2155b31b0e36338b3fb09f2" + integrity sha512-bqAhli8eGS6v2qxivy2/4K0Ag8o//jsu1G2G6QcieFiT6y7oIF/nd/6Tvw6OSm3roOTifVQWNKwkt1yFWhGS+w== dependencies: "@babel/runtime" "^7.16.3" - "@emotion/cache" "^11.6.0" + "@emotion/cache" "^11.7.1" prop-types "^15.7.2" -"@mui/system@^5.2.2": - version "5.2.2" - resolved "https://registry.yarnpkg.com/@mui/system/-/system-5.2.2.tgz#81ef74f0c269d18b99a2d0253833d6554bbf5198" - integrity sha512-221tPOcZC8A89GOt6LH9YPTj2Iqf880iqrHd7AHT/HznBKOlLrnWD83pCuLPyX2jeFz4OzhvmGbdt5a74UEgaA== +"@mui/system@^5.2.6": + version "5.2.6" + resolved "https://registry.yarnpkg.com/@mui/system/-/system-5.2.6.tgz#153b534223caae254a98162eef06d6ab48ecff34" + integrity sha512-PZ7bmpWOLikWgqn2zWv9/Xa7lxnRBOmfjoMH7c/IVYJs78W3971brXJ3xV9MEWWQcoqiYQeXzUJaNf4rFbKCBA== dependencies: "@babel/runtime" "^7.16.3" - "@mui/private-theming" "^5.2.2" - "@mui/styled-engine" "^5.2.0" + "@mui/private-theming" "^5.2.3" + "@mui/styled-engine" "^5.2.6" "@mui/types" "^7.1.0" - "@mui/utils" "^5.2.2" + "@mui/utils" "^5.2.3" clsx "^1.1.1" csstype "^3.0.10" prop-types "^15.7.2" @@ -2410,10 +2327,10 @@ resolved "https://registry.yarnpkg.com/@mui/types/-/types-7.1.0.tgz#5ed928c5a41cfbf9a4be82ea3bbdc47bcc9610d5" integrity sha512-Hh7ALdq/GjfIwLvqH3XftuY3bcKhupktTm+S6qRIDGOtPtRuq2L21VWzOK4p7kblirK0XgGVH5BLwa6u8z/6QQ== -"@mui/utils@^5.2.2": - version "5.2.2" - resolved "https://registry.yarnpkg.com/@mui/utils/-/utils-5.2.2.tgz#972aab7d2564e77c06e0c3c11e7b1aec6e37c927" - integrity sha512-0u9ImUfpCfTxmvQTfUzTSS+jKWMX15MBZeZCRQZ0f7o9Yi8BlrLj33lMx0mFBkUSYdTXnqL4yfOn7RBzV01HMQ== +"@mui/utils@^5.2.3": + version "5.2.3" + resolved "https://registry.yarnpkg.com/@mui/utils/-/utils-5.2.3.tgz#994f3a500679804483732596fcfa531e59c56445" + integrity sha512-sQujlajIS0zQKcGIS6tZR0L1R+ib26B6UtuEn+cZqwKHsPo3feuS+SkdscYBdcCdMbrZs4gj8WIJHl2z6tbSzQ== dependencies: "@babel/runtime" "^7.16.3" "@types/prop-types" "^15.7.4" @@ -2433,15 +2350,15 @@ dependencies: webpack-bundle-analyzer "3.6.1" -"@next/env@12.0.4": - version "12.0.4" - resolved "https://registry.yarnpkg.com/@next/env/-/env-12.0.4.tgz#effe19526fa51ab2da1a39e594b80a257b3fa1c5" - integrity sha512-QtZ6X5c6Zqa7oWs5csEmZ7xy+gLdtRKKg02SOT5l0Ziea4P5IU8mSOCyNC4fZmXewcRVjpbY+yGqAAP7hJUfOA== +"@next/env@12.0.7": + version "12.0.7" + resolved "https://registry.yarnpkg.com/@next/env/-/env-12.0.7.tgz#316f7bd1b6b69f554d2676cfc91a16bc7e32ee79" + integrity sha512-TNDqBV37wd95SiNdZsSUq8gnnrTwr+aN9wqy4Zxrxw4bC/jCHNsbK94DxjkG99VL30VCRXXDBTA1/Wa2jIpF9Q== -"@next/eslint-plugin-next@11.1.2": - version "11.1.2" - resolved "https://registry.yarnpkg.com/@next/eslint-plugin-next/-/eslint-plugin-next-11.1.2.tgz#f26cf90bcb6cd2e4645e2ba253bbc9aaaa43a170" - integrity sha512-cN+ojHRsufr9Yz0rtvjv8WI5En0RPZRJnt0y16Ha7DD+0n473evz8i1ETEJHmOLeR7iPJR0zxRrxeTN/bJMOjg== +"@next/eslint-plugin-next@11.1.3": + version "11.1.3" + resolved "https://registry.yarnpkg.com/@next/eslint-plugin-next/-/eslint-plugin-next-11.1.3.tgz#3d1c5be05dea39a59549ce624711d114c39f6a78" + integrity sha512-hsQJUAyvxI8IUXEExhYi4py1MtOMydVdEgFhIdTTiHUI30bh3vGYH/ZuQ8njHJrE5WeVZ7YBlTX0muPOer1kOQ== dependencies: glob "7.1.7" @@ -2451,19 +2368,19 @@ integrity sha512-hseekptFqOCxLbdaNDS/yelaG2Q2uaNDilnRjq8Uv/LWHuZ9F2cp7ndwTolW9acJsbDedamKRMgdw4V2Fz0pUA== "@next/plugin-storybook@^11.1.0": - version "11.1.2" - resolved "https://registry.yarnpkg.com/@next/plugin-storybook/-/plugin-storybook-11.1.2.tgz#8628a0cc7e912dbfa5e37a5f2122a81527e1a8e8" - integrity sha512-92u2K392Xt8wfzqocd49HfzDZ4KenqFFC63s2S+oA/eH1ICkEg8oU0Pq6A+myjHUsfP3pgY0Wf5K2wLzMBCBgg== + version "11.1.3" + resolved "https://registry.yarnpkg.com/@next/plugin-storybook/-/plugin-storybook-11.1.3.tgz#71aad411f86e21473d37b4490fe729e2accca944" + integrity sha512-jIOXJyabJ7W7gEa6XpiHkRNPJWk26Ti/lfNeH8W63mAF4jF++/4N4inUWyNMnTPba13niYJpgzF5R9T9RdOrWw== -"@next/polyfill-module@12.0.4": - version "12.0.4" - resolved "https://registry.yarnpkg.com/@next/polyfill-module/-/polyfill-module-12.0.4.tgz#ef4f4fd6d773ad655db1859ca71127e0c358af50" - integrity sha512-mk9yCDNpfXINTJKFTZNgwYs7eqRFpc5D/49O/fKB59blihyKl1GY1sZ0l7a2bn5l1X/WuaZzcIfqnrwkneqeaQ== +"@next/polyfill-module@12.0.7": + version "12.0.7" + resolved "https://registry.yarnpkg.com/@next/polyfill-module/-/polyfill-module-12.0.7.tgz#140e698557113cd3a3c0833f15ca8af1b608f2dc" + integrity sha512-sA8LAMMlmcspIZw/jeQuJTyA3uGrqOhTBaQE+G9u6DPohqrBFRkaz7RzzJeqXkUXw600occsIBknSjyVd1R67A== -"@next/react-dev-overlay@12.0.4": - version "12.0.4" - resolved "https://registry.yarnpkg.com/@next/react-dev-overlay/-/react-dev-overlay-12.0.4.tgz#c97113df84986233c62eed37382aab85a0ec006e" - integrity sha512-9O0lXyzv5goFSmDwq9Hp8JE+DcObvd+bTXvmGSSvYR91AlIoVlH8/PwATx8Rf5YEuqggn/XKR1hn2kBYcbcGnA== +"@next/react-dev-overlay@12.0.7": + version "12.0.7" + resolved "https://registry.yarnpkg.com/@next/react-dev-overlay/-/react-dev-overlay-12.0.7.tgz#ae8f9bd14b1786e52330b729ff63061735d21c77" + integrity sha512-dSQLgpZ5uzyittFtIHlJCLAbc0LlMFbRBSYuGsIlrtGyjYN+WMcnz8lK48VLxNPFGuB/hEzkWV4TW5Zu75+Fzg== dependencies: "@babel/code-frame" "7.12.11" anser "1.4.9" @@ -2477,65 +2394,65 @@ stacktrace-parser "0.1.10" strip-ansi "6.0.1" -"@next/react-refresh-utils@12.0.4": - version "12.0.4" - resolved "https://registry.yarnpkg.com/@next/react-refresh-utils/-/react-refresh-utils-12.0.4.tgz#20d43626498c451f71bb0bb26c3f780ad90f5fd6" - integrity sha512-kNUDmpBaJ+8Lb8CtKNynRFF9oijCjUKKru6Ont+JKhti9//5dNFFIcuo607bJSH86un06OEK0TZUt5XWVlbkjw== - -"@next/swc-android-arm64@12.0.4": - version "12.0.4" - resolved "https://registry.yarnpkg.com/@next/swc-android-arm64/-/swc-android-arm64-12.0.4.tgz#e3ad69d3aadbd1d3ff0768b4f02b66c3806aa6b2" - integrity sha512-6mXumia8ZPcy7bYu9kjItfWxrE6SFaJyqQDaFy9G9WrU9x3M1R1Yok8B2X1mboM8itD0tq+t3R/ebQEkkmevUw== - -"@next/swc-darwin-arm64@12.0.4": - version "12.0.4" - resolved "https://registry.yarnpkg.com/@next/swc-darwin-arm64/-/swc-darwin-arm64-12.0.4.tgz#bc083ed3ad5e6971d2f374f38a7d8f3c46a6de0a" - integrity sha512-7WMen1qhF5JmjKD9S5IEgEoaPJOXyIZj/Nsqa8ZSWxdF5oogp3uYYbKb/rvMYoKzpIbjyoLH/OCM5lm5IFM4iw== - -"@next/swc-darwin-x64@12.0.4": - version "12.0.4" - resolved "https://registry.yarnpkg.com/@next/swc-darwin-x64/-/swc-darwin-x64-12.0.4.tgz#84855d4c9fef3b3a094c0f2424ae2b7e6dc29caa" - integrity sha512-PVgefMWjxP6CU1HQs39+Bfpjcue6qErJfvJ/+n2zimjLzyeQAmD6LM9f1lDSttW2LjKjasoxR5qkRNLVlqzlaA== - -"@next/swc-linux-arm-gnueabihf@12.0.4": - version "12.0.4" - resolved "https://registry.yarnpkg.com/@next/swc-linux-arm-gnueabihf/-/swc-linux-arm-gnueabihf-12.0.4.tgz#090156c4fc88d86ebc67df35e99daa97ddb232de" - integrity sha512-8xGQu3sJiIdriKiCux3jDJ9pwivELEg7z2zfW0CqmQMbKNB7qP9lc0pq6CxshtKyXRMczNWRMtQ3Cjwep+UvNg== - -"@next/swc-linux-arm64-gnu@12.0.4": - version "12.0.4" - resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-12.0.4.tgz#3ddda6eb703eda411b117d1974f08e028bb987ed" - integrity sha512-HhEWcBkqGr3E7SYLtN9VnYUGamAWaLcXawHN33Em0WP7gzXrBqz0iIJNH7uEzHDS6980EqU/rrkLyhCHrYSZgQ== - -"@next/swc-linux-arm64-musl@12.0.4": - version "12.0.4" - resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-12.0.4.tgz#a17985b811166bb3598816009e5f025539827c21" - integrity sha512-oZyQ9wjtE7OX9RlnovP7izNx2AR/RzTuYWU4Ttim8ssABsipQSxSlfRaeb+Qi6jTc6k+lrPhjRfaZ+fGv/m2Ag== - -"@next/swc-linux-x64-gnu@12.0.4": - version "12.0.4" - resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-12.0.4.tgz#46fa9f4a4d381d41c0fc75912810e72468b0fb49" - integrity sha512-aBuf78QzL93T59Lk9kEGfHcA+9SzYIH7dGon1nqVxtAd2iqicKYNVaVcb38VKeiIBXMSUHXTdu6Ee053ZCOmSw== - -"@next/swc-linux-x64-musl@12.0.4": - version "12.0.4" - resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-12.0.4.tgz#5e07982c84df77ddad537f3abca7d0f52504fc08" - integrity sha512-yDgqUqL4H8M3Y0hv30ZyL9UvjnK4iXmD4I6iJz+XIHSRdA/VUiyKKoL7okf9hxr0mSxBtagbZ5A3qEoW/VliUQ== - -"@next/swc-win32-arm64-msvc@12.0.4": - version "12.0.4" - resolved "https://registry.yarnpkg.com/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-12.0.4.tgz#17705a3d20b35fddd2f61c4d2e491bbf6909e71a" - integrity sha512-evDUrEYsUo+PMHsedaymfZO98VwV9wNFzuWVCyKgqg6SD1ZRpzbpqYQY7aINIuqZVdIWZElBE6EM+oxaj7PuWQ== - -"@next/swc-win32-ia32-msvc@12.0.4": - version "12.0.4" - resolved "https://registry.yarnpkg.com/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-12.0.4.tgz#a2a6d5c09a07c62d3a6b5b6dbc4443b566b8385b" - integrity sha512-Lbmz0xlo8vW4EDWyzCfy3nGfqt7skqwxaERwe+vDVTBZ56mvJ5dsdyjqK24sxu4FFkWR7SaU4eNlHwZR+A3kTg== - -"@next/swc-win32-x64-msvc@12.0.4": - version "12.0.4" - resolved "https://registry.yarnpkg.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-12.0.4.tgz#acb9ffb17118b797d8c76dd688dd0aec5fa65cd4" - integrity sha512-f+7WNIJOno5QEelrmob+3vN5EZJb3KCkOrnvUsQ0+LCCD0dIPIhCjeHAh3BGj9msGu8ijnXvD7JxVxE5V26cnQ== +"@next/react-refresh-utils@12.0.7": + version "12.0.7" + resolved "https://registry.yarnpkg.com/@next/react-refresh-utils/-/react-refresh-utils-12.0.7.tgz#921c403798e188b4f1d9e609283c0e8d3e532f89" + integrity sha512-Pglj1t+7RxH0txEqVcD8ZxrJgqLDmKvQDqxKq3ZPRWxMv7LTl7FVT2Pnb36QFeBwCvMVl67jxsADKsW0idz8sA== + +"@next/swc-android-arm64@12.0.7": + version "12.0.7" + resolved "https://registry.yarnpkg.com/@next/swc-android-arm64/-/swc-android-arm64-12.0.7.tgz#9b0a9e4bc646a045eef725764112096f0a6ea204" + integrity sha512-yViT7EEc7JqxncRT+ZTeTsrAYXLlcefo0Y0eAfYmmalGD2605L4FWAVrJi4WnrSLji7l+veczw1WBmNeHICKKA== + +"@next/swc-darwin-arm64@12.0.7": + version "12.0.7" + resolved "https://registry.yarnpkg.com/@next/swc-darwin-arm64/-/swc-darwin-arm64-12.0.7.tgz#2fd506dba91e4a35036b9fc7930a4d6b8895f16a" + integrity sha512-vhAyW2rDEUcQesRVaj0z1hSoz7QhDzzGd0V1/5/5i9YJOfOtyrPsVJ82tlf7BfXl6/Ep+eKNfWVIb5/Jv89EKg== + +"@next/swc-darwin-x64@12.0.7": + version "12.0.7" + resolved "https://registry.yarnpkg.com/@next/swc-darwin-x64/-/swc-darwin-x64-12.0.7.tgz#b3016503caa5ed5cc6a20051517d5b2a79cfdc58" + integrity sha512-km+6Rx6TvbraoQ1f0MXa69ol/x0RxzucFGa2OgZaYJERas0spy0iwW8hpASsGcf597D8VRW1x+R2C7ZdjVBSTw== + +"@next/swc-linux-arm-gnueabihf@12.0.7": + version "12.0.7" + resolved "https://registry.yarnpkg.com/@next/swc-linux-arm-gnueabihf/-/swc-linux-arm-gnueabihf-12.0.7.tgz#8e91ecddc2d6d26946949a67d481110db3063d09" + integrity sha512-d0zWr877YqZ2cf/DQy6obouaR39r0FPebcXj2nws9AC99m68CO2xVpWv9jT7mFvpY+T40HJisLH80jSZ2iQ9sA== + +"@next/swc-linux-arm64-gnu@12.0.7": + version "12.0.7" + resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-12.0.7.tgz#1eefcf7b063610315b74e5c7dc24c3437370e49d" + integrity sha512-fdobh5u6gG13Gd5LkHhJ+W8tF9hbaFolRW99FhzArMe5/nMKlLdBymOxvitE3K4gSFQxbXJA6TbU0Vv0e59Kww== + +"@next/swc-linux-arm64-musl@12.0.7": + version "12.0.7" + resolved "https://registry.yarnpkg.com/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-12.0.7.tgz#e9e764519dfb75e43355c442181346cd6e72459b" + integrity sha512-vx0c5Q3oIScFNT/4jI9rCe0yPzKuCqWOkiO/OOV0ixSI2gLhbrwDIcdkm79fKVn3i8JOJunxE4zDoFeR/g8xqQ== + +"@next/swc-linux-x64-gnu@12.0.7": + version "12.0.7" + resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-12.0.7.tgz#fef02e14ed8f9c114479dabba1475ae2d3bb040d" + integrity sha512-9ITyp6s6uGVKNx3C/GP7GrYycbcwTADG7TdIXzXUxOOZORrdB1GNg3w/EL3Am4VMPPEpO6v1RfKo2IKZpVKfTA== + +"@next/swc-linux-x64-musl@12.0.7": + version "12.0.7" + resolved "https://registry.yarnpkg.com/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-12.0.7.tgz#07dc334b1924d9f5a8c4a891b91562af19ff5de4" + integrity sha512-C+k+cygbIZXYfc+Hx2fNPUBEg7jzio+mniP5ywZevuTXW14zodIfQ3ZMoMJR8EpOVvYpjWFk2uAjiwqgx8vo/g== + +"@next/swc-win32-arm64-msvc@12.0.7": + version "12.0.7" + resolved "https://registry.yarnpkg.com/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-12.0.7.tgz#6c559d87ce142693173039a18b1c1d65519762dd" + integrity sha512-7jTRjOKkDVnb5s7VoHT7eX+eyT/5BQJ/ljP2G56riAgKGqPL63/V7FXemLhhLT67D+OjoP8DRA2E2ne6IPHk4w== + +"@next/swc-win32-ia32-msvc@12.0.7": + version "12.0.7" + resolved "https://registry.yarnpkg.com/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-12.0.7.tgz#16b23f2301b16877b3623f0e8364e8177e2ef7db" + integrity sha512-2u5pGDsk7H6gGxob2ATIojzlwKzgYsrijo7RRpXOiPePVqwPWg6/pmhaJzLdpfjaBgRg1NFmwSp/7Ump9X8Ijg== + +"@next/swc-win32-x64-msvc@12.0.7": + version "12.0.7" + resolved "https://registry.yarnpkg.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-12.0.7.tgz#8d75d3b6a872ab97ab73e3b4173d56dbb2991917" + integrity sha512-frEWtbf+q8Oz4e2UqKJrNssk6DZ6/NLCQXn5/ORWE9dPAfe9XS6aK5FRZ6DuEPmmKd5gOoRkKJFFz5nYd+TeyQ== "@nodelib/fs.scandir@2.1.5": version "2.1.5" @@ -2564,9 +2481,9 @@ fastq "^1.6.0" "@npmcli/fs@^1.0.0": - version "1.0.0" - resolved "https://registry.yarnpkg.com/@npmcli/fs/-/fs-1.0.0.tgz#589612cfad3a6ea0feafcb901d29c63fd52db09f" - integrity sha512-8ltnOpRR/oJbOp8vaGUnipOi3bqkcW+sLHFlyXIr08OGHmVJLB1Hn7QtGXbYcpVtH1gAYZTlmDXtE4YV0+AMMQ== + version "1.1.0" + resolved "https://registry.yarnpkg.com/@npmcli/fs/-/fs-1.1.0.tgz#bec1d1b89c170d40e1b73ad6c943b0b75e7d2951" + integrity sha512-VhP1qZLXcrXRIaPoqb4YA55JQxLNF3jNR4T55IdOJa3+IFJKNYHtPvtXx8slmeMavj37vCzCfrqQM1vWLsYKLA== dependencies: "@gar/promisify" "^1.0.1" semver "^7.3.5" @@ -2671,9 +2588,9 @@ integrity sha512-Aq58f5HiWdyDlFffbbSjAlv596h/cOnt2DO1w3DOC7OJ5EHs0hd/nycJfiu9RJbT6Yk6F1knnRRXNSpxoIVZ9Q== "@pmmmwh/react-refresh-webpack-plugin@^0.5.1": - version "0.5.3" - resolved "https://registry.yarnpkg.com/@pmmmwh/react-refresh-webpack-plugin/-/react-refresh-webpack-plugin-0.5.3.tgz#b8f0e035f6df71b5c4126cb98de29f65188b9e7b" - integrity sha512-OoTnFb8XEYaOuMNhVDsLRnAO6MCYHNs1g6d8pBcHhDFsi1P3lPbq/IklwtbAx9cG0W4J9KswxZtwGnejrnxp+g== + version "0.5.4" + resolved "https://registry.yarnpkg.com/@pmmmwh/react-refresh-webpack-plugin/-/react-refresh-webpack-plugin-0.5.4.tgz#df0d0d855fc527db48aac93c218a0bf4ada41f99" + integrity sha512-zZbZeHQDnoTlt2AF+diQT0wsSXpvWiaIOZwBRdltNFhG1+I3ozyaw7U/nBiUwyJ0D+zwdXp0E3bWOl38Ag2BMw== dependencies: ansi-html-community "^0.0.8" common-path-prefix "^3.0.0" @@ -2824,42 +2741,42 @@ "@sinonjs/commons" "^1.7.0" "@storybook/addon-a11y@^6.3.7": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/addon-a11y/-/addon-a11y-6.4.3.tgz#29b116ccc34f98534b97fc488375374b6034b565" - integrity sha512-sb3cPfqHACtivPkcx1UePYAyJ0VMmwS4NWWe8JzfSxV4Fmyj7m6O7vIThuWs5eEm6iakljheubVTsQwQwll85A== - dependencies: - "@storybook/addons" "6.4.3" - "@storybook/api" "6.4.3" - "@storybook/channels" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/components" "6.4.3" - "@storybook/core-events" "6.4.3" + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/addon-a11y/-/addon-a11y-6.4.9.tgz#95cd51ad7a71e4c0a39259df2eb10c382bf324db" + integrity sha512-9LwFprh7A3KWmQRTqnyh/wvQ1SX/BewzhBPWqJzq0fGnx9fG35zt0VFtXV13i157wTRDqSO1g92Dgxw9l3S8/A== + dependencies: + "@storybook/addons" "6.4.9" + "@storybook/api" "6.4.9" + "@storybook/channels" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/components" "6.4.9" + "@storybook/core-events" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" - "@storybook/theming" "6.4.3" + "@storybook/theming" "6.4.9" axe-core "^4.2.0" core-js "^3.8.2" global "^4.4.0" - lodash "^4.17.20" + lodash "^4.17.21" react-sizeme "^3.0.1" regenerator-runtime "^0.13.7" ts-dedent "^2.0.0" util-deprecate "^1.0.2" -"@storybook/addon-actions@6.4.3", "@storybook/addon-actions@^6.3.7": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/addon-actions/-/addon-actions-6.4.3.tgz#324b67fecd72a259dba49a4c34c5cece400e66d9" - integrity sha512-oMjENUSDfCOvebAQPyeOIk4Ov6St1QHZUP88aErWepA4m9IVRGMVSpFmuE25Qwq0qGKHCWo9UDlxKN5tlM13Qw== +"@storybook/addon-actions@6.4.9", "@storybook/addon-actions@^6.3.7": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/addon-actions/-/addon-actions-6.4.9.tgz#1d4e8c00ad304efe6722043dac759f4716b515ee" + integrity sha512-L1N66p/vr+wPUBfrH3qffjNAcWSS/wvuL370T7cWxALA9LLA8yY9U2EpITc5btuCC5QOxApCeyHkFnrBhNa94g== dependencies: - "@storybook/addons" "6.4.3" - "@storybook/api" "6.4.3" - "@storybook/components" "6.4.3" - "@storybook/core-events" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/api" "6.4.9" + "@storybook/components" "6.4.9" + "@storybook/core-events" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" - "@storybook/theming" "6.4.3" + "@storybook/theming" "6.4.9" core-js "^3.8.2" fast-deep-equal "^3.1.3" global "^4.4.0" - lodash "^4.17.20" + lodash "^4.17.21" polished "^4.0.5" prop-types "^15.7.2" react-inspector "^5.1.0" @@ -2869,18 +2786,18 @@ util-deprecate "^1.0.2" uuid-browser "^3.1.0" -"@storybook/addon-backgrounds@6.4.3", "@storybook/addon-backgrounds@^6.3.7": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/addon-backgrounds/-/addon-backgrounds-6.4.3.tgz#98273172c5a2131907552ca327c8b86be0fcf900" - integrity sha512-WZbUUfjLFLC2Exw75jpc5P46vN9pNI3DhIiqvG+tPXzcsQNPUfZZeOnSSr0KoUFmiD2f3yqrB5CPgSeOQaw73A== +"@storybook/addon-backgrounds@6.4.9", "@storybook/addon-backgrounds@^6.3.7": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/addon-backgrounds/-/addon-backgrounds-6.4.9.tgz#89033aed6f01d6a2dc134cbdb1ce0c46afd130ec" + integrity sha512-/jqUZvk+x8TpDedyFnJamSYC91w/e8prj42xtgLG4+yBlb0UmewX7BAq9i/lhowhUjuLKaOX9E8E0AHftg8L6A== dependencies: - "@storybook/addons" "6.4.3" - "@storybook/api" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/components" "6.4.3" - "@storybook/core-events" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/api" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/components" "6.4.9" + "@storybook/core-events" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" - "@storybook/theming" "6.4.3" + "@storybook/theming" "6.4.9" core-js "^3.8.2" global "^4.4.0" memoizerific "^1.11.3" @@ -2888,28 +2805,28 @@ ts-dedent "^2.0.0" util-deprecate "^1.0.2" -"@storybook/addon-controls@6.4.3", "@storybook/addon-controls@^6.3.7": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/addon-controls/-/addon-controls-6.4.3.tgz#9d4457b40b4da1f3a58bf94cb81078c901e4551a" - integrity sha512-gCZEUgz5XXetGzn3dczptb09UDB1J3on8YFTgPJ0IP/1JSRT90gDQ+3a3GeUPvnzop7scw0Ndvat1OT4flI4gg== +"@storybook/addon-controls@6.4.9", "@storybook/addon-controls@^6.3.7": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/addon-controls/-/addon-controls-6.4.9.tgz#286a184336a80981fdd805f44a68f60fb6e38e73" + integrity sha512-2eqtiYugCAOw8MCv0HOfjaZRQ4lHydMYoKIFy/QOv6/mjcJeG9dF01dA30n3miErQ18BaVyAB5+7rrmuqMwXVA== dependencies: - "@storybook/addons" "6.4.3" - "@storybook/api" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/components" "6.4.3" - "@storybook/core-common" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/api" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/components" "6.4.9" + "@storybook/core-common" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" - "@storybook/node-logger" "6.4.3" - "@storybook/store" "6.4.3" - "@storybook/theming" "6.4.3" + "@storybook/node-logger" "6.4.9" + "@storybook/store" "6.4.9" + "@storybook/theming" "6.4.9" core-js "^3.8.2" - lodash "^4.17.20" + lodash "^4.17.21" ts-dedent "^2.0.0" -"@storybook/addon-docs@6.4.3", "@storybook/addon-docs@^6.3.7": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/addon-docs/-/addon-docs-6.4.3.tgz#c42943d46affbfec93190531221d2d2bd7d980c9" - integrity sha512-/hpP7JaL4TAVa/uE6vKtmXqmZQ/2H5kuZOBIdMSXBetTH2O8xPc8I7WTEzKetF6OrPFCEivR/DhcEruC4P80gg== +"@storybook/addon-docs@6.4.9", "@storybook/addon-docs@^6.3.7": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/addon-docs/-/addon-docs-6.4.9.tgz#dc34c6152085043a771623b2de344bc9d91f0563" + integrity sha512-sJvnbp6Z+e7B1+vDE8gZVhCg1eNotIa7bx9LYd1Y2QwJ4PEv9hE2YxnzmWt3NZJGtrn4gdGaMCk7pmksugHi7g== dependencies: "@babel/core" "^7.12.10" "@babel/generator" "^7.12.11" @@ -2920,21 +2837,21 @@ "@mdx-js/loader" "^1.6.22" "@mdx-js/mdx" "^1.6.22" "@mdx-js/react" "^1.6.22" - "@storybook/addons" "6.4.3" - "@storybook/api" "6.4.3" - "@storybook/builder-webpack4" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/components" "6.4.3" - "@storybook/core" "6.4.3" - "@storybook/core-events" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/api" "6.4.9" + "@storybook/builder-webpack4" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/components" "6.4.9" + "@storybook/core" "6.4.9" + "@storybook/core-events" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" - "@storybook/csf-tools" "6.4.3" - "@storybook/node-logger" "6.4.3" - "@storybook/postinstall" "6.4.3" - "@storybook/preview-web" "6.4.3" - "@storybook/source-loader" "6.4.3" - "@storybook/store" "6.4.3" - "@storybook/theming" "6.4.3" + "@storybook/csf-tools" "6.4.9" + "@storybook/node-logger" "6.4.9" + "@storybook/postinstall" "6.4.9" + "@storybook/preview-web" "6.4.9" + "@storybook/source-loader" "6.4.9" + "@storybook/store" "6.4.9" + "@storybook/theming" "6.4.9" acorn "^7.4.1" acorn-jsx "^5.3.1" acorn-walk "^7.2.0" @@ -2946,7 +2863,7 @@ html-tags "^3.1.0" js-string-escape "^1.0.1" loader-utils "^2.0.0" - lodash "^4.17.20" + lodash "^4.17.21" nanoid "^3.1.23" p-limit "^3.1.0" prettier "^2.2.1" @@ -2959,35 +2876,35 @@ util-deprecate "^1.0.2" "@storybook/addon-essentials@^6.3.7": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/addon-essentials/-/addon-essentials-6.4.3.tgz#b76aeb4c20f3095374973d14392502313c0dac73" - integrity sha512-pSeujHmQH8AOVd2nf5ignum4zaM5D9Amiml2kHflZa5bnJs6FwmsE5G/7mb7fbqtCJt/nw1PbaaUT4eT5M/uuQ== - dependencies: - "@storybook/addon-actions" "6.4.3" - "@storybook/addon-backgrounds" "6.4.3" - "@storybook/addon-controls" "6.4.3" - "@storybook/addon-docs" "6.4.3" - "@storybook/addon-measure" "6.4.3" - "@storybook/addon-outline" "6.4.3" - "@storybook/addon-toolbars" "6.4.3" - "@storybook/addon-viewport" "6.4.3" - "@storybook/addons" "6.4.3" - "@storybook/api" "6.4.3" - "@storybook/node-logger" "6.4.3" + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/addon-essentials/-/addon-essentials-6.4.9.tgz#e761a61a9ac9809b8a5d8b6f7c5a1b50f0e2cd91" + integrity sha512-3YOtGJsmS7A4aIaclnEqTgO+fUEX63pHq2CvqIKPGLVPgLmn6MnEhkkV2j30MfAkoe3oynLqFBvkCdYwzwJxNQ== + dependencies: + "@storybook/addon-actions" "6.4.9" + "@storybook/addon-backgrounds" "6.4.9" + "@storybook/addon-controls" "6.4.9" + "@storybook/addon-docs" "6.4.9" + "@storybook/addon-measure" "6.4.9" + "@storybook/addon-outline" "6.4.9" + "@storybook/addon-toolbars" "6.4.9" + "@storybook/addon-viewport" "6.4.9" + "@storybook/addons" "6.4.9" + "@storybook/api" "6.4.9" + "@storybook/node-logger" "6.4.9" core-js "^3.8.2" regenerator-runtime "^0.13.7" ts-dedent "^2.0.0" "@storybook/addon-links@^6.3.7": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/addon-links/-/addon-links-6.4.3.tgz#733c933bfd4e34755f665574401d9b725cbd7653" - integrity sha512-yjDqulTder966NSis/N+Q+2nTnuUYYfHpvt2LHmf6oHhhkNdWzzzQ3if95BUC2SJMe/CvKlownq2Or64TlsFpg== + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/addon-links/-/addon-links-6.4.9.tgz#2d0a7f813dcef160feb357f6548bb1a7ba425d7d" + integrity sha512-xXFz/bmw67u4+zPVqJdiJkCtGrO2wAhcsLc4QSTc2+Xgkvkk7ulcRguiujAy5bfinhPa6U1vpJrrg5GFGV+trA== dependencies: - "@storybook/addons" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/core-events" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/core-events" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" - "@storybook/router" "6.4.3" + "@storybook/router" "6.4.9" "@types/qs" "^6.9.5" core-js "^3.8.2" global "^4.4.0" @@ -2996,98 +2913,98 @@ regenerator-runtime "^0.13.7" ts-dedent "^2.0.0" -"@storybook/addon-measure@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/addon-measure/-/addon-measure-6.4.3.tgz#6bd896d6a351cc01110cda5e1a7cec12adbe47d9" - integrity sha512-C8zLs+Db9JO6TuylYad3aBlqW4naheaqjtY2gnSk6z5wGdwo8BxAvhV6fN3Z/iQkNwOEVtPYRwtfxuhT1RQ6bw== +"@storybook/addon-measure@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/addon-measure/-/addon-measure-6.4.9.tgz#d4446e0b0686f4f25bbd7eee8c4cf296d8bea216" + integrity sha512-c7r98kZM0i7ZrNf0BZe/12BwTYGDLUnmyNcLhugquvezkm32R1SaqXF8K1bGkWkSuzBvt49lAXXPPGUh+ByWEQ== dependencies: - "@storybook/addons" "6.4.3" - "@storybook/api" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/components" "6.4.3" - "@storybook/core-events" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/api" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/components" "6.4.9" + "@storybook/core-events" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" core-js "^3.8.2" global "^4.4.0" -"@storybook/addon-outline@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/addon-outline/-/addon-outline-6.4.3.tgz#840978a2f5bfbe2e509a4132807f4430ae41b56e" - integrity sha512-F8W3qwosFps0rSaSeqUJayFt8ZMa2qmAy0ly9H1ZfONGTqRotiO/FH56RWcvkpYMe7/dO8WyZQWWnV+427vMHw== +"@storybook/addon-outline@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/addon-outline/-/addon-outline-6.4.9.tgz#0f6b20eb41580686cca4b9f12937932dd5f51c64" + integrity sha512-pXXfqisYfdoxyJuSogNBOUiqIugv0sZGYDJXuwEgEDZ27bZD6fCQmsK3mqSmRzAfXwDqTKvWuu2SRbEk/cRRGA== dependencies: - "@storybook/addons" "6.4.3" - "@storybook/api" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/components" "6.4.3" - "@storybook/core-events" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/api" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/components" "6.4.9" + "@storybook/core-events" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" core-js "^3.8.2" global "^4.4.0" regenerator-runtime "^0.13.7" ts-dedent "^2.0.0" -"@storybook/addon-toolbars@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/addon-toolbars/-/addon-toolbars-6.4.3.tgz#8bc725b2be560b359f3c06a7b63def33438bce68" - integrity sha512-3PeXafbYyACkECQIfyk1Kfvo2bhUMiqFVJpEVnKQcxMdFDTrjMu+CTWWDV4nxss/4MhNM9idrHO4oRdaeKuTpQ== +"@storybook/addon-toolbars@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/addon-toolbars/-/addon-toolbars-6.4.9.tgz#147534d0b185a1782f3381a47c627b4a4193297d" + integrity sha512-fep1lLDcyaQJdR8rC/lJTamiiJ8Ilio580d9aXDM651b7uHqhxM0dJvM9hObBU8dOj/R3hIAszgTvdTzYlL2cQ== dependencies: - "@storybook/addons" "6.4.3" - "@storybook/api" "6.4.3" - "@storybook/components" "6.4.3" - "@storybook/theming" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/api" "6.4.9" + "@storybook/components" "6.4.9" + "@storybook/theming" "6.4.9" core-js "^3.8.2" regenerator-runtime "^0.13.7" -"@storybook/addon-viewport@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/addon-viewport/-/addon-viewport-6.4.3.tgz#4ba4afdc0e21f2a0ffe37e963ba165325fd1cadc" - integrity sha512-9waCLMXBWTRX6FoGkNE4cadLy4cVmoYcaKsUxOOtElNLguVnVZttssTeJxBkXWL7vZAAOLKpUk/XJBI4H8ttWA== - dependencies: - "@storybook/addons" "6.4.3" - "@storybook/api" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/components" "6.4.3" - "@storybook/core-events" "6.4.3" - "@storybook/theming" "6.4.3" +"@storybook/addon-viewport@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/addon-viewport/-/addon-viewport-6.4.9.tgz#73753ff62043d3d6e6d845590ed70caf775af960" + integrity sha512-iqDcfbOG3TClybDEIi+hOKq8PDKNldyAiqBeak4AfGp+lIZ4NvhHgS5RCNylMVKpOUMbGIeWiSFxQ/oglEN1zA== + dependencies: + "@storybook/addons" "6.4.9" + "@storybook/api" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/components" "6.4.9" + "@storybook/core-events" "6.4.9" + "@storybook/theming" "6.4.9" core-js "^3.8.2" global "^4.4.0" memoizerific "^1.11.3" prop-types "^15.7.2" regenerator-runtime "^0.13.7" -"@storybook/addons@6.4.3", "@storybook/addons@^6.3.7": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/addons/-/addons-6.4.3.tgz#f34cb04289806f3d22be8a39c67fcd1dbdcbe137" - integrity sha512-LiS8NNZXpietvWw+A+jTVtVpVRARc2vq9R7KWAj07oFF91KD+U4PISAYbNMUVitej05CJJqT0jdtiW8G5pAr1g== +"@storybook/addons@6.4.9", "@storybook/addons@^6.3.7": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/addons/-/addons-6.4.9.tgz#43b5dabf6781d863fcec0a0b293c236b4d5d4433" + integrity sha512-y+oiN2zd+pbRWwkf6aQj4tPDFn+rQkrv7fiVoMxsYub+kKyZ3CNOuTSJH+A1A+eBL6DmzocChUyO6jvZFuh6Dg== dependencies: - "@storybook/api" "6.4.3" - "@storybook/channels" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/core-events" "6.4.3" + "@storybook/api" "6.4.9" + "@storybook/channels" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/core-events" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" - "@storybook/router" "6.4.3" - "@storybook/theming" "6.4.3" + "@storybook/router" "6.4.9" + "@storybook/theming" "6.4.9" "@types/webpack-env" "^1.16.0" core-js "^3.8.2" global "^4.4.0" regenerator-runtime "^0.13.7" -"@storybook/api@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/api/-/api-6.4.3.tgz#ae30c75be8559cb6b54195989b50a7e3ccf4cb23" - integrity sha512-aWD7wPhj+HF2XBmH6b7hgRJPFldDXzhYbtPqsq6ukCrGlJder8NsnL6wHzXlQWgxudw8u3oqM+Q9kLwNiz4yXg== +"@storybook/api@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/api/-/api-6.4.9.tgz#6187d08658629580f0a583f2069d55b34964b34a" + integrity sha512-U+YKcDQg8xal9sE5eSMXB9vcqk8fD1pSyewyAjjbsW5hV0B3L3i4u7z/EAD9Ujbnor+Cvxq+XGvp+Qnc5Gd40A== dependencies: - "@storybook/channels" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/core-events" "6.4.3" + "@storybook/channels" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/core-events" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" - "@storybook/router" "6.4.3" + "@storybook/router" "6.4.9" "@storybook/semver" "^7.3.2" - "@storybook/theming" "6.4.3" + "@storybook/theming" "6.4.9" core-js "^3.8.2" fast-deep-equal "^3.1.3" global "^4.4.0" - lodash "^4.17.20" + lodash "^4.17.21" memoizerific "^1.11.3" regenerator-runtime "^0.13.7" store2 "^2.12.0" @@ -3095,10 +3012,10 @@ ts-dedent "^2.0.0" util-deprecate "^1.0.2" -"@storybook/builder-webpack4@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/builder-webpack4/-/builder-webpack4-6.4.3.tgz#b9d1568eb4a2c5f6900aa83ed8a5773167caf26e" - integrity sha512-nD4pIR5OY5KFIGpK4j/wLRNGGYFSlXkSW1jtG3qSQPpThB50hVftwHUW/62qq4u025KPrp/nDlgYpGfsUdRQ1A== +"@storybook/builder-webpack4@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/builder-webpack4/-/builder-webpack4-6.4.9.tgz#86cd691c856eeb7a6a7bcafa57e9a66c1e0b9906" + integrity sha512-nDbXDd3A8dvalCiuBZuUT6/GQP14+fuxTj5g+AppCgV1gLO45lXWtX75Hc0IbZrIQte6tDg5xeFQamZSLPMcGg== dependencies: "@babel/core" "^7.12.10" "@babel/plugin-proposal-class-properties" "^7.12.1" @@ -3121,22 +3038,22 @@ "@babel/preset-env" "^7.12.11" "@babel/preset-react" "^7.12.10" "@babel/preset-typescript" "^7.12.7" - "@storybook/addons" "6.4.3" - "@storybook/api" "6.4.3" - "@storybook/channel-postmessage" "6.4.3" - "@storybook/channels" "6.4.3" - "@storybook/client-api" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/components" "6.4.3" - "@storybook/core-common" "6.4.3" - "@storybook/core-events" "6.4.3" - "@storybook/node-logger" "6.4.3" - "@storybook/preview-web" "6.4.3" - "@storybook/router" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/api" "6.4.9" + "@storybook/channel-postmessage" "6.4.9" + "@storybook/channels" "6.4.9" + "@storybook/client-api" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/components" "6.4.9" + "@storybook/core-common" "6.4.9" + "@storybook/core-events" "6.4.9" + "@storybook/node-logger" "6.4.9" + "@storybook/preview-web" "6.4.9" + "@storybook/router" "6.4.9" "@storybook/semver" "^7.3.2" - "@storybook/store" "6.4.3" - "@storybook/theming" "6.4.3" - "@storybook/ui" "6.4.3" + "@storybook/store" "6.4.9" + "@storybook/theming" "6.4.9" + "@storybook/ui" "6.4.9" "@types/node" "^14.0.10" "@types/webpack" "^4.41.26" autoprefixer "^9.8.6" @@ -3171,57 +3088,57 @@ webpack-hot-middleware "^2.25.1" webpack-virtual-modules "^0.2.2" -"@storybook/channel-postmessage@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/channel-postmessage/-/channel-postmessage-6.4.3.tgz#2167a05a4306bee3623f213d65661e5bdc7a9148" - integrity sha512-UKXYqKo4yah7q2AzdqvBXs7LqX9G3383FyIs9BdVcx+cvdaMHT3FKk9CJAibgED1puABN08QpHnwLzPYwVmq4A== +"@storybook/channel-postmessage@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/channel-postmessage/-/channel-postmessage-6.4.9.tgz#b20b7d66f0f2a8ba39fe9002f3a3dc16d9e1f681" + integrity sha512-0Oif4e6/oORv4oc2tHhIRts9faE/ID9BETn4uqIUWSl2CX1wYpKYDm04rEg3M6WvSzsi+6fzoSFvkr9xC5Ns2w== dependencies: - "@storybook/channels" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/core-events" "6.4.3" + "@storybook/channels" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/core-events" "6.4.9" core-js "^3.8.2" global "^4.4.0" qs "^6.10.0" telejson "^5.3.2" -"@storybook/channel-websocket@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/channel-websocket/-/channel-websocket-6.4.3.tgz#3923d4749f4405192f6369bd837989ad0f0e37ce" - integrity sha512-6mw3PSNr6Y22qRticJ7ktpAax4UknD++6/g/NwvvMwajcW4gjCT5esRYnCoAPYRq5DbOfj9v1R3H55syz9YMGg== +"@storybook/channel-websocket@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/channel-websocket/-/channel-websocket-6.4.9.tgz#f012840894f73bac289ddcdc57efb385c4a0b7ef" + integrity sha512-R1O5yrNtN+dIAghqMXUqoaH7XWBcrKi5miVRn7QelKG3qZwPL8HQa7gIPc/b6S2D6hD3kQdSuv/zTIjjMg7wyw== dependencies: - "@storybook/channels" "6.4.3" - "@storybook/client-logger" "6.4.3" + "@storybook/channels" "6.4.9" + "@storybook/client-logger" "6.4.9" core-js "^3.8.2" global "^4.4.0" telejson "^5.3.2" -"@storybook/channels@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/channels/-/channels-6.4.3.tgz#e70668d3dea06fcadf274c867a3430e3a5350787" - integrity sha512-E9JGZ53ITybokm7CEYARQjwdF/yDTu/R0tEo0MldPrNumb8yDjb4vxokBpvwbOMZ/n+QSU1BUIISm5bYt3owlQ== +"@storybook/channels@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/channels/-/channels-6.4.9.tgz#132c574d3fb2e6aaa9c52312c592794699b9d8ec" + integrity sha512-DNW1qDg+1WFS2aMdGh658WJXh8xBXliO5KAn0786DKcWCsKjfsPPQg/QCHczHK0+s5SZyzQT5aOBb4kTRHELQA== dependencies: core-js "^3.8.2" ts-dedent "^2.0.0" util-deprecate "^1.0.2" -"@storybook/client-api@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/client-api/-/client-api-6.4.3.tgz#912c19ca347a6edaf2a1562746fa31db82b0fa33" - integrity sha512-GBXRvCXlY3GSTK4f2NFi5NjGcmeZVpRerqGb+bEcPdxkjOlFjQVBeNyl45AbNuuq+m3+SabZfTNCdy3gWe2Jjw== +"@storybook/client-api@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/client-api/-/client-api-6.4.9.tgz#e3d90c66356d6f53f8ceb4f31753f670f704fde0" + integrity sha512-1IljlTr+ea2pIr6oiPhygORtccOdEb7SqaVzWDfLCHOhUnJ2Ka5UY9ADqDa35jvSSdRdynfk9Yl5/msY0yY1yg== dependencies: - "@storybook/addons" "6.4.3" - "@storybook/channel-postmessage" "6.4.3" - "@storybook/channels" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/core-events" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/channel-postmessage" "6.4.9" + "@storybook/channels" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/core-events" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" - "@storybook/store" "6.4.3" + "@storybook/store" "6.4.9" "@types/qs" "^6.9.5" "@types/webpack-env" "^1.16.0" core-js "^3.8.2" fast-deep-equal "^3.1.3" global "^4.4.0" - lodash "^4.17.20" + lodash "^4.17.21" memoizerific "^1.11.3" qs "^6.10.0" regenerator-runtime "^0.13.7" @@ -3230,23 +3147,23 @@ ts-dedent "^2.0.0" util-deprecate "^1.0.2" -"@storybook/client-logger@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/client-logger/-/client-logger-6.4.3.tgz#1db1eab500f85c095239d581769c8e04e84994fe" - integrity sha512-/KmfJlihg2ldm9ml2sNIPOCdSIgF+TsRCET5W8vmwRUu/QUcs6mJMKlEWmmmlyATBp5DKQR+fABe2DccGuOWEQ== +"@storybook/client-logger@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/client-logger/-/client-logger-6.4.9.tgz#ef6af30fac861fea69c8917120ed06b4c2f0b54e" + integrity sha512-BVagmmHcuKDZ/XROADfN3tiolaDW2qG0iLmDhyV1gONnbGE6X5Qm19Jt2VYu3LvjKF1zMPSWm4mz7HtgdwKbuQ== dependencies: core-js "^3.8.2" global "^4.4.0" -"@storybook/components@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/components/-/components-6.4.3.tgz#498f22b375a73d1e4cefdbb165d1de2d8d60ba31" - integrity sha512-U8U5xm6R4ufsoFODimTNywk1zMG4p4AmKNpq9GboF9tSVKcoyfj8DpPlDJbdga5V9XVGcO2b5FoTRCzUiEsfvw== +"@storybook/components@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/components/-/components-6.4.9.tgz#caed59eb3f09d1646da748186f718a0e54fb8fd7" + integrity sha512-uOUR97S6kjptkMCh15pYNM1vAqFXtpyneuonmBco5vADJb3ds0n2a8NeVd+myIbhIXn55x0OHKiSwBH/u7swCQ== dependencies: "@popperjs/core" "^2.6.0" - "@storybook/client-logger" "6.4.3" + "@storybook/client-logger" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" - "@storybook/theming" "6.4.3" + "@storybook/theming" "6.4.9" "@types/color-convert" "^2.0.0" "@types/overlayscrollbars" "^1.12.0" "@types/react-syntax-highlighter" "11.0.5" @@ -3254,7 +3171,7 @@ core-js "^3.8.2" fast-deep-equal "^3.1.3" global "^4.4.0" - lodash "^4.17.20" + lodash "^4.17.21" markdown-to-jsx "^7.1.3" memoizerific "^1.11.3" overlayscrollbars "^1.13.1" @@ -3268,36 +3185,36 @@ ts-dedent "^2.0.0" util-deprecate "^1.0.2" -"@storybook/core-client@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/core-client/-/core-client-6.4.3.tgz#758b36397536867b75646acbb89a5eba1d03c928" - integrity sha512-lyp2N2Rn8YKFuds6FrKiRJ7NAkBA7yK4QNfuGgxbyDdT/nI+1v24ljZJzF8tRM2aC75w8m7YSQXTAmG9i4o76Q== - dependencies: - "@storybook/addons" "6.4.3" - "@storybook/channel-postmessage" "6.4.3" - "@storybook/channel-websocket" "6.4.3" - "@storybook/client-api" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/core-events" "6.4.3" +"@storybook/core-client@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/core-client/-/core-client-6.4.9.tgz#324119a67609f758e244a7d58bac00e62020a21f" + integrity sha512-LZSpTtvBlpcn+Ifh0jQXlm/8wva2zZ2v13yxYIxX6tAwQvmB54U0N4VdGVmtkiszEp7TQUAzA8Pcyp4GWE+UMA== + dependencies: + "@storybook/addons" "6.4.9" + "@storybook/channel-postmessage" "6.4.9" + "@storybook/channel-websocket" "6.4.9" + "@storybook/client-api" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/core-events" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" - "@storybook/preview-web" "6.4.3" - "@storybook/store" "6.4.3" - "@storybook/ui" "6.4.3" + "@storybook/preview-web" "6.4.9" + "@storybook/store" "6.4.9" + "@storybook/ui" "6.4.9" airbnb-js-shims "^2.2.1" ansi-to-html "^0.6.11" core-js "^3.8.2" global "^4.4.0" - lodash "^4.17.20" + lodash "^4.17.21" qs "^6.10.0" regenerator-runtime "^0.13.7" ts-dedent "^2.0.0" unfetch "^4.2.0" util-deprecate "^1.0.2" -"@storybook/core-common@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/core-common/-/core-common-6.4.3.tgz#a389a6c80ada48d8fe970e09767b0aa65b7b5b91" - integrity sha512-1bqg2dwo6FcarAwQjXQtmELLQp9FxPdFM9UpKZJuIfRWMOqaxPiRofI1nYxQcE59WHEbHEvg7KcOaJ5TUA2MhA== +"@storybook/core-common@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/core-common/-/core-common-6.4.9.tgz#1a892903061f927b8f7b9fa8d25273a2f5c9e227" + integrity sha512-wVHRfUGnj/Tv8nGjv128NDQ5Zp6c63rSXd1lYLzfZPTJmGOz4rpPPez2IZSnnDwbAWeqUSMekFVZPj4v6yuujQ== dependencies: "@babel/core" "^7.12.10" "@babel/plugin-proposal-class-properties" "^7.12.1" @@ -3320,7 +3237,7 @@ "@babel/preset-react" "^7.12.10" "@babel/preset-typescript" "^7.12.7" "@babel/register" "^7.12.1" - "@storybook/node-logger" "6.4.3" + "@storybook/node-logger" "6.4.9" "@storybook/semver" "^7.3.2" "@types/node" "^14.0.10" "@types/pretty-hrtime" "^1.0.0" @@ -3349,29 +3266,29 @@ util-deprecate "^1.0.2" webpack "4" -"@storybook/core-events@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/core-events/-/core-events-6.4.3.tgz#5fb3281a7cacba7fbf0d51a7a782cf751b27f6d7" - integrity sha512-UnXDO57U0jJYxXT4hVYQ7ze2wnCp3jrkRSyUPmMcyqpuLAWFhj+QYyna/7+geNID80MbVkkNLE+AEeSY+PPglQ== +"@storybook/core-events@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/core-events/-/core-events-6.4.9.tgz#7febedb8d263fbd6e4a69badbfcdce0101e6f782" + integrity sha512-YhU2zJr6wzvh5naYYuy/0UKNJ/SaXu73sIr0Tx60ur3bL08XkRg7eZ9vBhNBTlAa35oZqI0iiGCh0ljiX7yEVQ== dependencies: core-js "^3.8.2" -"@storybook/core-server@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/core-server/-/core-server-6.4.3.tgz#fcf5526e9fbe542e55d6b9615a8789d08d94efe4" - integrity sha512-gL2zBYtN1vim/rzf1bKFotmVm0ZDBsZNVDN7zsk3ukDee1c8jhRJHu1275CT/rjkqnEwW1Ng0sWncl5LxINpZQ== +"@storybook/core-server@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/core-server/-/core-server-6.4.9.tgz#593fd4cc21a05c908e0eed20767eb6c9cddad428" + integrity sha512-Ht/e17/SNW9BgdvBsnKmqNrlZ6CpHeVsClEUnauMov8I5rxjvKBVmI/UsbJJIy6H6VLiL/RwrA3RvLoAoZE8dA== dependencies: "@discoveryjs/json-ext" "^0.5.3" - "@storybook/builder-webpack4" "6.4.3" - "@storybook/core-client" "6.4.3" - "@storybook/core-common" "6.4.3" - "@storybook/core-events" "6.4.3" + "@storybook/builder-webpack4" "6.4.9" + "@storybook/core-client" "6.4.9" + "@storybook/core-common" "6.4.9" + "@storybook/core-events" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" - "@storybook/csf-tools" "6.4.3" - "@storybook/manager-webpack4" "6.4.3" - "@storybook/node-logger" "6.4.3" + "@storybook/csf-tools" "6.4.9" + "@storybook/manager-webpack4" "6.4.9" + "@storybook/node-logger" "6.4.9" "@storybook/semver" "^7.3.2" - "@storybook/store" "6.4.3" + "@storybook/store" "6.4.9" "@types/node" "^14.0.10" "@types/node-fetch" "^2.5.7" "@types/pretty-hrtime" "^1.0.0" @@ -3390,7 +3307,7 @@ fs-extra "^9.0.1" globby "^11.0.2" ip "^1.1.5" - lodash "^4.17.20" + lodash "^4.17.21" node-fetch "^2.6.1" pretty-hrtime "^1.0.3" prompts "^2.4.0" @@ -3404,18 +3321,18 @@ webpack "4" ws "^8.2.3" -"@storybook/core@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/core/-/core-6.4.3.tgz#93cc30bd5fb6542496551cc73129785021911b57" - integrity sha512-fSqaoJNl7AT7D49xrgMylaQvJc9wkTohsaLggVNONOTV+qigYnqT9mL1c+gFDAmLq6sk9ngBelwHcQ1gmxqWpA== +"@storybook/core@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/core/-/core-6.4.9.tgz#4bf910d7322b524f8166c97c28875e1e3775f391" + integrity sha512-Mzhiy13loMSd3PCygK3t7HIT3X3L35iZmbe6+2xVbVmc/3ypCmq4PQALCUoDOGk37Ifrhop6bo6sl4s9YQ6UFw== dependencies: - "@storybook/core-client" "6.4.3" - "@storybook/core-server" "6.4.3" + "@storybook/core-client" "6.4.9" + "@storybook/core-server" "6.4.9" -"@storybook/csf-tools@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/csf-tools/-/csf-tools-6.4.3.tgz#f85212896d8014a16a9b5825406924d9db1608da" - integrity sha512-so4U6TqmE7jCOrTeRaX9iO2EYEdbolStxIH7Wjw9gQFX75F8EA+TmhKCqoCXBrHnqsUxUFDPeJTrPfGxgPbrGA== +"@storybook/csf-tools@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/csf-tools/-/csf-tools-6.4.9.tgz#7cccb905875ba5962dda83825f763a111932464b" + integrity sha512-zbgsx9vY5XOA9bBmyw+KyuRspFXAjEJ6I3d/6Z3G1kNBeOEj9i3DT7O99Rd/THfL/3mWl8DJ/7CJVPk1ZYxunA== dependencies: "@babel/core" "^7.12.10" "@babel/generator" "^7.12.11" @@ -3430,7 +3347,7 @@ fs-extra "^9.0.1" global "^4.4.0" js-string-escape "^1.0.1" - lodash "^4.17.20" + lodash "^4.17.21" prettier "^2.2.1" regenerator-runtime "^0.13.7" ts-dedent "^2.0.0" @@ -3442,20 +3359,20 @@ dependencies: lodash "^4.17.15" -"@storybook/manager-webpack4@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/manager-webpack4/-/manager-webpack4-6.4.3.tgz#0c6619022e79f54efddc9a5983cce74a0e16a4c5" - integrity sha512-xZpm8eUAf7Otqcm5cNw31AUeIRdjM69go0iMNNwIVcVJjYup46wJ/zUYRjZyBOSwKpWRPEWzMCav9c++RQ+2pw== +"@storybook/manager-webpack4@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/manager-webpack4/-/manager-webpack4-6.4.9.tgz#76edd6f2c627dc64d3362a265c2fe6ae7ee22507" + integrity sha512-828x3rqMuzBNSb13MSDo2nchY7fuywh+8+Vk+fn00MvBYJjogd5RQFx5ocwhHzmwXbnESIerlGwe81AzMck8ng== dependencies: "@babel/core" "^7.12.10" "@babel/plugin-transform-template-literals" "^7.12.1" "@babel/preset-react" "^7.12.10" - "@storybook/addons" "6.4.3" - "@storybook/core-client" "6.4.3" - "@storybook/core-common" "6.4.3" - "@storybook/node-logger" "6.4.3" - "@storybook/theming" "6.4.3" - "@storybook/ui" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/core-client" "6.4.9" + "@storybook/core-common" "6.4.9" + "@storybook/node-logger" "6.4.9" + "@storybook/theming" "6.4.9" + "@storybook/ui" "6.4.9" "@types/node" "^14.0.10" "@types/webpack" "^4.41.26" babel-loader "^8.0.0" @@ -3484,10 +3401,10 @@ webpack-dev-middleware "^3.7.3" webpack-virtual-modules "^0.2.2" -"@storybook/node-logger@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/node-logger/-/node-logger-6.4.3.tgz#5f9d94aab24a3f18ba03e2d3aafcb920bbfeb27d" - integrity sha512-kA3xevEIytm4RFtaBYTel6nhjeqMzxgXfIvgu7HEPtwNyOZr0acoQ7Q3d90r5EfcfVm+M4crp7AMpUnN2CY+CQ== +"@storybook/node-logger@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/node-logger/-/node-logger-6.4.9.tgz#7c28f16f5c61feda8f45fa2c06000ebb87b57df7" + integrity sha512-giil8dA85poH+nslKHIS9tSxp4MP4ensOec7el6GwKiqzAQXITrm3b7gw61ETj39jAQeLIcQYGHLq1oqQo4/YQ== dependencies: "@types/npmlog" "^4.1.2" chalk "^4.1.0" @@ -3495,28 +3412,28 @@ npmlog "^5.0.1" pretty-hrtime "^1.0.3" -"@storybook/postinstall@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/postinstall/-/postinstall-6.4.3.tgz#f97bfe1a84c2dc5c86a69642c54b9bca9121af55" - integrity sha512-1UX3VFY61Osl2oeGAPWm7LYgijalH3cKuA0AXdwbGpoNCQO9fx7Hz69iqbVr8FDdu2se+1yt9B6CvbJfN3Wmyw== +"@storybook/postinstall@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/postinstall/-/postinstall-6.4.9.tgz#7b011a2e188bcc54180b16d06f21c9d52a5324ac" + integrity sha512-LNI5ku+Q4DI7DD3Y8liYVgGPasp8r/5gzNLSJZ1ad03OW/mASjhSsOKp2eD8Jxud2T5JDe3/yKH9u/LP6SepBQ== dependencies: core-js "^3.8.2" -"@storybook/preview-web@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/preview-web/-/preview-web-6.4.3.tgz#a1fbafe68a3b6b8a7cc3dbd565bbee337b17873d" - integrity sha512-TJki+OrcVvNMfhOOHUWxlnhpM1frkL3KSCCGXiAi9n9YAqvEw6DeFX3d7+Z8uAxe4kRQsdqRaszyy+13KHrEyQ== +"@storybook/preview-web@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/preview-web/-/preview-web-6.4.9.tgz#21f7d251af0de64ae796834ead08ae4ed67e6456" + integrity sha512-fMB/akK14oc+4FBkeVJBtZQdxikOraXQSVn6zoVR93WVDR7JVeV+oz8rxjuK3n6ZEWN87iKH946k4jLoZ95tdw== dependencies: - "@storybook/addons" "6.4.3" - "@storybook/channel-postmessage" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/core-events" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/channel-postmessage" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/core-events" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" - "@storybook/store" "6.4.3" + "@storybook/store" "6.4.9" ansi-to-html "^0.6.11" core-js "^3.8.2" global "^4.4.0" - lodash "^4.17.20" + lodash "^4.17.21" qs "^6.10.0" regenerator-runtime "^0.13.7" synchronous-promise "^2.0.15" @@ -3538,28 +3455,28 @@ tslib "^2.0.0" "@storybook/react@^6.3.7": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/react/-/react-6.4.3.tgz#938f48758e7e785e6ad498e7d3405b2eb81db919" - integrity sha512-OifoqX13dQqR7CcQnGO8xiTUlapsL6iRoDLDWLoNcYduhJCgpuNmM8fJu8pPsUYzDR+hG0FNrx03LK8lkBwNjQ== + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/react/-/react-6.4.9.tgz#0b5effb07cf98bc73302b5486b9355ed545ee9fa" + integrity sha512-GVbCeii2dIKSD66pAdn9bY7mRoOzBE6ll+vRDW1n00FIvGfckmoIZtQHpurca7iNTAoufv8+t0L9i7IItdrUuw== dependencies: "@babel/preset-flow" "^7.12.1" "@babel/preset-react" "^7.12.10" "@pmmmwh/react-refresh-webpack-plugin" "^0.5.1" - "@storybook/addons" "6.4.3" - "@storybook/core" "6.4.3" - "@storybook/core-common" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/core" "6.4.9" + "@storybook/core-common" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" - "@storybook/node-logger" "6.4.3" + "@storybook/node-logger" "6.4.9" "@storybook/react-docgen-typescript-plugin" "1.0.2-canary.253f8c1.0" "@storybook/semver" "^7.3.2" - "@storybook/store" "6.4.3" + "@storybook/store" "6.4.9" "@types/webpack-env" "^1.16.0" babel-plugin-add-react-displayname "^0.0.5" babel-plugin-named-asset-import "^0.3.1" babel-plugin-react-docgen "^4.2.1" core-js "^3.8.2" global "^4.4.0" - lodash "^4.17.20" + lodash "^4.17.21" prop-types "^15.7.2" react-dev-utils "^11.0.4" react-refresh "^0.10.0" @@ -3568,17 +3485,17 @@ ts-dedent "^2.0.0" webpack "4" -"@storybook/router@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/router/-/router-6.4.3.tgz#3682793a14b8bb75105184450117e4df3505b820" - integrity sha512-13Xs9KK9vvnil7HPF8esuvwrpdb/DDn6SzMgEFJxKYVgJy6ASAu/rzFweezCZntT58F8kEqEn1sHMOjw4gN7hw== +"@storybook/router@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/router/-/router-6.4.9.tgz#7cc3f85494f4e14d38925e2802145df69a071201" + integrity sha512-GT2KtVHo/mBjxDBFB5ZtVJVf8vC+3p5kRlQC4jao68caVp7H24ikPOkcY54VnQwwe4A1aXpGbJXUyTisEPFlhQ== dependencies: - "@storybook/client-logger" "6.4.3" + "@storybook/client-logger" "6.4.9" core-js "^3.8.2" fast-deep-equal "^3.1.3" global "^4.4.0" history "5.0.0" - lodash "^4.17.20" + lodash "^4.17.21" memoizerific "^1.11.3" qs "^6.10.0" react-router "^6.0.0" @@ -3593,35 +3510,35 @@ core-js "^3.6.5" find-up "^4.1.0" -"@storybook/source-loader@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/source-loader/-/source-loader-6.4.3.tgz#8b89afd2a5529639e0ed35d357632cff1ac0aeca" - integrity sha512-BsYsZOVUYveD6oRN+Fae22ZFC2AYGoIrQj7loZPb3AWih8X4/3Jb70eoXB2yBzE+lVjQodTad/TDAmMR2OBVrg== +"@storybook/source-loader@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/source-loader/-/source-loader-6.4.9.tgz#918fe93e4bd52622a664398db79d5f71b384ce0b" + integrity sha512-J/Jpcc15hnWa2DB/EZ4gVJvdsY3b3CDIGW/NahuNXk36neS+g4lF3qqVNAEqQ1pPZ0O8gMgazyZPGm0MHwUWlw== dependencies: - "@storybook/addons" "6.4.3" - "@storybook/client-logger" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/client-logger" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" core-js "^3.8.2" estraverse "^5.2.0" global "^4.4.0" loader-utils "^2.0.0" - lodash "^4.17.20" + lodash "^4.17.21" prettier "^2.2.1" regenerator-runtime "^0.13.7" -"@storybook/store@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/store/-/store-6.4.3.tgz#5de37dd336a5cf4878910060e58658aa07924570" - integrity sha512-KbuvBWiqL9SCQCY45ZiCQueTTWWvX1ClXCoNoeVdZ0NskAV6e+tIhlSWSIpbVNG9zKUMmKj2Kkyq55D7cQrWQg== +"@storybook/store@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/store/-/store-6.4.9.tgz#613c6f13271276837c6a603a16199d2abf90153e" + integrity sha512-H30KfiM2XyGMJcLaOepCEUsU7S3C/f7t46s6Nhw0lc5w/6HTQc2jGV3GgG3lUAUAzEQoxmmu61w3N2a6eyRzmg== dependencies: - "@storybook/addons" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/core-events" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/core-events" "6.4.9" "@storybook/csf" "0.0.2--canary.87bc651.0" core-js "^3.8.2" fast-deep-equal "^3.1.3" global "^4.4.0" - lodash "^4.17.20" + lodash "^4.17.21" memoizerific "^1.11.3" regenerator-runtime "^0.13.7" slash "^3.0.0" @@ -3635,15 +3552,15 @@ resolved "https://registry.yarnpkg.com/@storybook/testing-react/-/testing-react-0.0.22.tgz#65d3defefbac0183eded0dafb601241d8f135c66" integrity sha512-XBJpH1cROXkwwKwD89kIcyhyMPEN5zfSyOUanrN+/Tx4nB5IwzVc/Om+7mtSFvh4UTSNOk5G42Y12KE/HbH7VA== -"@storybook/theming@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/theming/-/theming-6.4.3.tgz#97db57dde4cb1dfa1cc07181b8b1ece3557696ea" - integrity sha512-kXoDN8H6jfHLBawYB65E11yU7iRzej1HRG33CpY6ViPllV0IfIesUWXbrVQyJmTB2IQaoJpzwJN0Bt2KPaTOhw== +"@storybook/theming@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/theming/-/theming-6.4.9.tgz#8ece44007500b9a592e71eca693fbeac90803b0d" + integrity sha512-Do6GH6nKjxfnBg6djcIYAjss5FW9SRKASKxLYxX2RyWJBpz0m/8GfcGcRyORy0yFTk6jByA3Hs+WFH3GnEbWkw== dependencies: "@emotion/core" "^10.1.1" "@emotion/is-prop-valid" "^0.8.6" "@emotion/styled" "^10.0.27" - "@storybook/client-logger" "6.4.3" + "@storybook/client-logger" "6.4.9" core-js "^3.8.2" deep-object-diff "^1.1.0" emotion-theming "^10.0.27" @@ -3653,21 +3570,21 @@ resolve-from "^5.0.0" ts-dedent "^2.0.0" -"@storybook/ui@6.4.3": - version "6.4.3" - resolved "https://registry.yarnpkg.com/@storybook/ui/-/ui-6.4.3.tgz#099cdc7bc09c1d71dac9a9eb4698aa949ed2be6a" - integrity sha512-z9b90YctCrqNkfT17fhPKs5m11pn7Bqy7iOZg/1OFZZzRp4iYLzrGdkdwnGe/cpSaJ7pXwdmoJZCqZoXIrJCYQ== +"@storybook/ui@6.4.9": + version "6.4.9" + resolved "https://registry.yarnpkg.com/@storybook/ui/-/ui-6.4.9.tgz#c01413ca919ede20f84d19e556bf93dd2e7c5110" + integrity sha512-lJbsaMTH4SyhqUTmt+msSYI6fKSSfOnrzZVu6bQ73+MfRyGKh1ki2Nyhh+w8BiGEIOz02WlEpZC0y11FfgEgXw== dependencies: "@emotion/core" "^10.1.1" - "@storybook/addons" "6.4.3" - "@storybook/api" "6.4.3" - "@storybook/channels" "6.4.3" - "@storybook/client-logger" "6.4.3" - "@storybook/components" "6.4.3" - "@storybook/core-events" "6.4.3" - "@storybook/router" "6.4.3" + "@storybook/addons" "6.4.9" + "@storybook/api" "6.4.9" + "@storybook/channels" "6.4.9" + "@storybook/client-logger" "6.4.9" + "@storybook/components" "6.4.9" + "@storybook/core-events" "6.4.9" + "@storybook/router" "6.4.9" "@storybook/semver" "^7.3.2" - "@storybook/theming" "6.4.3" + "@storybook/theming" "6.4.9" copy-to-clipboard "^3.3.1" core-js "^3.8.2" core-js-pure "^3.8.2" @@ -3675,7 +3592,7 @@ emotion-theming "^10.0.27" fuse.js "^3.6.1" global "^4.4.0" - lodash "^4.17.20" + lodash "^4.17.21" markdown-to-jsx "^7.1.3" memoizerific "^1.11.3" polished "^4.0.5" @@ -3711,13 +3628,13 @@ pretty-format "^26.6.2" "@testing-library/jest-dom@^5.9.0": - version "5.15.1" - resolved "https://registry.yarnpkg.com/@testing-library/jest-dom/-/jest-dom-5.15.1.tgz#4c49ba4d244f235aec53f0a83498daeb4ee06c33" - integrity sha512-kmj8opVDRE1E4GXyLlESsQthCXK7An28dFWxhiMwD7ZUI7ZxA6sjdJRxLerD9Jd8cHX4BDc1jzXaaZKqzlUkvg== + version "5.16.1" + resolved "https://registry.yarnpkg.com/@testing-library/jest-dom/-/jest-dom-5.16.1.tgz#3db7df5ae97596264a7da9696fe14695ba02e51f" + integrity sha512-ajUJdfDIuTCadB79ukO+0l8O+QwN0LiSxDaYUTI4LndbbUsGi6rWU1SCexXzBA2NSjlVB9/vbkasQIL3tmPBjw== dependencies: "@babel/runtime" "^7.9.2" "@types/testing-library__jest-dom" "^5.9.1" - aria-query "^4.2.2" + aria-query "^5.0.0" chalk "^3.0.0" css "^3.0.0" css.escape "^1.5.1" @@ -3770,9 +3687,9 @@ "@types/babel__traverse" "*" "@types/babel__generator@*": - version "7.6.3" - resolved "https://registry.yarnpkg.com/@types/babel__generator/-/babel__generator-7.6.3.tgz#f456b4b2ce79137f768aa130d2423d2f0ccfaba5" - integrity sha512-/GWCmzJWqV7diQW54smJZzWbSFf4QYtF71WCKhcx6Ru/tFyQIY2eiiITcCAeuPbNSvT9YCGkVMqqvSk2Z0mXiA== + version "7.6.4" + resolved "https://registry.yarnpkg.com/@types/babel__generator/-/babel__generator-7.6.4.tgz#1f20ce4c5b1990b37900b63f050182d28c2439b7" + integrity sha512-tFkciB9j2K755yrTALxD44McOrk+gfpIpvC3sxHjRawj6PfnQxrse4Clq5y/Rq+G3mrBurMax/lG8Qn2t9mSsg== dependencies: "@babel/types" "^7.0.0" @@ -3864,9 +3781,9 @@ integrity sha512-vt+kDhq/M2ayberEtJcIN/hxXy1Pk+59g2FV/ZQceeaTyCtCucjL2Q7FXlFjtWn4n15KCr1NE2lNNFhp0lEThw== "@types/express-serve-static-core@*", "@types/express-serve-static-core@^4.17.18": - version "4.17.26" - resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-4.17.26.tgz#5d9a8eeecb9d5f9d7fc1d85f541512a84638ae88" - integrity sha512-zeu3tpouA043RHxW0gzRxwCHchMgftE8GArRsvYT0ByDMbn19olQHx5jLue0LxWY6iYtXb7rXmuVtSkhy9YZvQ== + version "4.17.27" + resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-4.17.27.tgz#7a776191e47295d2a05962ecbb3a4ce97e38b401" + integrity sha512-e/sVallzUTPdyOTiqi8O8pMdBBphscvI6E4JYaKlja4Lm+zh7UFSSdW5VMkRbhDtmrONqOUHOXRguPsDckzxNA== dependencies: "@types/node" "*" "@types/qs" "*" @@ -3963,9 +3880,9 @@ integrity sha512-A79HEEiwXTFtfY+Bcbo58M2GRYzCr9itHWzbzHVFNEYCcoU/MMGwYYf721gBrnhpj1s6RGVVha/IgNFnR0Iw/Q== "@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== + version "2.0.4" + resolved "https://registry.yarnpkg.com/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz#8467d4b3c087805d63580480890791277ce35c44" + integrity sha512-z/QT1XN4K4KYuslS23k62yDIDLwLFkzxOuMplDtObz0+y7VqJCaO2o+SPwHCvLFZh7xazvvoor2tA/hPz9ee7g== "@types/istanbul-lib-report@*": version "3.0.0" @@ -4120,9 +4037,9 @@ integrity sha512-s3nugnZumCC//n4moGGe6tkNMyYEdaDBitVjwPxXmR5lnMG5dHePinH2EdxkG3Rh1ghFHHixAG4NJhpJW1rthQ== "@types/node@^14.0.10", "@types/node@^14.14.31": - version "14.17.34" - resolved "https://registry.yarnpkg.com/@types/node/-/node-14.17.34.tgz#fe4b38b3f07617c0fa31ae923fca9249641038f0" - integrity sha512-USUftMYpmuMzeWobskoPfzDi+vkpe0dvcOBRNOscFrGxVp4jomnRxWuVohgqBow2xyIPC0S3gjxV/5079jhmDg== + version "14.18.3" + resolved "https://registry.yarnpkg.com/@types/node/-/node-14.18.3.tgz#b3682cfd9d5542b025df13233d073cb4347f63f3" + integrity sha512-GtTH2crF4MtOIrrAa+jgTV9JX/PfoUCYr6MiZw7O/dkZu5b6gm5dc1nAL0jwGo4ortSBBtGyeVaxdC8X6V+pLg== "@types/nodemailer@^6.4.4": version "6.4.4" @@ -4137,9 +4054,9 @@ integrity sha512-Gj7cI7z+98M282Tqmp2K5EIsoouUEzbBJhQQzDE3jSIRk6r9gsz0oUokqIUR4u1R3dMHo0pDHM7sNOHyhulypw== "@types/npmlog@^4.1.2": - version "4.1.3" - resolved "https://registry.yarnpkg.com/@types/npmlog/-/npmlog-4.1.3.tgz#9c24b49a97e25cf15a890ff404764080d7942132" - integrity sha512-1TcL7YDYCtnHmLhTWbum+IIwLlvpaHoEKS2KNIngEwLzwgDeHaebaEHHbQp8IqzNQ9IYiboLKUjAf7MZqG63+w== + version "4.1.4" + resolved "https://registry.yarnpkg.com/@types/npmlog/-/npmlog-4.1.4.tgz#30eb872153c7ead3e8688c476054ddca004115f6" + integrity sha512-WKG4gTr8przEZBiJ5r3s8ZIAoMXNbOgQ+j/d5O4X3x6kZJRLNvyUJuUK/KoG3+8BaOHPhp2m7WC6JKKeovDSzQ== "@types/overlayscrollbars@^1.12.0": version "1.12.1" @@ -4262,9 +4179,9 @@ "@types/node" "*" "@types/shelljs@^0.8.8": - version "0.8.9" - resolved "https://registry.yarnpkg.com/@types/shelljs/-/shelljs-0.8.9.tgz#45dd8501aa9882976ca3610517dac3831c2fbbf4" - integrity sha512-flVe1dvlrCyQJN/SGrnBxqHG+RzXrVKsmjD8WS/qYHpq5UPjfq7UWFBENP0ZuOl0g6OpAlL6iBoLSvKYUUmyQw== + version "0.8.10" + resolved "https://registry.yarnpkg.com/@types/shelljs/-/shelljs-0.8.10.tgz#c33079c9b41a9d6f788f98f1d8a68f880a14f454" + integrity sha512-nhBdUA/n0nRo1B6E4BuRnUvllYAqal4T9zd91ZDnBh+qQMQTwvxmJHx6xEn/0vdjP2kqEA5eVeLazs4nMxeuFg== dependencies: "@types/glob" "*" "@types/node" "*" @@ -4324,9 +4241,9 @@ "@types/node" "*" "@types/tmp@^0.2.2": - version "0.2.2" - resolved "https://registry.yarnpkg.com/@types/tmp/-/tmp-0.2.2.tgz#424537a3b91828cb26aaf697f21ae3cd1b69f7e7" - integrity sha512-MhSa0yylXtVMsyT8qFpHA1DLHj4DvQGH5ntxrhHSh8PxUVNi35Wk+P5hVgqbO2qZqOotqr9jaoPRL+iRjWYm/A== + version "0.2.3" + resolved "https://registry.yarnpkg.com/@types/tmp/-/tmp-0.2.3.tgz#908bfb113419fd6a42273674c00994d40902c165" + integrity sha512-dDZH/tXzwjutnuk4UacGgFRwV+JSLaXL1ikvidfJprkb7L9Nx1njcRHHmi3Dsvt7pgqqTEeucQuOrWHPFgzVHA== "@types/uglify-js@*": version "3.13.1" @@ -4865,9 +4782,9 @@ acorn@^7.0.0, acorn@^7.1.1, acorn@^7.4.0, acorn@^7.4.1: integrity sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A== acorn@^8.2.4: - version "8.6.0" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.6.0.tgz#e3692ba0eb1a0c83eaa4f37f5fa7368dd7142895" - integrity sha512-U1riIR+lBSNi3IbxtaHOIKdH8sLFv3NYfNv8sg7ZsNhcfl4HF2++BfqqrNAxoCLQW1iiylOj76ecnaUxz+z9yw== + version "8.7.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.7.0.tgz#90951fde0f8f09df93549481e5fc141445b791cf" + integrity sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ== address@1.1.2, address@^1.0.1: version "1.1.2" @@ -5310,6 +5227,11 @@ aria-query@^4.2.2: "@babel/runtime" "^7.10.2" "@babel/runtime-corejs3" "^7.10.2" +aria-query@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/aria-query/-/aria-query-5.0.0.tgz#210c21aaf469613ee8c9a62c7f86525e058db52c" + integrity sha512-V+SM7AbUwJ+EBnB8+DXs0hPZHO0W6pqBcc0dW90OwtVG02PswOu/teuARoLQjdDOH+t9pJgGnW5/Qmouf3gPJg== + arr-diff@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-4.0.0.tgz#d6461074febfec71e7e15235761a329a5dc7c520" @@ -5722,9 +5644,9 @@ babel-plugin-macros@^3.0.1: resolve "^1.19.0" babel-plugin-named-asset-import@^0.3.1: - version "0.3.7" - resolved "https://registry.yarnpkg.com/babel-plugin-named-asset-import/-/babel-plugin-named-asset-import-0.3.7.tgz#156cd55d3f1228a5765774340937afc8398067dd" - integrity sha512-squySRkf+6JGnvjoUtDEjSREJEBirnXi9NqP6rjSYsylxQxqBTz+pkmf395i9E2zsvmYUaI40BHo6SqZUdydlw== + version "0.3.8" + resolved "https://registry.yarnpkg.com/babel-plugin-named-asset-import/-/babel-plugin-named-asset-import-0.3.8.tgz#6b7fa43c59229685368683c28bc9734f24524cc2" + integrity sha512-WXiAc++qo7XcJ1ZnTYGtLxmBCVbddAml3CEXgWaBzNzLNoxtQ8AiGEFDMOhot9XjTCQbvP5E77Fj9Gk924f00Q== babel-plugin-polyfill-corejs2@^0.3.0: version "0.3.0" @@ -5953,7 +5875,12 @@ blob-util@^2.0.2: resolved "https://registry.yarnpkg.com/blob-util/-/blob-util-2.0.2.tgz#3b4e3c281111bb7f11128518006cdc60b403a1eb" integrity sha512-T7JQa+zsXXEa6/8ZhHcQEW1UFfVM49Ts65uBkFL6fz2QmrElqmbajIDJvuA0tEhRe5eIjpV9ZF+0RfZR9voJFQ== -bluebird@3.7.2, bluebird@^3.3.5, bluebird@^3.5.5, bluebird@^3.7.1, bluebird@^3.7.2: +bluebird@3.7.1: + version "3.7.1" + resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.7.1.tgz#df70e302b471d7473489acf26a93d63b53f874de" + integrity sha512-DdmyoGCleJnkbp3nkbxTLJ18rjDsE4yCggEwKNXkeV123sPNfOCYeDoeuOY+F2FrSjO1YXcTU+dsy96KMy+gcg== + +bluebird@3.7.2, bluebird@^3.3.5, bluebird@^3.5.5, bluebird@^3.7.2: version "3.7.2" resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.7.2.tgz#9f229c15be272454ffa973ace0dbee79a1b0c36f" integrity sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg== @@ -5968,7 +5895,7 @@ bn.js@^5.0.0, bn.js@^5.1.1: resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-5.2.0.tgz#358860674396c6997771a9d051fcc1b57d4ae002" integrity sha512-D7iWRBvnZE8ecXiLj/9wbxH7Tk79fAh8IHaTNq1RWRixsS02W+5qS+iE9yq6RYl0asXx5tw0bLhmT5pIfbSquw== -body-parser@1.19.0, body-parser@^1.18.3: +body-parser@1.19.0: version "1.19.0" resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.19.0.tgz#96b2709e57c9c4e09a6fd66a8fd979844f69f08a" integrity sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw== @@ -5984,6 +5911,22 @@ body-parser@1.19.0, body-parser@^1.18.3: raw-body "2.4.0" type-is "~1.6.17" +body-parser@1.19.1, body-parser@^1.18.3: + version "1.19.1" + resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.19.1.tgz#1499abbaa9274af3ecc9f6f10396c995943e31d4" + integrity sha512-8ljfQi5eBk8EJfECMrgqNGWPEY5jWP+1IzkzkGdFFEwFQZZyaZ21UqdaHktgiMlH0xLHqIFtE/u2OYE5dOtViA== + dependencies: + bytes "3.1.1" + content-type "~1.0.4" + debug "2.6.9" + depd "~1.1.2" + http-errors "1.8.1" + iconv-lite "0.4.24" + on-finished "~2.3.0" + qs "6.9.6" + raw-body "2.4.2" + type-is "~1.6.18" + boolbase@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/boolbase/-/boolbase-1.0.0.tgz#68dff5fbe60c51eb37725ea9e3ed310dcc1e776e" @@ -6271,18 +6214,7 @@ browserslist@4.16.6: escalade "^3.1.1" node-releases "^1.1.71" -browserslist@^4.12.0, browserslist@^4.18.1, browserslist@^4.9.1: - version "4.18.1" - resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.18.1.tgz#60d3920f25b6860eb917c6c7b185576f4d8b017f" - integrity sha512-8ScCzdpPwR2wQh8IT82CA2VgDwjHyqMovPBZSNH54+tm4Jk2pCuv90gmAdH6J84OCRWi0b4gMe6O6XPXuJnjgQ== - dependencies: - caniuse-lite "^1.0.30001280" - electron-to-chromium "^1.3.896" - escalade "^3.1.1" - node-releases "^2.0.1" - picocolors "^1.0.0" - -browserslist@^4.17.5: +browserslist@^4.12.0, browserslist@^4.17.5, browserslist@^4.19.1, browserslist@^4.9.1: version "4.19.1" resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.19.1.tgz#4ac0435b35ab655896c31d53018b6dd5e9e4c9a3" integrity sha512-u2tbbG5PdKRTUoctO3NBD8FQ5HdPh1ZXPHzp1rwaa5jTc+RV9/+RlWiAIKmjRPQF+xbGM9Kklj5bZQFa2s/38A== @@ -6300,7 +6232,7 @@ bser@2.1.1: dependencies: node-int64 "^0.4.0" -bson@*, bson@^4.2.2, bson@^4.5.4: +bson@*, bson@^4.2.2, bson@^4.6.0: version "4.6.0" resolved "https://registry.yarnpkg.com/bson/-/bson-4.6.0.tgz#15c3b39ba3940c3d915a0c44d51459f4b4fbf1b2" integrity sha512-8jw1NU1hglS+Da1jDOUYuNcBJ4cNHCFIqzlwoFNnsTOg2R/ox0aTYcTiBN4dzRa9q7Cvy6XErh3L8ReTEb9AQQ== @@ -6387,6 +6319,11 @@ bytes@3.1.0: resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.0.tgz#f6cf7933a360e0588fa9fde85651cdc7f805d1f6" integrity sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg== +bytes@3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.1.tgz#3f018291cb4cbad9accb6e6970bca9c8889e879a" + integrity sha512-dWe4nWO/ruEOY7HkUJ5gFt1DCFV9zPRoJr8pV0/ASQermOZjtq8jMjOprC0Kd10GLN+l7xaUPvxzJFWtxGu8Fg== + c8@^7.6.0: version "7.10.0" resolved "https://registry.yarnpkg.com/c8/-/c8-7.10.0.tgz#c539ebb15d246b03b0c887165982c49293958a73" @@ -6540,15 +6477,10 @@ camelcase@^6.0.0, camelcase@^6.1.0, camelcase@^6.2.0: resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.2.1.tgz#250fd350cfd555d0d2160b1d51510eaf8326e86e" integrity sha512-tVI4q5jjFV5CavAU8DXfza/TJcZutVKo/5Foskmsqcm0MsL91moHvwiGNnqaa2o6PF/7yT5ikDRcVcl8Rj6LCA== -caniuse-lite@^1.0.30001109, caniuse-lite@^1.0.30001125, caniuse-lite@^1.0.30001202, caniuse-lite@^1.0.30001219, caniuse-lite@^1.0.30001228: - version "1.0.30001283" - resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001283.tgz#8573685bdae4d733ef18f78d44ba0ca5fe9e896b" - integrity sha512-9RoKo841j1GQFSJz/nCXOj0sD7tHBtlowjYlrqIUS812x9/emfBLBt6IyMz1zIaYc/eRL8Cs6HPUVi2Hzq4sIg== - -caniuse-lite@^1.0.30001280, caniuse-lite@^1.0.30001286: - version "1.0.30001291" - resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001291.tgz#08a8d2cfea0b2cf2e1d94dd795942d0daef6108c" - integrity sha512-roMV5V0HNGgJ88s42eE70sstqGW/gwFndosYrikHthw98N5tLnOTxFqMLQjZVRxTWFlJ4rn+MsgXrR7MDPY4jA== +caniuse-lite@^1.0.30001109, caniuse-lite@^1.0.30001125, caniuse-lite@^1.0.30001202, caniuse-lite@^1.0.30001219, caniuse-lite@^1.0.30001228, caniuse-lite@^1.0.30001286: + version "1.0.30001294" + resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001294.tgz#4849f27b101fd59ddee3751598c663801032533d" + integrity sha512-LiMlrs1nSKZ8qkNhpUf5KD0Al1KCBE3zaT7OLOwEkagXMEDij98SiOovn9wxVGQpklk9vVC/pUSqgYmkmKOS8g== capture-exit@^2.0.0: version "2.0.0" @@ -7185,6 +7117,13 @@ content-disposition@0.5.3: dependencies: safe-buffer "5.1.2" +content-disposition@0.5.4: + version "0.5.4" + resolved "https://registry.yarnpkg.com/content-disposition/-/content-disposition-0.5.4.tgz#8b82b4efac82512a02bb0b1dcec9d2c5e8eb5bfe" + integrity sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ== + dependencies: + safe-buffer "5.2.1" + content-type@~1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/content-type/-/content-type-1.0.4.tgz#e138cc75e040c727b1966fe5e5f8c9aee256fe3b" @@ -7219,7 +7158,7 @@ cookie@0.4.0: resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.4.0.tgz#beb437e7022b3b6d49019d088665303ebe9c14ba" integrity sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg== -cookie@^0.4.0, cookie@^0.4.1: +cookie@0.4.1, cookie@^0.4.0, cookie@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.4.1.tgz#afd713fe26ebd21ba95ceb61f9a8116e50a537d1" integrity sha512-ZwrFkGJxUR3EIoXtO+yVE69Eb7KlixbaeAWfBQB9vVsNn/o+Yw69gBWSSDK825hQNdN+wF8zELf3dFNl/kxkUA== @@ -7254,17 +7193,17 @@ copy-to-clipboard@^3.3.1: toggle-selection "^1.0.6" core-js-compat@^3.18.0, core-js-compat@^3.19.1, core-js-compat@^3.6.2, core-js-compat@^3.8.1: - version "3.19.2" - resolved "https://registry.yarnpkg.com/core-js-compat/-/core-js-compat-3.19.2.tgz#18066a3404a302433cb0aa8be82dd3d75c76e5c4" - integrity sha512-ObBY1W5vx/LFFMaL1P5Udo4Npib6fu+cMokeziWkA8Tns4FcDemKF5j9JvaI5JhdkW8EQJQGJN1EcrzmEwuAqQ== + version "3.20.1" + resolved "https://registry.yarnpkg.com/core-js-compat/-/core-js-compat-3.20.1.tgz#96917b4db634fbbbc7b36575b2e8fcbf7e4f9691" + integrity sha512-AVhKZNpqMV3Jz8hU0YEXXE06qoxtQGsAqU0u1neUngz5IusDJRX/ZJ6t3i7mS7QxNyEONbCo14GprkBrxPlTZA== dependencies: - browserslist "^4.18.1" + browserslist "^4.19.1" semver "7.0.0" core-js-pure@^3.10.2, core-js-pure@^3.19.0, core-js-pure@^3.8.1, core-js-pure@^3.8.2: - version "3.19.2" - resolved "https://registry.yarnpkg.com/core-js-pure/-/core-js-pure-3.19.2.tgz#26b5bfb503178cff6e3e115bc2ba6c6419383680" - integrity sha512-5LkcgQEy8pFeVnd/zomkUBSwnmIxuF1C8E9KrMAbOc8f34IBT9RGvTYeNDdp1PnvMJrrVhvk1hg/yVV5h/znlg== + version "3.20.1" + resolved "https://registry.yarnpkg.com/core-js-pure/-/core-js-pure-3.20.1.tgz#f7a2c62f98de83e4da8fca7b78846d3a2f542145" + integrity sha512-yeNNr3L9cEBwNy6vhhIJ0nko7fE7uFO6PgawcacGt2VWep4WqQx0RiqlkgSP7kqUMC1IKdfO9qPeWXcUheHLVQ== core-js@^1.0.0: version "1.2.7" @@ -7272,9 +7211,9 @@ core-js@^1.0.0: integrity sha1-ZSKUwUZR2yj6k70tX/KYOk8IxjY= core-js@^3, core-js@^3.0.4, core-js@^3.6.5, core-js@^3.8.2: - version "3.19.2" - resolved "https://registry.yarnpkg.com/core-js/-/core-js-3.19.2.tgz#ae216d7f4f7e924d9a2e3ff1e4b1940220f9157b" - integrity sha512-ciYCResnLIATSsXuXnIOH4CbdfgV+H1Ltg16hJFN7/v6OxqnFr/IFGeLacaZ+fHLAm0TBbXwNK9/DNBzBUrO/g== + version "3.20.1" + resolved "https://registry.yarnpkg.com/core-js/-/core-js-3.20.1.tgz#eb1598047b7813572f1dc24b7c6a95528c99eef3" + integrity sha512-btdpStYFQScnNVQ5slVcr858KP0YWYjV16eGJQw8Gg7CWtu/2qNvIM3qVRIR3n1pK2R9NNOrTevbvAYxajwEjg== core-util-is@1.0.2: version "1.0.2" @@ -7465,15 +7404,15 @@ css-loader@^3.6.0: semver "^6.3.0" css-select@^4.1.3: - version "4.1.3" - resolved "https://registry.yarnpkg.com/css-select/-/css-select-4.1.3.tgz#a70440f70317f2669118ad74ff105e65849c7067" - integrity sha512-gT3wBNd9Nj49rAbmtFHj1cljIAOLYSX1nZ8CB7TBO3INYckygm5B7LISU/szY//YmdiSLbJvDLOx9VnMVpMBxA== + version "4.2.1" + resolved "https://registry.yarnpkg.com/css-select/-/css-select-4.2.1.tgz#9e665d6ae4c7f9d65dbe69d0316e3221fb274cdd" + integrity sha512-/aUslKhzkTNCQUB2qTX84lVmfia9NyjP3WpDGtj/WxhwBzWBYUV3DgUpurHTme8UTPcPlAD1DJ+b0nN/t50zDQ== dependencies: boolbase "^1.0.0" - css-what "^5.0.0" - domhandler "^4.2.0" - domutils "^2.6.0" - nth-check "^2.0.0" + css-what "^5.1.0" + domhandler "^4.3.0" + domutils "^2.8.0" + nth-check "^2.0.1" css-vendor@^0.3.8: version "0.3.8" @@ -7482,7 +7421,7 @@ css-vendor@^0.3.8: dependencies: is-in-browser "^1.0.2" -css-what@^5.0.0: +css-what@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/css-what/-/css-what-5.1.0.tgz#3f7b707aadf633baf62c2ceb8579b545bb40f7fe" integrity sha512-arSMRWIIFY0hV8pIxZMEfmMI47Wj3R/aWpZDDxWYCPEiOMv6tfOrnpDtgxBYPEQD4V0Y/958+1TdC3iWTFcUPw== @@ -7558,11 +7497,11 @@ cyclist@^1.0.1: integrity sha1-WW6WmP0MgOEgOMK4LW6xs1tiJNk= cypress@*, cypress@^9: - version "9.1.0" - resolved "https://registry.yarnpkg.com/cypress/-/cypress-9.1.0.tgz#5d23c1b363b7d4853009c74a422a083a8ad2601c" - integrity sha512-fyXcCN51vixkPrz/vO/Qy6WL3hKYJzCQFeWofOpGOFewVVXrGfmfSOGFntXpzWBXsIwPn3wzW0HOFw51jZajNQ== + version "9.2.0" + resolved "https://registry.yarnpkg.com/cypress/-/cypress-9.2.0.tgz#727c20b4662167890db81d5f6ba615231835b17d" + integrity sha512-Jn26Tprhfzh/a66Sdj9SoaYlnNX6Mjfmj5PHu2a7l3YHXhrgmavM368wjCmgrxC6KHTOv9SpMQGhAJn+upDViA== dependencies: - "@cypress/request" "^2.88.7" + "@cypress/request" "^2.88.10" "@cypress/xvfb" "^1.2.4" "@types/node" "^14.14.31" "@types/sinonjs__fake-timers" "^6.0.2" @@ -8060,7 +7999,7 @@ domhandler@^2.3.0: dependencies: domelementtype "1" -domhandler@^4.0.0, domhandler@^4.2.0: +domhandler@^4.0.0, domhandler@^4.2.0, domhandler@^4.3.0: version "4.3.0" resolved "https://registry.yarnpkg.com/domhandler/-/domhandler-4.3.0.tgz#16c658c626cf966967e306f966b431f77d4a5626" integrity sha512-fC0aXNQXqKSFTr2wDNZDhsEYjCiYsDWl3D01kwt25hm1YIPyDGHvvi3rw+PLqHAl/m71MaiF7d5zvBr0p5UB2g== @@ -8075,7 +8014,7 @@ domutils@^1.5.1: dom-serializer "0" domelementtype "1" -domutils@^2.5.2, domutils@^2.6.0: +domutils@^2.5.2, domutils@^2.8.0: version "2.8.0" resolved "https://registry.yarnpkg.com/domutils/-/domutils-2.8.0.tgz#4437def5db6e2d1f5d6ee859bd95ca7d02048135" integrity sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A== @@ -8163,15 +8102,10 @@ ejs@^2.6.1: resolved "https://registry.yarnpkg.com/ejs/-/ejs-2.7.4.tgz#48661287573dcc53e366c7a1ae52c3a120eec9ba" integrity sha512-7vmuyh5+kuUyJKePhQfRQBhXV5Ce+RnaeeQArKu1EAMpL3WbgMt5WG6uQZpEVvYSSsxMXRKOewtDk9RaTKXRlA== -electron-to-chromium@^1.3.564, electron-to-chromium@^1.3.723: - version "1.4.7" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.7.tgz#58e0b4ec9096ee1422e4d9e83ceeb05b0cf076eb" - integrity sha512-UPy2MsQw1OdcbxR7fvwWZH/rXcv+V26+uvQVHx0fGa1kqRfydtfOw+NMGAvZJ63hyaH4aEBxbhSEtqbpliSNWA== - -electron-to-chromium@^1.3.896, electron-to-chromium@^1.4.17: - version "1.4.24" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.24.tgz#9cf8a92d5729c480ee47ff0aa5555f57467ae2fa" - integrity sha512-erwx5r69B/WFfFuF2jcNN0817BfDBdC4765kQ6WltOMuwsimlQo3JTEq0Cle+wpHralwdeX3OfAtw/mHxPK0Wg== +electron-to-chromium@^1.3.564, electron-to-chromium@^1.3.723, electron-to-chromium@^1.4.17: + version "1.4.29" + resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.29.tgz#a9b85ab888d0122124c9647c04d8dd246fae94b6" + integrity sha512-N2Jbwxo5Rum8G2YXeUxycs1sv4Qme/ry71HG73bv8BvZl+I/4JtRgK/En+ST/Wh/yF1fqvVCY4jZBgMxnhjtBA== elegant-spinner@^1.0.1: version "1.0.1" @@ -8179,9 +8113,9 @@ elegant-spinner@^1.0.1: integrity sha1-2wQ1IcldfjA/2PNFvtwzSc+wcp4= element-resize-detector@^1.2.2: - version "1.2.3" - resolved "https://registry.yarnpkg.com/element-resize-detector/-/element-resize-detector-1.2.3.tgz#5078d9b99398fe4c589f8c8df94ff99e5d413ff3" - integrity sha512-+dhNzUgLpq9ol5tyhoG7YLoXL3ssjfFW+0gpszXPwRU6NjGr1fVHMEAF8fVzIiRJq57Nre0RFeIjJwI8Nh2NmQ== + version "1.2.4" + resolved "https://registry.yarnpkg.com/element-resize-detector/-/element-resize-detector-1.2.4.tgz#3e6c5982dd77508b5fa7e6d5c02170e26325c9b1" + integrity sha512-Fl5Ftk6WwXE0wqCgNoseKWndjzZlDCwuPTcoVZfCP9R3EHQF8qUtr3YUPNETegRBOKqQKPW3n4kiIWngGi8tKg== dependencies: batch-processor "1.0.0" @@ -8297,9 +8231,9 @@ entities@~2.0: integrity sha512-MyoZ0jgnLvB2X3Lg5HqpFmn1kybDiIfEQmKzTb5apr51Rb+T3KdmMiqa70T+bhGnyv7bQ6WMj2QMHpGMmlrUYQ== env-ci@^5.0.2: - version "5.4.1" - resolved "https://registry.yarnpkg.com/env-ci/-/env-ci-5.4.1.tgz#814387ddd6857b37472ef612361f34d720c29a18" - integrity sha512-xyuCtyFZLpnW5aH0JstETKTSMwHHQX4m42juzEZzvbUCJX7RiPVlhASKM0f/cJ4vvI/+txMkZ7F5To6dCdPYhg== + version "5.5.0" + resolved "https://registry.yarnpkg.com/env-ci/-/env-ci-5.5.0.tgz#43364e3554d261a586dec707bc32be81112b545f" + integrity sha512-o0JdWIbOLP+WJKIUt36hz1ImQQFuN92nhsfTkHHap+J8CiI8WgGpH/a9jEGHh4/TU5BUUGjlnKXNoDb57+ne+A== dependencies: execa "^5.0.0" fromentries "^1.3.2" @@ -8381,9 +8315,9 @@ es-to-primitive@^1.2.1: is-symbol "^1.0.2" es5-shim@^4.5.13: - version "4.6.2" - resolved "https://registry.yarnpkg.com/es5-shim/-/es5-shim-4.6.2.tgz#827cdd0c6fb5beb26fd368d65430e8b5eaeba942" - integrity sha512-n0XTVMGps+Deyr38jtqKPR5F5hb9owYeRQcKJW39eFvzUk/u/9Ww315werRzbiNMnHCUw/YHDPBphTlEnzdi+A== + version "4.6.4" + resolved "https://registry.yarnpkg.com/es5-shim/-/es5-shim-4.6.4.tgz#10ce5f06c7bccfdd60b4e08edf95c7e2fbc1dc2a" + integrity sha512-Z0f7OUYZ8JfqT12d3Tgh2ErxIH5Shaz97GE8qyDG9quxb2Hmh2vvFHlOFjx6lzyD0CRgvJfnNYcisjdbRp7MPw== es6-error@^4.0.1: version "4.1.1" @@ -8443,11 +8377,11 @@ escodegen@^2.0.0: source-map "~0.6.1" eslint-config-next@^11.1.0: - version "11.1.2" - resolved "https://registry.yarnpkg.com/eslint-config-next/-/eslint-config-next-11.1.2.tgz#73c918f2fa6120d5f65080bf3fcf6b154905707e" - integrity sha512-dFutecxX2Z5/QVlLwdtKt+gIfmNMP8Qx6/qZh3LM/DFVdGJEAnUKrr4VwGmACB2kx/PQ5bx3R+QxnEg4fDPiTg== + version "11.1.3" + resolved "https://registry.yarnpkg.com/eslint-config-next/-/eslint-config-next-11.1.3.tgz#6431a3a7356d360bdd5bb18827640715164af8e9" + integrity sha512-j9y/ZG2u+8od/kIz7X8uQ7F/Y8fKp/P/WqLi8SOLXJn2VqJ79IB4J1a6MOXPZF9sUeEnwuRHS8+1u5bIBeSxKw== dependencies: - "@next/eslint-plugin-next" "11.1.2" + "@next/eslint-plugin-next" "11.1.3" "@rushstack/eslint-patch" "^1.0.6" "@typescript-eslint/parser" "^4.20.0" eslint-import-resolver-node "^0.3.4" @@ -8535,9 +8469,9 @@ eslint-plugin-react-hooks@^4.2.0: integrity sha512-XslZy0LnMn+84NEG9jSGR6eGqaZB3133L8xewQo3fQagbQuGt7a63gf+P1NGKZavEYEC3UXaWEAA/AqDkuN6xA== eslint-plugin-react@^7.23.1: - version "7.27.1" - resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-7.27.1.tgz#469202442506616f77a854d91babaae1ec174b45" - integrity sha512-meyunDjMMYeWr/4EBLTV1op3iSG3mjT/pz5gti38UzfM4OPpNc2m0t2xvKCOMU5D6FSdd34BIMFOvQbW+i8GAA== + version "7.28.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-7.28.0.tgz#8f3ff450677571a659ce76efc6d80b6a525adbdf" + integrity sha512-IOlFIRHzWfEQQKcAD4iyYDndHwTQiCMcJVJjxempf203jnNLUnW34AXLrV33+nEXoifJE2ZEGmcjKPL8957eSw== dependencies: array-includes "^3.1.4" array.prototype.flatmap "^1.2.5" @@ -8847,7 +8781,7 @@ expect@^26.6.2: jest-message-util "^26.6.2" jest-regex-util "^26.0.0" -express@4.17.1, express@^4.16.3, express@^4.17.1: +express@4.17.1: version "4.17.1" resolved "https://registry.yarnpkg.com/express/-/express-4.17.1.tgz#4491fc38605cf51f8629d39c2b5d026f98a4c134" integrity sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g== @@ -8883,6 +8817,42 @@ express@4.17.1, express@^4.16.3, express@^4.17.1: utils-merge "1.0.1" vary "~1.1.2" +express@^4.16.3, express@^4.17.1: + version "4.17.2" + resolved "https://registry.yarnpkg.com/express/-/express-4.17.2.tgz#c18369f265297319beed4e5558753cc8c1364cb3" + integrity sha512-oxlxJxcQlYwqPWKVJJtvQiwHgosH/LrLSPA+H4UxpyvSS6jC5aH+5MoHFM+KABgTOt0APue4w66Ha8jCUo9QGg== + dependencies: + accepts "~1.3.7" + array-flatten "1.1.1" + body-parser "1.19.1" + content-disposition "0.5.4" + content-type "~1.0.4" + cookie "0.4.1" + cookie-signature "1.0.6" + debug "2.6.9" + depd "~1.1.2" + encodeurl "~1.0.2" + escape-html "~1.0.3" + etag "~1.8.1" + finalhandler "~1.1.2" + fresh "0.5.2" + merge-descriptors "1.0.1" + methods "~1.1.2" + on-finished "~2.3.0" + parseurl "~1.3.3" + path-to-regexp "0.1.7" + proxy-addr "~2.0.7" + qs "6.9.6" + range-parser "~1.2.1" + safe-buffer "5.2.1" + send "0.17.2" + serve-static "1.14.2" + setprototypeof "1.2.0" + statuses "~1.5.0" + type-is "~1.6.18" + utils-merge "1.0.1" + vary "~1.1.2" + extend-shallow@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-2.0.1.tgz#51af7d614ad9a9f610ea1bafbb989d6b1c56890f" @@ -9233,9 +9203,9 @@ flush-write-stream@^1.0.0: readable-stream "^2.3.6" follow-redirects@^1.14.0: - version "1.14.5" - resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.14.5.tgz#f09a5848981d3c772b5392309778523f8d85c381" - integrity sha512-wtphSXy7d4/OR+MvIFbCVBDzZ5520qV8XfPklSN5QtxuMUJZ+b0Wnst1e1lCDocfzuCkHqj8k0FpZqO+UIaKNA== + version "1.14.6" + resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.14.6.tgz#8cfb281bbc035b3c067d6cd975b0f6ade6e855cd" + integrity sha512-fhUl5EwSJbbl8AR+uYL2KQDxLkdSjZGR36xy46AO7cOMTrCMON6Sa28FmAnC2tRTDbd/Uuzz3aJBv7EBN7JH8A== for-each@^0.3.3: version "0.3.3" @@ -9482,9 +9452,9 @@ fuse.js@^3.6.1: integrity sha512-hT9yh/tiinkmirKrlv4KWOjztdoZo1mx9Qh4KvWqC7isoXwdUY3PNWUxceF4/qO9R6riA2C29jdTOeQOIROjgw== gauge@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/gauge/-/gauge-3.0.1.tgz#4bea07bcde3782f06dced8950e51307aa0f4a346" - integrity sha512-6STz6KdQgxO4S/ko+AbjlFGGdGcknluoqU+79GOFCDqqyYj5OanQf9AjxwN0jCidtT+ziPMmPSt9E4hfQ0CwIQ== + version "3.0.2" + resolved "https://registry.yarnpkg.com/gauge/-/gauge-3.0.2.tgz#03bf4441c044383908bcfa0656ad91803259b395" + integrity sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q== dependencies: aproba "^1.0.3 || ^2.0.0" color-support "^1.1.2" @@ -9492,8 +9462,8 @@ gauge@^3.0.0: has-unicode "^2.0.1" object-assign "^4.1.1" signal-exit "^3.0.0" - string-width "^1.0.1 || ^2.0.0" - strip-ansi "^3.0.1 || ^4.0.0" + string-width "^4.2.3" + strip-ansi "^6.0.1" wide-align "^1.1.2" gensync@^1.0.0-beta.1, gensync@^1.0.0-beta.2: @@ -10082,10 +10052,10 @@ history@5.0.0: dependencies: "@babel/runtime" "^7.7.6" -history@^5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/history/-/history-5.1.0.tgz#2e93c09c064194d38d52ed62afd0afc9d9b01ece" - integrity sha512-zPuQgPacm2vH2xdORvGGz1wQMuHSIB56yNAy5FnLuwOwgSYyPKptJtcMm6Ev+hRGeS+GzhbmRacHzvlESbFwDg== +history@^5.2.0: + version "5.2.0" + resolved "https://registry.yarnpkg.com/history/-/history-5.2.0.tgz#7cdd31cf9bac3c5d31f09c231c9928fad0007b7c" + integrity sha512-uPSF6lAJb3nSePJ43hN3eKj1dTWpN9gMod0ZssbFTIsen+WehTmEadgL+kg78xLJFdRfrrC//SavDzmRVdE+Ig== dependencies: "@babel/runtime" "^7.7.6" @@ -10139,7 +10109,7 @@ html-entities@^2.1.0: resolved "https://registry.yarnpkg.com/html-entities/-/html-entities-2.3.2.tgz#760b404685cb1d794e4f4b744332e3b00dcfe488" integrity sha512-c3Ab/url5ksaT0WyleslpBEthOzWhrjQbg75y7XUsfSzi3Dgzt0l8w5e7DylRn15MTlMMD58dTfzddNS2kcAjQ== -html-escaper@^2.0.0: +html-escaper@^2.0.0, html-escaper@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/html-escaper/-/html-escaper-2.0.2.tgz#dfd60027da36a36dfcbe236262c00a5822681453" integrity sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg== @@ -10259,7 +10229,7 @@ http-errors@1.7.3, http-errors@~1.7.2: statuses ">= 1.5.0 < 2" toidentifier "1.0.0" -http-errors@^1.7.3: +http-errors@1.8.1, http-errors@^1.7.3: version "1.8.1" resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.8.1.tgz#7c3f28577cbc8a207388455dbd62295ed07bd68c" integrity sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g== @@ -10416,9 +10386,9 @@ ignore@^4.0.3, ignore@^4.0.6: integrity sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg== ignore@^5.0.4, ignore@^5.1.4: - version "5.1.9" - resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.1.9.tgz#9ec1a5cbe8e1446ec60d4420060d43aa6e7382fb" - integrity sha512-2zeMQpbKz5dhZ9IwL0gbxSW5w0NK/MSAMtNuhgIHEPmaU3vPdKPL0UdvUCXs5SS4JAwsBxysK5sFMW8ocFiVjQ== + version "5.2.0" + resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.2.0.tgz#6d3bac8fa7fe0d45d9f9be7bac2fc279577e345a" + integrity sha512-CmxgYGiEPCLhfLnpPp1MoRmifwEIOgjcHXxOBjv7mY96c+eWScsOP9c112ZyLdWHi0FxHjI+4uVhKYp/gcdRmQ== image-size@1.0.0: version "1.0.0" @@ -10871,9 +10841,9 @@ is-nan@^1.2.1: define-properties "^1.1.3" is-negative-zero@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/is-negative-zero/-/is-negative-zero-2.0.1.tgz#3de746c18dda2319241a53675908d8f766f11c24" - integrity sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w== + version "2.0.2" + resolved "https://registry.yarnpkg.com/is-negative-zero/-/is-negative-zero-2.0.2.tgz#7bf6f03a28003b8b3965de3ac26f664d765f3150" + integrity sha512-dqJvarLawXsFbNDeJW7zAz8ItJ9cd28YufuuFzh0G8pNHjJMnY08Dv7sYX2uF5UpQOwieAeOExEYAWWfu7ZZUA== is-node-process@^1.0.1: version "1.0.1" @@ -11027,11 +10997,11 @@ is-unicode-supported@^0.1.0: integrity sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw== is-weakref@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-weakref/-/is-weakref-1.0.1.tgz#842dba4ec17fa9ac9850df2d6efbc1737274f2a2" - integrity sha512-b2jKc2pQZjaeFYWEf7ScFj+Be1I+PXmlu572Q8coTXZ+LD/QQZ7ShPMst8h16riVgyXTQwUsFEl74mDvc/3MHQ== + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-weakref/-/is-weakref-1.0.2.tgz#9529f383a9338205e89765e0392efc2f100f06f2" + integrity sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ== dependencies: - call-bind "^1.0.0" + call-bind "^1.0.2" is-whitespace-character@^1.0.0: version "1.0.4" @@ -11185,9 +11155,9 @@ istanbul-lib-source-maps@^4.0.0: source-map "^0.6.1" istanbul-reports@^3.0.2: - version "3.1.1" - resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-3.1.1.tgz#7085857f17d2441053c6ce5c3b8fdf6882289397" - integrity sha512-q1kvhAXWSsXfMjCdNHNPKZZv94OlspKnoGv+R9RGbnqOOQ0VbNfLFgQDVgi7hHenKsndGq3/o0OBdzDXthWcNw== + version "3.1.2" + resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-3.1.2.tgz#b80e13cbab0120e1c367ebaa099862361aed5ead" + integrity sha512-0gHxuT1NNC0aEIL1zbJ+MTgPbbHhU77eJPuU35WKA7TgXiSNlCAx4PENoMrH0Or6M2H80TaZcWKhM0IK6V8gRw== dependencies: html-escaper "^2.0.0" istanbul-lib-report "^3.0.0" @@ -11640,9 +11610,9 @@ jest@^26.0.1: jest-cli "^26.6.3" joi@^17.4.0: - version "17.4.3" - resolved "https://registry.yarnpkg.com/joi/-/joi-17.4.3.tgz#462941fd994f11fcb92f59ba9f004706b9a45d17" - integrity sha512-8W3oOogFRuy2aLAdlhMpzS4fNBIMiyIa3xBaBYMFgA272/d5sob1DAth6jjo+5VrOlzbEgmbBGbU4cLrffPKog== + version "17.5.0" + resolved "https://registry.yarnpkg.com/joi/-/joi-17.5.0.tgz#7e66d0004b5045d971cf416a55fb61d33ac6e011" + integrity sha512-R7hR50COp7StzLnDi4ywOXHrBrgNXuUUfJWIR5lPY5Bm/pOD3jZaTwpluUXVLRWcoWZxkrHBBJ5hLxgnlehbdw== dependencies: "@hapi/hoek" "^9.0.0" "@hapi/topo" "^5.0.0" @@ -11898,10 +11868,10 @@ junk@^3.1.0: resolved "https://registry.yarnpkg.com/junk/-/junk-3.1.0.tgz#31499098d902b7e98c5d9b9c80f43457a88abfa1" integrity sha512-pBxcB3LFc8QVgdggvZWyeys+hnrNWg4OcZIU/1X59k5jQdLBlCsYGRQaz234SqoRLTCgMH00fY0xRJH+F9METQ== -kareem@2.3.2: - version "2.3.2" - resolved "https://registry.yarnpkg.com/kareem/-/kareem-2.3.2.tgz#78c4508894985b8d38a0dc15e1a8e11078f2ca93" - integrity sha512-STHz9P7X2L4Kwn72fA4rGyqyXdmrMSdxqHx9IXon/FXluXieaFA6KJ2upcHAHxQPQ0LeM/OjLrhFxifHewOALQ== +kareem@2.3.3: + version "2.3.3" + resolved "https://registry.yarnpkg.com/kareem/-/kareem-2.3.3.tgz#a4432d7965a5bb06fc2b4eeae71317344c9a756a" + integrity sha512-uESCXM2KdtOQ8LOvKyTUXEeg0MkYp4wGglTIpGcYHvjJcS5sn2Wkfrfit8m4xSbaNDAw2KdI9elgkOxZbrFYbg== kind-of@^3.0.2, kind-of@^3.0.3, kind-of@^3.2.0: version "3.2.2" @@ -12739,9 +12709,9 @@ minipass-pipeline@^1.2.2: minipass "^3.0.0" minipass@^3.0.0, minipass@^3.1.1: - version "3.1.5" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.1.5.tgz#71f6251b0a33a49c01b3cf97ff77eda030dff732" - integrity sha512-+8NzxD82XQoNKNrl1d/FSi+X8wAEWR+sbYAfIvub4Nz0d22plFG72CEVVaufV8PNf4qSslFTD8VMOxNVhHCjTw== + version "3.1.6" + resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.1.6.tgz#3b8150aa688a711a1521af5e8779c1d3bb4f45ee" + integrity sha512-rty5kpw9/z8SX9dmxblFA6edItUmwJgMeYDZRrwlIVN27i8gysGbznJwUggw2V/FVqFSDdWy040ZPS811DYAqQ== dependencies: yallist "^4.0.0" @@ -12832,10 +12802,10 @@ mongo-object@^0.1.4: resolved "https://registry.yarnpkg.com/mongo-object/-/mongo-object-0.1.4.tgz#950d1d856b85af5f2321b82bb08b67b9c27f9766" integrity sha512-QtYk0gupWEn2+iB+DDRt1L+WbcNYvJRaHdih/dcqthOa1DbnREUGSs2WGcW478GNYpElflo/yybZXu0sTiRXHg== -mongodb-connection-string-url@^2.1.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/mongodb-connection-string-url/-/mongodb-connection-string-url-2.2.0.tgz#e2422bae91a953dc4ae5882e401301f5be39a227" - integrity sha512-U0cDxLUrQrl7DZA828CA+o69EuWPWEJTwdMPozyd7cy/dbtncUZczMw7wRHcwMD7oKOn0NM2tF9jdf5FFVW9CA== +mongodb-connection-string-url@^2.3.2: + version "2.4.1" + resolved "https://registry.yarnpkg.com/mongodb-connection-string-url/-/mongodb-connection-string-url-2.4.1.tgz#6b3c6c40133a0ad059fe9a0abda64b2a1cb4e8b4" + integrity sha512-d5Kd2bVsKcSA7YI/yo57fSTtMwRQdFkvc5IZwod1RRxJtECeWPPSo7zqcUGJELifRA//Igs4spVtYAmvFCatug== dependencies: "@types/whatwg-url" "^8.2.1" whatwg-url "^11.0.0" @@ -12872,14 +12842,14 @@ mongodb-memory-server@^7.3.6: mongodb-memory-server-core "7.6.3" tslib "^2.3.0" -mongodb@4.1.4: - version "4.1.4" - resolved "https://registry.yarnpkg.com/mongodb/-/mongodb-4.1.4.tgz#ba8062c7c67e7a22db5a059dbac1e3044b48453b" - integrity sha512-Cv/sk8on/tpvvqbEvR1h03mdyNdyvvO+WhtFlL4jrZ+DSsN/oSQHVqmJQI/sBCqqbOArFcYCAYDfyzqFwV4GSQ== +mongodb@4.2.2: + version "4.2.2" + resolved "https://registry.yarnpkg.com/mongodb/-/mongodb-4.2.2.tgz#cd70568bd96003877e35358ad17a0c5de35c6dfd" + integrity sha512-zt8rCTnTKyMQppyt63qMnrLM5dbADgUk18ORPF1XbtHLIYCyc9hattaYHi0pqMvNxDpgGgUofSVzS+UQErgTug== dependencies: - bson "^4.5.4" + bson "^4.6.0" denque "^2.0.1" - mongodb-connection-string-url "^2.1.0" + mongodb-connection-string-url "^2.3.2" optionalDependencies: saslprep "^1.0.3" @@ -12897,13 +12867,13 @@ mongodb@^3.7.3: saslprep "^1.0.0" mongoose@*, mongoose@6: - version "6.0.14" - resolved "https://registry.yarnpkg.com/mongoose/-/mongoose-6.0.14.tgz#8f4d45318bb5de08814a8a9b040dd53521246608" - integrity sha512-SZ0kBlHrz/G70yWdVXLfM/gH4NsY85+as4MZRdtWxBTDEcmoE3rCFAz1/Ho2ycg5mJAeOBwdGZw4a5sn/WrwUA== + version "6.1.4" + resolved "https://registry.yarnpkg.com/mongoose/-/mongoose-6.1.4.tgz#a414e64c849fae3ced99348e9de73f986c9f0551" + integrity sha512-RsNiMpGWo7OXFmq5xt0ZWYt2rabHLxNYr0oAiR0xDv23lHKCkXDqyDl71+sXF9rcWEe8BTHG+1IRQykiNBvaKQ== dependencies: bson "^4.2.2" - kareem "2.3.2" - mongodb "4.1.4" + kareem "2.3.3" + mongodb "4.2.2" mpath "0.8.4" mquery "4.0.0" ms "2.1.2" @@ -12952,7 +12922,7 @@ ms@2.1.2: resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== -ms@^2.1.1: +ms@2.1.3, ms@^2.1.1: version "2.1.3" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== @@ -13091,17 +13061,17 @@ next-sitemap@^1.4.17: minimist "^1.2.5" next@12: - version "12.0.4" - resolved "https://registry.yarnpkg.com/next/-/next-12.0.4.tgz#096578b320f0faf0bd51798decb39aaf00052efe" - integrity sha512-1pvjcSZBm5OLoGmDhp4JwKwIE798WbqUNLuyU7w6a2jUkdWaxOYtkE/ROXQTi2pXHj7+6rm68AvhxROLX2NHQg== + version "12.0.7" + resolved "https://registry.yarnpkg.com/next/-/next-12.0.7.tgz#33ebf229b81b06e583ab5ae7613cffe1ca2103fc" + integrity sha512-sKO8GJJYfuk9c+q+zHSNumvff+wP7ufmOlwT6BuzwiYfFJ61VTTkfTcDLSJ+95ErQJiC54uS4Yg5JEE8H6jXRA== dependencies: "@babel/runtime" "7.15.4" "@hapi/accept" "5.0.2" "@napi-rs/triples" "1.0.3" - "@next/env" "12.0.4" - "@next/polyfill-module" "12.0.4" - "@next/react-dev-overlay" "12.0.4" - "@next/react-refresh-utils" "12.0.4" + "@next/env" "12.0.7" + "@next/polyfill-module" "12.0.7" + "@next/react-dev-overlay" "12.0.7" + "@next/react-refresh-utils" "12.0.7" acorn "8.5.0" assert "2.0.0" browserify-zlib "0.2.0" @@ -13143,19 +13113,19 @@ next@12: use-subscription "1.5.1" util "0.12.4" vm-browserify "1.1.2" - watchpack "2.1.1" + watchpack "2.3.0" optionalDependencies: - "@next/swc-android-arm64" "12.0.4" - "@next/swc-darwin-arm64" "12.0.4" - "@next/swc-darwin-x64" "12.0.4" - "@next/swc-linux-arm-gnueabihf" "12.0.4" - "@next/swc-linux-arm64-gnu" "12.0.4" - "@next/swc-linux-arm64-musl" "12.0.4" - "@next/swc-linux-x64-gnu" "12.0.4" - "@next/swc-linux-x64-musl" "12.0.4" - "@next/swc-win32-arm64-msvc" "12.0.4" - "@next/swc-win32-ia32-msvc" "12.0.4" - "@next/swc-win32-x64-msvc" "12.0.4" + "@next/swc-android-arm64" "12.0.7" + "@next/swc-darwin-arm64" "12.0.7" + "@next/swc-darwin-x64" "12.0.7" + "@next/swc-linux-arm-gnueabihf" "12.0.7" + "@next/swc-linux-arm64-gnu" "12.0.7" + "@next/swc-linux-arm64-musl" "12.0.7" + "@next/swc-linux-x64-gnu" "12.0.7" + "@next/swc-linux-x64-musl" "12.0.7" + "@next/swc-win32-arm64-msvc" "12.0.7" + "@next/swc-win32-ia32-msvc" "12.0.7" + "@next/swc-win32-x64-msvc" "12.0.7" nice-try@^1.0.4: version "1.0.5" @@ -13276,11 +13246,6 @@ node-match-path@^0.6.3: resolved "https://registry.yarnpkg.com/node-match-path/-/node-match-path-0.6.3.tgz#55dd8443d547f066937a0752dce462ea7dc27551" integrity sha512-fB1reOHKLRZCJMAka28hIxCwQLxGmd7WewOCBDYKpyA1KXi68A7vaGgdZAPhY2E6SXoYt3KqYCCvXLJ+O0Fu/Q== -node-modules-regexp@^1.0.0: - version "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@^8.0.0: version "8.0.2" resolved "https://registry.yarnpkg.com/node-notifier/-/node-notifier-8.0.2.tgz#f3167a38ef0d2c8a866a83e318c1ba0efeb702c5" @@ -13420,7 +13385,7 @@ npmlog@^5.0.1: gauge "^3.0.0" set-blocking "^2.0.0" -nth-check@^2.0.0: +nth-check@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/nth-check/-/nth-check-2.0.1.tgz#2efe162f5c3da06a28959fbd3db75dbeea9f0fc2" integrity sha512-it1vE95zF6dTT9lBsYbxvqh0Soy4SPowchj0UBGj/V6cTPnXXtQOPUbhZ6CmGzAD/rW22LQK6E96pcdJXk4A4w== @@ -13495,9 +13460,9 @@ object-copy@^0.1.0: kind-of "^3.0.3" object-inspect@^1.11.0, object-inspect@^1.9.0: - version "1.11.0" - resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.11.0.tgz#9dceb146cedd4148a0d9e51ab88d34cf509922b1" - integrity sha512-jp7ikS6Sd3GxQfZJPyH3cjcbJF6GZPClgdV+EFygjFLQ5FmW/dRUnTd9PQ9k0JhoNDabWFbpF1yCdSWCC6gexg== + version "1.12.0" + resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.12.0.tgz#6e2c120e868fd1fd18cb4f18c31741d0d6e776f0" + integrity sha512-Ho2z80bVIvJloH+YzRmpZVQe87+qASmBUKZDWgx9cu+KDrX2ZDH/3tMy+gXbZETVGs2M8YdxObOh7XAtim9Y0g== object-is@^1.0.1: version "1.1.5" @@ -14132,14 +14097,7 @@ pify@^4.0.1: resolved "https://registry.yarnpkg.com/pify/-/pify-4.0.1.tgz#4b2cd25c50d598735c50292224fd8c6df41e3231" integrity sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g== -pirates@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/pirates/-/pirates-4.0.1.tgz#643a92caf894566f91b2b986d2c66950a8e2fb87" - integrity sha512-WuNqLTbMI3tmfef2TKxlQmAiLHKtFhlsCZnPIpuv2Ow0RDVO8lfy1Opf4NUzlMXLjPl+Men7AuVdX6TA+s+uGA== - dependencies: - node-modules-regexp "^1.0.0" - -pirates@^4.0.1: +pirates@^4.0.0, pirates@^4.0.1: version "4.0.4" resolved "https://registry.yarnpkg.com/pirates/-/pirates-4.0.4.tgz#07df81e61028e402735cdd49db701e4885b4e6e6" integrity sha512-ZIrVPH+A52Dw84R0L3/VS9Op04PuQ2SEoJL6bkshmiTic/HldyW9Tf7oH5mhJZBK7NmDx27vSMrYEXPXclpDKw== @@ -14288,9 +14246,9 @@ postcss-nested@^4.2.1: postcss-selector-parser "^6.0.2" postcss-selector-parser@^6.0.0, postcss-selector-parser@^6.0.2: - version "6.0.6" - resolved "https://registry.yarnpkg.com/postcss-selector-parser/-/postcss-selector-parser-6.0.6.tgz#2c5bba8174ac2f6981ab631a42ab0ee54af332ea" - integrity sha512-9LXrvaaX3+mcv5xkg5kFwqSzSH1JIObIx51PrndZwlmznwXRfxMddDvo9gve3gVR8ZTKgoFDdWkbRFmEhT4PMg== + version "6.0.8" + resolved "https://registry.yarnpkg.com/postcss-selector-parser/-/postcss-selector-parser-6.0.8.tgz#f023ed7a9ea736cd7ef70342996e8e78645a7914" + integrity sha512-D5PG53d209Z1Uhcc0qAZ5U3t5HagH3cxu+WLZ22jt3gLUpXM4eXXfiO14jiDWST3NNooX/E8wISfOhZ9eIjGTQ== dependencies: cssesc "^3.0.0" util-deprecate "^1.0.2" @@ -14328,9 +14286,9 @@ prelude-ls@~1.1.2: integrity sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ= prettier@^2.2.1: - version "2.5.0" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.5.0.tgz#a6370e2d4594e093270419d9cc47f7670488f893" - integrity sha512-FM/zAKgWTxj40rH03VxzIPdXmj39SwSjwG0heUcNFwI+EMZJnY93yAiKXM3dObIKAM5TA88werc8T/EwhB45eg== + version "2.5.1" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.5.1.tgz#fff75fa9d519c54cf0fce328c1017d94546bc56a" + integrity sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg== pretty-bytes@^5.6.0: version "5.6.0" @@ -14472,16 +14430,7 @@ prop-types-extra@^1.1.0: react-is "^16.3.2" warning "^4.0.0" -prop-types@^15.0.0, prop-types@^15.5.8, prop-types@^15.6.0: - version "15.7.2" - resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.7.2.tgz#52c41e75b8c87e72b9d9360e0206b99dcbffa6c5" - integrity sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ== - dependencies: - loose-envify "^1.4.0" - object-assign "^4.1.1" - react-is "^16.8.1" - -prop-types@^15.6.2, prop-types@^15.7.2: +prop-types@^15.0.0, prop-types@^15.5.8, prop-types@^15.6.0, prop-types@^15.6.2, prop-types@^15.7.2: version "15.8.0" resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.8.0.tgz#d237e624c45a9846e469f5f31117f970017ff588" integrity sha512-fDGekdaHh65eI3lMi5OnErU6a8Ighg2KjcjQxO7m8VHyWjcPyj5kiOgV1LQDOOOgVy3+5FgjXvdSSX7B8/5/4g== @@ -14497,7 +14446,7 @@ property-information@^5.0.0, property-information@^5.3.0: dependencies: xtend "^4.0.0" -proxy-addr@~2.0.5: +proxy-addr@~2.0.5, proxy-addr@~2.0.7: version "2.0.7" resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg== @@ -14589,10 +14538,15 @@ qs@6.7.0: resolved "https://registry.yarnpkg.com/qs/-/qs-6.7.0.tgz#41dc1a015e3d581f1621776be31afb2876a9b1bc" integrity sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ== +qs@6.9.6: + version "6.9.6" + resolved "https://registry.yarnpkg.com/qs/-/qs-6.9.6.tgz#26ed3c8243a431b2924aca84cc90471f35d5a0ee" + integrity sha512-TIRk4aqYLNoJUbd+g2lEdz5kLWIuTMRagAXxl78Q0RiVjAOugHmeKNGdd3cwo/ktpf9aL9epCfFqWDEKysUlLQ== + qs@^6.10.0, qs@^6.9.4: - version "6.10.1" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.10.1.tgz#4931482fa8d647a5aab799c5271d2133b981fb6a" - integrity sha512-M528Hph6wsSVOBiYUnGf+K/7w0hNshs/duGsNXPUCLH5XAqjEtiPGwNONLV0tBH8NoGb0mvD5JubnUTrujKDTg== + version "6.10.2" + resolved "https://registry.yarnpkg.com/qs/-/qs-6.10.2.tgz#c1431bea37fc5b24c5bdbafa20f16bdf2a4b9ffe" + integrity sha512-mSIdjzqznWgfd4pMii7sHtaYF8rx8861hBO80SraY5GT0XQibWZWJSid0avzHGkDIZLImux2S5mXO0Hfct2QCw== dependencies: side-channel "^1.0.4" @@ -14688,6 +14642,16 @@ raw-body@2.4.1: iconv-lite "0.4.24" unpipe "1.0.0" +raw-body@2.4.2: + version "2.4.2" + resolved "https://registry.yarnpkg.com/raw-body/-/raw-body-2.4.2.tgz#baf3e9c21eebced59dd6533ac872b71f7b61cb32" + integrity sha512-RPMAFUJP19WIet/99ngh6Iv8fzAbqum4Li7AD6DtGaW2RpMB/11xDoalPiJMTbu6I3hkbMVkATvZrqb9EEqeeQ== + dependencies: + bytes "3.1.1" + http-errors "1.8.1" + iconv-lite "0.4.24" + unpipe "1.0.0" + raw-loader@^4.0.2: version "4.0.2" resolved "https://registry.yarnpkg.com/raw-loader/-/raw-loader-4.0.2.tgz#1aac6b7d1ad1501e66efdac1522c73e59a584eb6" @@ -14791,9 +14755,9 @@ react-dev-utils@^11.0.4: text-table "0.2.0" react-docgen-typescript@^2.0.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/react-docgen-typescript/-/react-docgen-typescript-2.1.1.tgz#c9f9ccb1fa67e0f4caf3b12f2a07512a201c2dcf" - integrity sha512-XWe8bsYqVjxciKdpNoufaHiB7FgUHIOnVQgxUolRL3Zlof2zkdTzuQH6SU2n3Ek9kfy3O1c63ojMtNfpiuNeZQ== + version "2.2.2" + resolved "https://registry.yarnpkg.com/react-docgen-typescript/-/react-docgen-typescript-2.2.2.tgz#4611055e569edc071204aadb20e1c93e1ab1659c" + integrity sha512-tvg2ZtOpOi6QDwsb3GZhOjDkkX0h8Z2gipvTg6OVMUyoYoURhEiRNePT8NZItTVCDh39JJHnLdfCOkzoLbFnTg== react-docgen@^5.0.0: version "5.4.0" @@ -14838,9 +14802,9 @@ react-element-to-jsx-string@^14.3.4: react-is "17.0.2" react-error-overlay@^6.0.9: - version "6.0.9" - resolved "https://registry.yarnpkg.com/react-error-overlay/-/react-error-overlay-6.0.9.tgz#3c743010c9359608c375ecd6bc76f35d93995b0a" - integrity sha512-nQTTcUu+ATDbrSD1BZHr5kgSD4oF8OFjxun8uAaL8RwPBacGBNPf/yAuVVdx17N8XNzRDMrZ9XcKZHCjPW+9ew== + version "6.0.10" + resolved "https://registry.yarnpkg.com/react-error-overlay/-/react-error-overlay-6.0.10.tgz#0fe26db4fa85d9dbb8624729580e90e7159a59a6" + integrity sha512-mKR90fX7Pm5seCOfz8q9F+66VCc1PGsWSBxKbITjfKVQHMNF2zudxHnMdJiB1fRCb+XsbQV9sO9DCkgsMQgBIA== react-event-listener@^0.6.2: version "0.6.6" @@ -14857,9 +14821,9 @@ react-fast-compare@^3.0.1, react-fast-compare@^3.2.0: integrity sha512-rtGImPZ0YyLrscKI9xTpV8psd6I8VAtjKCzQDlzyDvqJA8XOW78TXYQwNRNd8g8JZnDu8q9Fu/1v4HPAVwVdHA== react-helmet-async@^1.0.7: - version "1.1.2" - resolved "https://registry.yarnpkg.com/react-helmet-async/-/react-helmet-async-1.1.2.tgz#653b7e6bbfdd239c5dcd6b8df2811c7a363b8334" - integrity sha512-LTTzDDkyIleT/JJ6T/uqx7Y8qi1EuPPSiJawQY/nHHz0h7SPDT6HxP1YDDQx/fzcVxCqpWEEMS3QdrSrNkJYhg== + version "1.2.2" + resolved "https://registry.yarnpkg.com/react-helmet-async/-/react-helmet-async-1.2.2.tgz#38d58d32ebffbc01ba42b5ad9142f85722492389" + integrity sha512-XgSQezeCbLfCxdZhDA3T/g27XZKnOYyOkruopTLSJj8RvFZwdXnM4djnfYaiBSDzOidDgTo1jcEozoRu/+P9UQ== dependencies: "@babel/runtime" "^7.12.5" invariant "^2.2.4" @@ -14873,11 +14837,12 @@ react-hook-form@4.9.8: integrity sha512-oOeTZe4MomOyoPzJ5k69kg2xukdDE02jkoH6kSH9anUq5GjD2gL6TGQGhjA2deV4JYjM7c1XD4Mwinxoqc407w== react-i18next@^11.5.0, react-i18next@^11.8.13: - version "11.14.3" - resolved "https://registry.yarnpkg.com/react-i18next/-/react-i18next-11.14.3.tgz#b44b5c4d1aadac5211be011827a2830be60f2522" - integrity sha512-Hf2aanbKgYxPjG8ZdKr+PBz9sY6sxXuZWizxCYyJD2YzvJ0W9JTQcddVEjDaKyBoCyd3+5HTerdhc9ehFugc6g== + version "11.15.2" + resolved "https://registry.yarnpkg.com/react-i18next/-/react-i18next-11.15.2.tgz#5bbbf1ab208d7fb77d93aa8161e06b7d55fb35ff" + integrity sha512-28WlZ6tr57RQoIM1x4/gTzvzh3Vvr+YeZwJHTOqV/sLXMFbR+xzjgSMdLnOCDxmlQ0irGN2uM+HT+mYK+3bg6g== dependencies: "@babel/runtime" "^7.14.5" + html-escaper "^2.0.2" html-parse-stringify "^3.0.1" react-inspector@^5.1.0: @@ -14894,7 +14859,7 @@ react-is@17.0.2, react-is@^17.0.1, react-is@^17.0.2: resolved "https://registry.yarnpkg.com/react-is/-/react-is-17.0.2.tgz#e691d4a8e9c789365655539ab372762b0efb54f0" integrity sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w== -react-is@^16.12.0, react-is@^16.13.1, react-is@^16.3.2, react-is@^16.6.3, react-is@^16.7.0, react-is@^16.8.1: +react-is@^16.12.0, react-is@^16.13.1, react-is@^16.3.2, react-is@^16.6.3, react-is@^16.7.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== @@ -14946,19 +14911,19 @@ react-refresh@^0.10.0: integrity sha512-PgidR3wST3dDYKr6b4pJoqQFpPGNKDSCDx4cZoshjXipw3LzO7mG1My2pwEzz2JVkF+inx3xRpDeQLFQGH/hsQ== react-router-dom@^6.0.0: - version "6.0.2" - resolved "https://registry.yarnpkg.com/react-router-dom/-/react-router-dom-6.0.2.tgz#860cefa697b9d4965eced3f91e82cdbc5995f3ad" - integrity sha512-cOpJ4B6raFutr0EG8O/M2fEoyQmwvZWomf1c6W2YXBZuFBx8oTk/zqjXghwScyhfrtnt0lANXV2182NQblRxFA== + version "6.2.1" + resolved "https://registry.yarnpkg.com/react-router-dom/-/react-router-dom-6.2.1.tgz#32ec81829152fbb8a7b045bf593a22eadf019bec" + integrity sha512-I6Zax+/TH/cZMDpj3/4Fl2eaNdcvoxxHoH1tYOREsQ22OKDYofGebrNm6CTPUcvLvZm63NL/vzCYdjf9CUhqmA== dependencies: - history "^5.1.0" - react-router "6.0.2" + history "^5.2.0" + react-router "6.2.1" -react-router@6.0.2, react-router@^6.0.0: - version "6.0.2" - resolved "https://registry.yarnpkg.com/react-router/-/react-router-6.0.2.tgz#bd2b0fa84fd1d152671e9f654d9c0b1f5a7c86da" - integrity sha512-8/Wm3Ed8t7TuedXjAvV39+c8j0vwrI5qVsYqjFr5WkJjsJpEvNSoLRUbtqSEYzqaTUj1IV+sbPJxvO+accvU0Q== +react-router@6.2.1, react-router@^6.0.0: + version "6.2.1" + resolved "https://registry.yarnpkg.com/react-router/-/react-router-6.2.1.tgz#be2a97a6006ce1d9123c28934e604faef51448a3" + integrity sha512-2fG0udBtxou9lXtK97eJeET2ki5//UWfQSl1rlJ7quwe6jrktK9FCCc8dQb5QY6jAv3jua8bBQRhhDOM/kVRsg== dependencies: - history "^5.1.0" + history "^5.2.0" react-sizeme@^3.0.1: version "3.0.2" @@ -15554,14 +15519,7 @@ rxjs@^6.3.3, rxjs@^6.4.0: dependencies: tslib "^1.9.0" -rxjs@^7.1.0, rxjs@^7.4.0: - version "7.4.0" - resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-7.4.0.tgz#a12a44d7eebf016f5ff2441b87f28c9a51cebc68" - integrity sha512-7SQDi7xeTMCJpqViXh8gL/lebcwlp3d831F05+9B44A4B0WfsEwUQHR64gsH1kvJ+Ep/J9K2+n1hVl1CsGN23w== - dependencies: - tslib "~2.1.0" - -rxjs@^7.2.0: +rxjs@^7.1.0, rxjs@^7.2.0, rxjs@^7.4.0: version "7.5.1" resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-7.5.1.tgz#af73df343cbcab37628197f43ea0c8256f54b157" integrity sha512-KExVEeZWxMZnZhUZtsJcFwz8IvPvgu4G2Z2QyqjZQzUGr32KDYuSxrEYO4w3tFFNbfLozcrKUTvTPi+E9ywJkQ== @@ -15578,7 +15536,7 @@ safe-buffer@5.1.2, safe-buffer@~5.1.0, safe-buffer@~5.1.1: resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== -safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@^5.1.1, safe-buffer@^5.1.2, safe-buffer@^5.2.0, safe-buffer@~5.2.0: +safe-buffer@5.2.1, safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@^5.1.1, safe-buffer@^5.1.2, safe-buffer@^5.2.0, 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== @@ -15729,6 +15687,25 @@ send@0.17.1: range-parser "~1.2.1" statuses "~1.5.0" +send@0.17.2: + version "0.17.2" + resolved "https://registry.yarnpkg.com/send/-/send-0.17.2.tgz#926622f76601c41808012c8bf1688fe3906f7820" + integrity sha512-UJYB6wFSJE3G00nEivR5rgWp8c2xXvJ3OPWPhmuteU0IKj8nKbG3DrjiOmLwpnHGYWAVwA69zmTm++YG0Hmwww== + dependencies: + debug "2.6.9" + depd "~1.1.2" + destroy "~1.0.4" + encodeurl "~1.0.2" + escape-html "~1.0.3" + etag "~1.8.1" + fresh "0.5.2" + http-errors "1.8.1" + mime "1.6.0" + ms "2.1.3" + on-finished "~2.3.0" + range-parser "~1.2.1" + statuses "~1.5.0" + serialize-javascript@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-4.0.0.tgz#b525e1238489a5ecfc42afacc3fe99e666f4b1aa" @@ -15778,6 +15755,16 @@ serve-static@1.14.1: parseurl "~1.3.3" send "0.17.1" +serve-static@1.14.2: + version "1.14.2" + resolved "https://registry.yarnpkg.com/serve-static/-/serve-static-1.14.2.tgz#722d6294b1d62626d41b43a013ece4598d292bfa" + integrity sha512-+TMNA9AFxUEGuC0z2mevogSnn9MXKb4fa7ngeRMJaaGv8vTwnIEkKi+QGvPt33HSnf8pRS+WGM0EbMtCJLKMBQ== + dependencies: + encodeurl "~1.0.2" + escape-html "~1.0.3" + parseurl "~1.3.3" + send "0.17.2" + serve@^11.3.2: version "11.3.2" resolved "https://registry.yarnpkg.com/serve/-/serve-11.3.2.tgz#b905e980616feecd170e51c8f979a7b2374098f5" @@ -16262,14 +16249,14 @@ statuses@^2.0.0: integrity sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ== store2@^2.12.0: - version "2.12.0" - resolved "https://registry.yarnpkg.com/store2/-/store2-2.12.0.tgz#e1f1b7e1a59b6083b2596a8d067f6ee88fd4d3cf" - integrity sha512-7t+/wpKLanLzSnQPX8WAcuLCCeuSHoWdQuh9SB3xD0kNOM38DNf+0Oa+wmvxmYueRzkmh6IcdKFtvTa+ecgPDw== + version "2.13.1" + resolved "https://registry.yarnpkg.com/store2/-/store2-2.13.1.tgz#fae7b5bb9d35fc53dc61cd262df3abb2f6e59022" + integrity sha512-iJtHSGmNgAUx0b/MCS6ASGxb//hGrHHRgzvN+K5bvkBTN7A9RTpPSf1WSp+nPGvWCJ1jRnvY7MKnuqfoi3OEqg== storybook-addon-next-router@^3.0.7: - version "3.0.10" - resolved "https://registry.yarnpkg.com/storybook-addon-next-router/-/storybook-addon-next-router-3.0.10.tgz#c6b1a6afdc640ddadf65c46764b808d736fd1bd5" - integrity sha512-DmmeLY/N3Cc0o4aq/vooxFkt+UbzWIshXftvkXZA2TPrHZ3flC7JzYZHiyxvMQVrhqQTKZ8FIvGXuuoNtmanZA== + version "3.1.1" + resolved "https://registry.yarnpkg.com/storybook-addon-next-router/-/storybook-addon-next-router-3.1.1.tgz#46623ca36b450745c3517f5cdc4bf30fa4a4a930" + integrity sha512-Z14dED37vNXkN7+VY80HhF9itGReWoBAlKREHEk2By/dW7zSSqcSyXYV4bDMXIMAFYHMaA1svcBC1idVG8FhAw== dependencies: tslib "^2.3.0" @@ -16407,14 +16394,6 @@ string-width@^1.0.1: is-fullwidth-code-point "^1.0.0" strip-ansi "^3.0.0" -"string-width@^1.0.1 || ^2.0.0", 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== - dependencies: - is-fullwidth-code-point "^2.0.0" - strip-ansi "^4.0.0" - "string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.0.0, string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.2, string-width@^4.2.3: version "4.2.3" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" @@ -16424,6 +16403,14 @@ string-width@^1.0.1: is-fullwidth-code-point "^3.0.0" strip-ansi "^6.0.1" +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== + dependencies: + is-fullwidth-code-point "^2.0.0" + strip-ansi "^4.0.0" + "string.prototype.matchall@^4.0.0 || ^3.0.1", string.prototype.matchall@^4.0.6: version "4.0.6" resolved "https://registry.yarnpkg.com/string.prototype.matchall/-/string.prototype.matchall-4.0.6.tgz#5abb5dabc94c7b0ea2380f65ba610b3a544b15fa" @@ -16526,7 +16513,7 @@ strip-ansi@^3.0.0, strip-ansi@^3.0.1: dependencies: ansi-regex "^2.0.0" -"strip-ansi@^3.0.1 || ^4.0.0", strip-ansi@^4.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= @@ -16622,10 +16609,10 @@ stylis@3.5.4: resolved "https://registry.yarnpkg.com/stylis/-/stylis-3.5.4.tgz#f665f25f5e299cf3d64654ab949a57c768b73fbe" integrity sha512-8/3pSmthWM7lsPBKv7NXkzn2Uc9W7NotcwGNpJaa3k7WMM1XDCA4MgT5k/8BIexd5ydZdboXtU90XH9Ec4Bv/Q== -stylis@^4.0.10, stylis@^4.0.3: - version "4.0.10" - resolved "https://registry.yarnpkg.com/stylis/-/stylis-4.0.10.tgz#446512d1097197ab3f02fb3c258358c3f7a14240" - integrity sha512-m3k+dk7QeJw660eIKRRn3xPF6uuvHs/FFzjX3HQ5ove0qYsiygoAhwn5a3IYKaZPo5LrYD0rfVmtv1gNY1uYwg== +stylis@4.0.13: + version "4.0.13" + resolved "https://registry.yarnpkg.com/stylis/-/stylis-4.0.13.tgz#f5db332e376d13cc84ecfe5dace9a2a51d954c91" + integrity sha512-xGPXiFVl4YED9Jh7Euv2V220mriG9u4B2TA6Ybjc1catrstKD2PpIdU3U0RKpkVBC2EhmL/F0sPCr9vrFTNRag== subarg@^1.0.0: version "1.0.0" @@ -17123,11 +17110,6 @@ ts-dedent@^2.0.0: resolved "https://registry.yarnpkg.com/ts-dedent/-/ts-dedent-2.2.0.tgz#39e4bd297cd036292ae2394eb3412be63f563bb5" integrity sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ== -ts-essentials@^2.0.3: - version "2.0.12" - resolved "https://registry.yarnpkg.com/ts-essentials/-/ts-essentials-2.0.12.tgz#c9303f3d74f75fa7528c3d49b80e089ab09d8745" - integrity sha512-3IVX4nI6B5cc31/GFFE+i8ey/N2eA0CZDbo6n0yrz0zDX8ZJ8djmU1p+XRz7G3is0F3bB3pu2pAroFdAWQKU3w== - ts-invariant@^0.4.0: version "0.4.4" resolved "https://registry.yarnpkg.com/ts-invariant/-/ts-invariant-0.4.4.tgz#97a523518688f93aafad01b0e80eb803eb2abd86" @@ -17135,10 +17117,10 @@ ts-invariant@^0.4.0: dependencies: tslib "^1.9.3" -ts-invariant@^0.9.0: - version "0.9.3" - resolved "https://registry.yarnpkg.com/ts-invariant/-/ts-invariant-0.9.3.tgz#4b41e0a80c2530a56ce4b8fd4e14183aaac0efa8" - integrity sha512-HinBlTbFslQI0OHP07JLsSXPibSegec6r9ai5xxq/qHYCsIQbzpymLpDhAUsnXcSrDEcd0L62L8vsOEdzM0qlA== +ts-invariant@^0.9.4: + version "0.9.4" + resolved "https://registry.yarnpkg.com/ts-invariant/-/ts-invariant-0.9.4.tgz#42ac6c791aade267dd9dc65276549df5c5d71cac" + integrity sha512-63jtX/ZSwnUNi/WhXjnK8kz4cHHpYS60AnmA6ixz17l7E12a5puCWFlNpkne5Rl0J8TBPVHpGjsj4fxs8ObVLQ== dependencies: tslib "^2.1.0" @@ -17189,11 +17171,6 @@ tslib@^2.0.0, tslib@^2.0.1, tslib@^2.0.3, tslib@^2.1.0, tslib@^2.3.0, tslib@^2.3 resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01" integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw== -tslib@~2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.1.0.tgz#da60860f1c2ecaa5703ab7d39bc05b6bf988b97a" - integrity sha512-hcVC3wYEziELGGmEEXue7D75zbwIIVUMWAVbHItGPx0ziyXxrOMQx4rQEVEV45Ut/1IotuEvwqPopzIOkDMf0A== - tsutils@^3.21.0: version "3.21.0" resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.21.0.tgz#b48717d394cea6c1e096983eed58e9d61715b623" @@ -17318,9 +17295,9 @@ uc.micro@^1.0.1: integrity sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA== uglify-js@^3.1.4: - version "3.14.4" - resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.14.4.tgz#68756f17d1b90b9d289341736cb9a567d6882f90" - integrity sha512-AbiSR44J0GoCeV81+oxcy/jDOElO2Bx3d0MfQCUShq7JRXaM4KtQopZsq2vFv8bCq2yMaGrw1FgygUd03RyRDA== + version "3.14.5" + resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.14.5.tgz#cdabb7d4954231d80cb4a927654c4655e51f4859" + integrity sha512-qZukoSxOG0urUTvjc2ERMTcAy+BiFh3weWAkeurLwjrCba73poHmG3E36XEjd/JGukMzwTL7uCxZiAexj8ppvQ== umd@^3.0.0: version "3.0.3" @@ -17564,9 +17541,9 @@ url-loader@^4.1.1: schema-utils "^3.0.0" url-parse@^1.2.0: - version "1.5.3" - resolved "https://registry.yarnpkg.com/url-parse/-/url-parse-1.5.3.tgz#71c1303d38fb6639ade183c2992c8cc0686df862" - integrity sha512-IIORyIQD9rvj0A4CLWsHkBBJuNqWpFQe224b6j9t/ABmquIS0qDU2pY6kl6AuOrL5OkCXHMCFNe1jBcuAggjvQ== + version "1.5.4" + resolved "https://registry.yarnpkg.com/url-parse/-/url-parse-1.5.4.tgz#e4f645a7e2a0852cc8a66b14b292a3e9a11a97fd" + integrity sha512-ITeAByWWoqutFClc/lRZnFplgXgEZr3WJ6XngMM/N9DMIm4K8zXPCZ1Jdu0rERwO84w1WC5wkle2ubwTA4NTBg== dependencies: querystringify "^2.1.1" requires-port "^1.0.0" @@ -17580,11 +17557,9 @@ url@^0.11.0, url@~0.11.0: querystring "0.2.0" use-composed-ref@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/use-composed-ref/-/use-composed-ref-1.1.0.tgz#9220e4e94a97b7b02d7d27eaeab0b37034438bbc" - integrity sha512-my1lNHGWsSDAhhVAT4MKs6IjBUtG6ZG11uUqexPH9PptiIZDQOzaF4f5tEbJ2+7qvNbtXNBbU3SfmN+fXlWDhg== - dependencies: - ts-essentials "^2.0.3" + version "1.2.1" + resolved "https://registry.yarnpkg.com/use-composed-ref/-/use-composed-ref-1.2.1.tgz#9bdcb5ccd894289105da2325e1210079f56bf849" + integrity sha512-6+X1FLlIcjvFMAeAD/hcxDT8tmyrWnbSPMU0EnxQuDLIxokuFzWliXBiYZuGIx+mrAMLBw0WFfCkaPw8ebzAhw== use-isomorphic-layout-effect@^1.0.0: version "1.1.1" @@ -17841,10 +17816,10 @@ watchpack-chokidar2@^2.0.1: dependencies: chokidar "^2.1.8" -watchpack@2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.1.1.tgz#e99630550fca07df9f90a06056987baa40a689c7" - integrity sha512-Oo7LXCmc1eE1AjyuSBmtC3+Wy4HcV8PxWh2kP6fOl8yTlNS7r0K9l1ao2lrrUza7V39Y3D/BbJgY8VeSlc5JKw== +watchpack@2.3.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.3.0.tgz#a41bca3da6afaff31e92a433f4c856a0c25ea0c4" + integrity sha512-MnN0Q1OsvB/GGHETrFeZPQaOelWh/7O+EiFlj8sM9GPjtQkis7k01aAxrg/18kTfoIVcLL+haEVFlXDaSRwKRw== dependencies: glob-to-regexp "^0.4.1" graceful-fs "^4.1.2" @@ -17861,9 +17836,9 @@ watchpack@^1.7.4: watchpack-chokidar2 "^2.0.1" watchpack@^2.2.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.3.0.tgz#a41bca3da6afaff31e92a433f4c856a0c25ea0c4" - integrity sha512-MnN0Q1OsvB/GGHETrFeZPQaOelWh/7O+EiFlj8sM9GPjtQkis7k01aAxrg/18kTfoIVcLL+haEVFlXDaSRwKRw== + version "2.3.1" + resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.3.1.tgz#4200d9447b401156eeca7767ee610f8809bc9d25" + integrity sha512-x0t0JuydIo8qCNctdDrn1OzH/qDzk2+rdCOC3YzumZ42fiMqmQ7T3xQurykYMhYfHaPHTp4ZxAx2NfUo1K6QaA== dependencies: glob-to-regexp "^0.4.1" graceful-fs "^4.1.2" @@ -18199,9 +18174,9 @@ ws@^6.0.0: async-limiter "~1.0.0" ws@^8.2.3: - version "8.3.0" - resolved "https://registry.yarnpkg.com/ws/-/ws-8.3.0.tgz#7185e252c8973a60d57170175ff55fdbd116070d" - integrity sha512-Gs5EZtpqZzLvmIM59w4igITU57lrtYVFneaa434VROv4thzJyV6UjIL3D42lslWlI+D4KzLYnxSwtfuiO79sNw== + version "8.4.0" + resolved "https://registry.yarnpkg.com/ws/-/ws-8.4.0.tgz#f05e982a0a88c604080e8581576e2a063802bed6" + integrity sha512-IHVsKe2pjajSUIl4KYMQOdlyliovpEPquKkqbwswulszzI7r0SfQrxnXdWAEqOlDCLrVSJzo+O1hAwdog2sKSQ== xml-name-validator@^3.0.0: version "3.0.0"