(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["mongoose"] = factory(); else root["mongoose"] = factory(); })(typeof self !== 'undefined' ? self : this, () => { return /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 5507: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /** * Export lib/mongoose * */ module.exports = __webpack_require__(1735); /***/ }), /***/ 1735: /***/ ((module, exports, __webpack_require__) => { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; /* eslint-env browser */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } (__webpack_require__(9906).set)(__webpack_require__(6333)); var DocumentProvider = __webpack_require__(4304); var PromiseProvider = __webpack_require__(6755); DocumentProvider.setBrowser(true); /** * The Mongoose [Promise](#promise_Promise) constructor. * * @method Promise * @api public */ Object.defineProperty(exports, "Promise", ({ get: function get() { return PromiseProvider.get(); }, set: function set(lib) { PromiseProvider.set(lib); } })); /** * Storage layer for mongoose promises * * @method PromiseProvider * @api public */ exports.PromiseProvider = PromiseProvider; /** * The [MongooseError](#error_MongooseError) constructor. * * @method Error * @api public */ exports.Error = __webpack_require__(4888); /** * The Mongoose [Schema](#schema_Schema) constructor * * #### Example: * * const mongoose = require('mongoose'); * const Schema = mongoose.Schema; * const CatSchema = new Schema(..); * * @method Schema * @api public */ exports.Schema = __webpack_require__(5506); /** * 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 */ exports.Types = __webpack_require__(8941); /** * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor * * @method VirtualType * @api public */ exports.VirtualType = __webpack_require__(459); /** * The various Mongoose SchemaTypes. * * #### Note: * * _Alias of mongoose.Schema.Types for backwards compatibility._ * * @property SchemaTypes * @see Schema.SchemaTypes #schema_Schema.Types * @api public */ exports.SchemaType = __webpack_require__(4289); /** * Internal utils * * @property utils * @api private */ exports.utils = __webpack_require__(6872); /** * The Mongoose browser [Document](/api/document.html) constructor. * * @method Document * @api public */ exports.Document = DocumentProvider(); /** * Return a new browser model. In the browser, a model is just * a simplified document with a schema - it does **not** have * functions like `findOne()`, etc. * * @method model * @api public * @param {String} name * @param {Schema} schema * @return Class */ exports.model = function (name, schema) { var Model = /*#__PURE__*/function (_exports$Document) { _inherits(Model, _exports$Document); var _super = _createSuper(Model); function Model(obj, fields) { _classCallCheck(this, Model); return _super.call(this, obj, schema, fields); } return _createClass(Model); }(exports.Document); Model.modelName = name; return Model; }; /*! * Module exports. */ if (typeof window !== 'undefined') { window.mongoose = module.exports; window.Buffer = Buffer; } /***/ }), /***/ 3434: /***/ ((module, exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ var NodeJSDocument = __webpack_require__(8727); var EventEmitter = (__webpack_require__(9620).EventEmitter); var MongooseError = __webpack_require__(4888); var Schema = __webpack_require__(5506); var ObjectId = __webpack_require__(6079); var ValidationError = MongooseError.ValidationError; var applyHooks = __webpack_require__(8859); var isObject = __webpack_require__(5721); /** * Document constructor. * * @param {Object} obj the values to set * @param {Object} schema * @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 https://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(); } } if (!schema) { throw new MongooseError.MissingSchemaError(); } this.$__setSchema(schema); NodeJSDocument.call(this, obj, fields, skipId, skipInit); applyHooks(this, schema, { decorateDoc: true }); // apply methods for (var m in schema.methods) { this[m] = schema.methods[m]; } // apply statics for (var s in schema.statics) { this[s] = schema.statics[s]; } } /*! * Inherit from the NodeJS document */ Document.prototype = Object.create(NodeJSDocument.prototype); Document.prototype.constructor = Document; /*! * ignore */ Document.events = new EventEmitter(); /*! * Browser doc exposes the event emitter API */ Document.$emitter = new EventEmitter(); ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', 'removeAllListeners', 'addListener'].forEach(function (emitterFn) { Document[emitterFn] = function () { return Document.$emitter[emitterFn].apply(Document.$emitter, arguments); }; }); /*! * Module exports. */ Document.ValidationError = ValidationError; module.exports = exports = Document; /***/ }), /***/ 6787: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var CastError = __webpack_require__(1795); var StrictModeError = __webpack_require__(3328); var Types = __webpack_require__(5251); var cast$expr = __webpack_require__(9739); var castTextSearch = __webpack_require__(6495); var get = __webpack_require__(9981); var getConstructorName = __webpack_require__(1981); var getSchemaDiscriminatorByValue = __webpack_require__(2392); var isOperator = __webpack_require__(9627); var util = __webpack_require__(161); var isObject = __webpack_require__(5721); var isMongooseObject = __webpack_require__(6584); var 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)); } if (obj == null) { return obj; } if (schema != null && schema.discriminators != null && obj[schema.options.discriminatorKey] != null) { schema = getSchemaDiscriminatorByValue(schema, obj[schema.options.discriminatorKey]) || schema; } var paths = Object.keys(obj); var i = paths.length; var _keys; var any$conditionals; var schematype; var nested; var path; var type; var val; 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 (var 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); if (type !== 'string' && type !== 'function') { throw new Error('Must have a string or function for $where'); } if (type === 'function') { obj[path] = val.toString(); } continue; } else if (path === '$expr') { val = cast$expr(val, schema); 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) { var split = path.split('.'); var j = split.length; while (j--) { var pathFirstHalf = split.slice(0, j).join('.'); var pathLastHalf = split.slice(j).join('.'); var _schematype = schema.path(pathFirstHalf); var discriminatorKey = _schematype && _schematype.schema && _schematype.schema.options && _schematype.schema.options.discriminatorKey; // 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 && (_schematype.schema && _schematype.schema.discriminators) != null && discriminatorKey != null && pathLastHalf !== discriminatorKey) { var discriminatorVal = get(obj, pathFirstHalf + '.' + discriminatorKey); if (discriminatorVal != null) { schematype = _schematype.schema.discriminators[discriminatorVal].path(pathLastHalf); } } } } if (!schematype) { // Handle potential embedded array queries var _split = path.split('.'); var _j = _split.length; var _pathFirstHalf = void 0; var _pathLastHalf = void 0; var remainingConds = void 0; // 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 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; var ret = cast(schematype.caster.schema, remainingConds, options, context)[_pathLastHalf]; if (ret === void 0) { delete obj[path]; } else { obj[path] = ret; } } else { obj[path] = val; } continue; } if (isObject(val)) { // handle geo schemas that use object notation // { loc: { long: Number, lat: Number } var 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'; } if (geo) { var numbertype = new Types.Number('__QueryCasting__'); var value = val[geo]; 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') { var 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 }); } var 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 }); } } } _cast(value, numbertype, context); continue; } } if (schema.nested[path]) { continue; } var strict = 'strict' in options ? options.strict : schema.options.strict; var strictQuery = 'strictQuery' in options ? options.strictQuery : 'strict' in options ? options.strict : 'strict' in schema._userProvidedOptions ? schema._userProvidedOptions.strict : schema.options.strictQuery; if (options.upsert && strict) { if (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 (strictQuery === 'throw') { throw new StrictModeError(path, 'Path "' + path + '" is not in ' + 'schema and strictQuery is \'throw\'.'); } else if (strictQuery) { delete obj[path]; } } else if (val == null) { continue; } else if (getConstructorName(val) === 'Object') { any$conditionals = Object.keys(val).some(isOperator); if (!any$conditionals) { obj[path] = schematype.castForQueryWrapper({ val: val, context: context }); } else { var ks = Object.keys(val); var $cond = void 0; var _k = ks.length; 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 (var 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) { var casted = []; var valuesArray = val; var _iterator = _createForOfIteratorHelper(valuesArray), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _val = _step.value; casted.push(schematype.castForQueryWrapper({ val: _val, context: context })); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } obj[path] = { $in: casted }; } else { obj[path] = schematype.castForQueryWrapper({ val: val, context: context }); } } } return obj; }; 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 { var nearKeys = Object.keys(val); var nearLen = nearKeys.length; while (nearLen--) { var nkey = nearKeys[nearLen]; var 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 }); } } } } /***/ }), /***/ 6670: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var CastError = __webpack_require__(1795); /*! * 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; } throw new CastError('boolean', value, path); }; module.exports.convertToTrue = new Set([true, 'true', 1, '1', 'yes']); module.exports.convertToFalse = new Set([false, 'false', 0, '0', 'no']); /***/ }), /***/ 195: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var assert = __webpack_require__(9373); 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; } if (value instanceof Date) { assert.ok(!isNaN(value.valueOf())); return value; } var 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); } if (!isNaN(date.valueOf())) { return date; } assert.ok(false); }; /***/ }), /***/ 6209: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var Decimal128Type = __webpack_require__(5003); var assert = __webpack_require__(9373); module.exports = function castDecimal128(value) { if (value == null) { return value; } if (_typeof(value) === 'object' && typeof value.$numberDecimal === 'string') { return Decimal128Type.fromString(value.$numberDecimal); } if (value instanceof Decimal128Type) { return value; } if (typeof value === 'string') { return Decimal128Type.fromString(value); } if (Buffer.isBuffer(value)) { return new Decimal128Type(value); } if (typeof value === 'number') { return Decimal128Type.fromString(String(value)); } if (typeof value.valueOf === 'function' && typeof value.valueOf() === 'string') { return Decimal128Type.fromString(value.valueOf()); } assert.ok(false); }; /***/ }), /***/ 3065: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var assert = __webpack_require__(9373); /*! * Given a value, cast it to a number, or throw an `Error` if the value * cannot be casted. `null` and `undefined` are considered valid. * * @param {Any} value * @return {Number} * @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; } if (typeof val === 'string' || typeof val === 'boolean') { val = Number(val); } 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); }; /***/ }), /***/ 4731: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isBsonType = __webpack_require__(1563); var ObjectId = (__webpack_require__(9906).get)().ObjectId; module.exports = function castObjectId(value) { if (value == null) { return value; } if (isBsonType(value, 'ObjectID')) { return value; } if (value._id) { if (isBsonType(value._id, 'ObjectID')) { return value._id; } if (value._id.toString instanceof Function) { return new ObjectId(value._id.toString()); } } if (value.toString instanceof Function) { return new ObjectId(value.toString()); } return new ObjectId(value); }; /***/ }), /***/ 2417: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var CastError = __webpack_require__(1795); /*! * 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(); } throw new CastError('string', value, path); }; /***/ }), /***/ 8727: /***/ ((module, exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var EventEmitter = (__webpack_require__(9620).EventEmitter); var InternalCache = __webpack_require__(6379); var MongooseError = __webpack_require__(4888); var MixedSchema = __webpack_require__(3861); var ObjectExpectedError = __webpack_require__(4107); var ObjectParameterError = __webpack_require__(900); var ParallelValidateError = __webpack_require__(7962); var Schema = __webpack_require__(5506); var StrictModeError = __webpack_require__(3328); var ValidationError = __webpack_require__(122); var ValidatorError = __webpack_require__(2037); var VirtualType = __webpack_require__(459); var $__hasIncludedChildren = __webpack_require__(7427); var promiseOrCallback = __webpack_require__(8486); var cleanModifiedSubpaths = __webpack_require__(4134); var compile = (__webpack_require__(8724)/* .compile */ .M); var defineKey = (__webpack_require__(8724)/* .defineKey */ .c); var flatten = (__webpack_require__(2829)/* .flatten */ .x); var flattenObjectWithDottedPaths = __webpack_require__(207); var get = __webpack_require__(9981); var getEmbeddedDiscriminatorPath = __webpack_require__(111); var getKeysInSchemaOrder = __webpack_require__(37); var handleSpreadDoc = __webpack_require__(719); var immediate = __webpack_require__(1490); var isDefiningProjection = __webpack_require__(2183); var isExclusive = __webpack_require__(9098); var inspect = (__webpack_require__(161).inspect); var internalToObjectOptions = (__webpack_require__(4962)/* .internalToObjectOptions */ .h); var markArraySubdocsPopulated = __webpack_require__(5837); var mpath = __webpack_require__(3564); var queryhelpers = __webpack_require__(2888); var utils = __webpack_require__(6872); var isPromise = __webpack_require__(5543); var clone = utils.clone; var deepEqual = utils.deepEqual; var isMongooseObject = utils.isMongooseObject; var arrayAtomicsBackupSymbol = (__webpack_require__(8770).arrayAtomicsBackupSymbol); var arrayAtomicsSymbol = (__webpack_require__(8770).arrayAtomicsSymbol); var documentArrayParent = (__webpack_require__(8770).documentArrayParent); var documentIsModified = (__webpack_require__(8770).documentIsModified); var documentModifiedPaths = (__webpack_require__(8770).documentModifiedPaths); var documentSchemaSymbol = (__webpack_require__(8770).documentSchemaSymbol); var getSymbol = (__webpack_require__(8770).getSymbol); var populateModelSymbol = (__webpack_require__(8770).populateModelSymbol); var scopeSymbol = (__webpack_require__(8770).scopeSymbol); var schemaMixedSymbol = (__webpack_require__(8107).schemaMixedSymbol); var parentPaths = __webpack_require__(251); var DocumentArray; var MongooseArray; var Embedded; var 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 https://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); // Support `browserDocument.js` syntax if (this.$__schema == null) { var _schema = utils.isObject(fields) && !fields.instanceOfSchema ? new Schema(fields) : fields; this.$__setSchema(_schema); fields = skipId; skipId = options; options = arguments[4] || {}; } this.$__ = new InternalCache(); this.$isNew = 'isNew' in options ? options.isNew : true; if (options.priorDoc != null) { this.$__.priorDoc = options.priorDoc; } if (skipId) { this.$__.skipId = skipId; } if (obj != null && _typeof(obj) !== 'object') { throw new ObjectParameterError(obj, 'obj', 'Document'); } var defaults = true; if (options.defaults !== undefined) { this.$__.defaults = options.defaults; defaults = options.defaults; } var schema = this.$__schema; if (typeof fields === 'boolean' || fields === 'throw') { this.$__.strictMode = fields; fields = undefined; } else { this.$__.strictMode = schema.options.strict; if (fields != null) { this.$__.selected = fields; } } var requiredPaths = schema.requiredPaths(true); var _iterator = _createForOfIteratorHelper(requiredPaths), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var path = _step.value; this.$__.activePaths.require(path); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } var exclude = null; // determine if this doc is a result of a query with // excluded fields if (utils.isPOJO(fields)) { exclude = isExclusive(fields); this.$__.fields = fields; this.$__.exclude = exclude; } var hasIncludedChildren = exclude === false && fields ? $__hasIncludedChildren(fields) : null; if (this._doc == null) { this.$__buildDoc(obj, fields, skipId, exclude, hasIncludedChildren, false); // By default, defaults get applied **before** setting initial values // Re: gh-6155 if (defaults) { $__applyDefaults(this, fields, exclude, hasIncludedChildren, true, null); } } if (obj) { // Skip set hooks if (this.$__original_set) { this.$__original_set(obj, undefined, true, options); } else { this.$set(obj, undefined, true, options); } if (obj instanceof Document) { this.$isNew = obj.$isNew; } } // 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) { if (options.skipDefaults) { this.$__.skipDefaults = options.skipDefaults; } } else if (defaults) { $__applyDefaults(this, fields, exclude, hasIncludedChildren, false, options.skipDefaults); } if (!this.$__.strictMode && obj) { var _this = this; var keys = Object.keys(this._doc); 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 }); } }); } applyQueue(this); } Object.defineProperty(Document.prototype, 'isNew', { get: function get() { return this.$isNew; }, set: function set(value) { this.$isNew = value; } }); Object.defineProperty(Document.prototype, 'errors', { get: function get() { return this.$errors; }, set: function set(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 () { // Delay creating emitter until necessary because emitters take up a lot of memory, // especially for subdocuments. if (!this.$__.emitter) { if (emitterFn === 'emit') { return; } this.$__.emitter = new EventEmitter(); this.$__.emitter.setMaxListeners(0); } return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments); }; Document.prototype["$".concat(emitterFn)] = Document.prototype[emitterFn]; }); Document.prototype.constructor = Document; for (var 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, get: function get() { if (this.$__.locals == null) { this.$__.locals = {}; } return this.$__.locals; }, set: function set(v) { this.$__.locals = v; } }); /** * Boolean flag specifying if the document is new. * * @api public * @property $isNew * @memberOf Document * @instance */ Document.prototype.$isNew; /** * 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 }); /** * 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; /** * 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 */ Object.defineProperty(Document.prototype, '$op', { get: function get() { return this.$__.op || null; }, set: function set(value) { this.$__.op = value; } }); /*! * ignore */ function $__applyDefaults(doc, fields, exclude, hasIncludedChildren, isBeforeSetters, pathsToSkip) { var paths = Object.keys(doc.$__schema.paths); var plen = paths.length; for (var _i = 0; _i < plen; ++_i) { var def = void 0; var curPath = ''; var p = paths[_i]; if (p === '_id' && doc.$__.skipId) { continue; } var type = doc.$__schema.paths[p]; var path = type.splitPath(); var len = path.length; var included = false; var doc_ = doc._doc; for (var j = 0; j < len; ++j) { if (doc_ == null) { break; } var piece = path[j]; curPath += (!curPath.length ? '' : '.') + piece; if (exclude === true) { if (curPath in fields) { break; } } else if (exclude === false && fields && !included) { var hasSubpaths = type.$isSingleNested || type.$isMongooseDocumentArray; if (curPath in fields || hasSubpaths && hasIncludedChildren != null && hasIncludedChildren[curPath]) { included = true; } else if (hasIncludedChildren != null && !hasIncludedChildren[curPath]) { break; } } if (j === len - 1) { if (doc_[piece] !== void 0) { break; } 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; } if (pathsToSkip && pathsToSkip[curPath]) { break; } 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; } 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; } if (typeof def !== 'undefined') { doc_[piece] = def; doc.$__.activePaths["default"](p); } } } else { doc_ = doc_[piece]; } } } } /*! * ignore */ function $applyDefaultsToNested(val, path, doc) { if (val == null) { return; } flattenObjectWithDottedPaths(val); var paths = Object.keys(doc.$__schema.paths); var plen = paths.length; var pathPieces = path.indexOf('.') === -1 ? [path] : path.split('.'); for (var _i2 = 0; _i2 < plen; ++_i2) { var curPath = ''; var p = paths[_i2]; if (!p.startsWith(path + '.')) { continue; } var type = doc.$__schema.paths[p]; var pieces = type.splitPath().slice(pathPieces.length); var len = pieces.length; if (type.defaultValue === void 0) { continue; } var cur = val; for (var j = 0; j < len; ++j) { if (cur == null) { break; } var piece = pieces[j]; if (j === len - 1) { if (cur[piece] !== void 0) { break; } try { var def = type.getDefault(doc, false); if (def !== void 0) { cur[piece] = def; } } catch (err) { doc.invalidate(path + '.' + curPath, err); break; } break; } curPath += (!curPath.length ? '' : '.') + piece; cur[piece] = cur[piece] || {}; cur = cur[piece]; } } } /** * 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) { var doc = {}; var 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(function (p) { return !p.includes('$*'); }); var plen = paths.length; var ii = 0; for (; ii < plen; ++ii) { var p = paths[ii]; if (p === '_id') { if (skipId) { continue; } if (obj && '_id' in obj) { continue; } } var path = this.$__schema.paths[p].splitPath(); var len = path.length; var last = len - 1; var curPath = ''; var doc_ = doc; var included = false; for (var _i3 = 0; _i3 < len; ++_i3) { var piece = path[_i3]; if (!curPath.length) { curPath = piece; } else { curPath += '.' + piece; } // 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; } } if (_i3 < last) { doc_ = doc_[piece] || (doc_[piece] = {}); } } } this._doc = doc; }; /*! * Converts to POJO when you use the document for querying */ 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 */ Document.prototype.init = function (doc, opts, fn) { if (typeof opts === 'function') { fn = opts; opts = null; } this.$__init(doc, opts); if (fn) { fn(null, this); } return this; }; Document.prototype.$init = function () { return this.constructor.prototype.init.apply(this, arguments); }; 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) { var id = String(doc._id); var _iterator2 = _createForOfIteratorHelper(opts.populated), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var item = _step2.value; if (item.isVirtual) { this.$populated(item.path, utils.getValue(item.path, doc), item); } else { this.$populated(item.path, item._docs[id], item); } if (item._childDocs == null) { continue; } var _iterator3 = _createForOfIteratorHelper(item._childDocs), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var child = _step3.value; if (child == null || child.$__ == null) { continue; } child.$__.parent = this; } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } item._childDocs = []; } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } init(this, doc, this._doc, opts); markArraySubdocsPopulated(this, opts.populated); this.$emit('init', this); this.constructor.emit('init', this); var hasIncludedChildren = this.$__.exclude === false && this.$__.fields ? $__hasIncludedChildren(this.$__.fields) : null; $__applyDefaults(this, this.$__.fields, this.$__.exclude, hasIncludedChildren, false, this.$__.skipDefaults); return this; }; /*! * Init helper. * * @param {Object} self document instance * @param {Object} obj raw mongodb doc * @param {Object} doc object we are initializing * @api private */ function init(self, obj, doc, opts, prefix) { prefix = prefix || ''; var keys = Object.keys(obj); var len = keys.length; var schemaType; var path; var i; var index = 0; var strict = self.$__.strictMode; var docSchema = self.$__schema; while (index < len) { _init(index++); } function _init(index) { i = keys[index]; path = prefix + i; schemaType = docSchema.path(path); // 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 (docSchema.$isRootDiscriminator && !self.$__isSelected(path)) { return; } if (!schemaType && utils.isPOJO(obj[i])) { // assume nested object if (!doc[i]) { doc[i] = {}; if (!strict && !(i in docSchema.tree) && !(i in docSchema.methods) && !(i in docSchema.virtuals)) { self[i] = doc[i]; } } init(self, obj[i], doc[i], opts, path + '.'); } else if (!schemaType) { doc[i] = obj[i]; if (!strict && !prefix) { 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] = schemaType._castNullish(null); } else if (obj[i] !== undefined) { var wasPopulated = obj[i].$__ == null ? null : obj[i].$__.wasPopulated; if (schemaType && !wasPopulated) { try { doc[i] = schemaType.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); } } } } /** * 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() { var args = Array.prototype.slice.call(arguments); args.unshift({ _id: this._id }); var query = this.constructor.update.apply(this.constructor, args); if (this.$session() != null) { if (!('session' in query.options)) { query.options.session = this.$session(); } } 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()`](https://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](https://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 */ Document.prototype.updateOne = function updateOne(doc, options, callback) { var _this2 = this; var query = this.constructor.updateOne({ _id: this._id }, doc, options); query.pre(function (cb) { _this2.constructor._middleware.execPre('updateOne', _this2, [_this2], cb); }); query.post(function (cb) { _this2.constructor._middleware.execPost('updateOne', _this2, [_this2], {}, cb); }); if (this.$session() != null) { if (!('session' in query.options)) { query.options.session = this.$session(); } } if (callback != null) { return query.exec(callback); } 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() { var args = Array.prototype.slice.call(arguments); args.unshift({ _id: this._id }); return this.constructor.replaceOne.apply(this.constructor, args); }; /** * 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()`.'); } if (session == null && this.$__.session == null) { return; } this.$__.session = session; if (!this.$isSubdocument) { var subdocs = this.$getAllSubdocs(); var _iterator4 = _createForOfIteratorHelper(subdocs), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var child = _step4.value; child.$session(session); } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } } 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) { var keys = Array.from(new Set(Object.keys(this._doc).concat(Object.keys(obj)))); for (var _i4 = 0, _keys = keys; _i4 < _keys.length; _i4++) { var key = _keys[_i4]; 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]); } return this; }; /** * 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 * @param {Boolean} [options.merge=false] if true, setting a [nested path](/docs/subdocs.html#subdocuments-versus-nested-paths) will merge existing values rather than overwrite the whole object. So `doc.set('nested', { a: 1, b: 2 })` becomes `doc.set('nested.a', 1); doc.set('nested.b', 2);` * @method $set * @name $set * @memberOf Document * @instance * @api public */ Document.prototype.$set = function $set(path, val, type, options) { var _this3 = this; if (utils.isPOJO(type)) { options = type; type = undefined; } var merge = options && options.merge; var adhoc = type && type !== true; var constructing = type === true; var adhocs; var keys; var i = 0; var pathtype; var key; var prefix; var strict = options && '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) { var _ref = [val, path]; path = _ref[0]; val = _ref[1]; } 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) { var _ref2 = [val, path]; path = _ref2[0]; val = _ref2[1]; } prefix = val ? val + '.' : ''; keys = getKeysInSchemaOrder(this.$__schema, path); var len = keys.length; // `_skipMinimizeTopLevel` is because we may have deleted the top-level // nested key to ensure key order. var _skipMinimizeTopLevel = options && options._skipMinimizeTopLevel || false; if (len === 0 && _skipMinimizeTopLevel) { delete options._skipMinimizeTopLevel; if (val) { this.$set(val, {}); } return this; } for (var _i5 = 0; _i5 < len; ++_i5) { key = keys[_i5]; var pathName = prefix + key; pathtype = this.$__schema.pathType(pathName); var 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 && valForKey != 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 (pathtype === 'adhocOrUndefined') { pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true }); } if (pathtype === 'real' || pathtype === 'virtual') { var 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); } } } else if (path[key] !== void 0) { this.$set(prefix + key, path[key], constructing, options); } } // Ensure all properties are in correct order var orderedDoc = {}; var orderedKeys = Object.keys(this.$__schema.tree); for (var _i6 = 0, _len = orderedKeys.length; _i6 < _len; ++_i6) { (key = orderedKeys[_i6]) && this._doc.hasOwnProperty(key) && (orderedDoc[key] = undefined); } this._doc = Object.assign(orderedDoc, this._doc); return this; } var pathType = this.$__schema.pathType(path); if (pathType === 'adhocOrUndefined') { pathType = getEmbeddedDiscriminatorPath(this, path, { typeOnly: true }); } // Assume this is a Mongoose document that was copied into a POJO using // `Object.assign()` or `{...doc}` val = handleSpreadDoc(val); // if this doc is being constructed we should not trigger getters var priorVal = function () { if (_this3.$__.priorDoc != null) { return _this3.$__.priorDoc.$__getValue(path); } if (constructing) { return void 0; } return _this3.$__getValue(path); }(); 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; } var hasInitialVal = this.$__.savedState != null && this.$__.savedState.hasOwnProperty(path); if (this.$__.savedState != null && !this.$isNew && !this.$__.savedState.hasOwnProperty(path)) { var initialVal = this.$__getValue(path); this.$__.savedState[path] = initialVal; var _keys3 = Object.keys(initialVal || {}); for (var _i7 = 0, _keys4 = _keys3; _i7 < _keys4.length; _i7++) { var _key = _keys4[_i7]; this.$__.savedState[path + '.' + _key] = initialVal[_key]; } } if (!merge) { this.$__setValue(path, null); cleanModifiedSubpaths(this, path); } else { return this.$set(val, path, constructing); } var _keys2 = getKeysInSchemaOrder(this.$__schema, val, path); this.$__setValue(path, {}); var _iterator5 = _createForOfIteratorHelper(_keys2), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var _key2 = _step5.value; this.$set(path + '.' + _key2, val[_key2], constructing, options); } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } if (priorVal != null && utils.deepEqual(hasInitialVal ? this.$__.savedState[path] : priorVal, val)) { this.unmarkModified(path); } else { this.markModified(path); } return this; } this.invalidate(path, new MongooseError.CastError('Object', val, path)); return this; } var schema; var parts = path.indexOf('.') === -1 ? [path] : path.split('.'); // 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 var mixed; for (i = 0; i < parts.length; ++i) { var 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; } schema = this.$__schema.path(subpath); if (schema == null) { continue; } 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 var cur = this._doc; var 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); } } var pathToMark; // 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 { var _len2 = parts.length; for (i = 0; i < _len2; ++i) { var _subpath = parts.slice(0, i + 1).join('.'); if (this.$get(_subpath, null, { getters: false }) === null) { pathToMark = _subpath; break; } } if (!pathToMark) { pathToMark = path; } } if (!schema) { this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal); if (pathType === 'nested' && val == null) { cleanModifiedSubpaths(this, path); } return this; } // 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 (val != null && merge && schema.$isSingleNested) { if (val instanceof Document) { val = val.toObject({ virtuals: false, transform: false }); } var _keys5 = Object.keys(val); for (var _i8 = 0, _keys6 = _keys5; _i8 < _keys6.length; _i8++) { var _key3 = _keys6[_i8]; this.$set(path + '.' + _key3, val[_key3], constructing, options); } return this; } var 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 var refMatches = function () { if (schema.options == null) { return false; } if (!(val instanceof Document)) { return false; } var model = val.constructor; // Check ref var ref = schema.options.ref; if (ref != null && (ref === model.modelName || ref === model.baseModelName)) { return true; } // Check refPath var refPath = schema.options.refPath; if (refPath == null) { return false; } var modelName = val.get(refPath); return modelName === model.modelName || modelName === model.baseModelName; }(); var didPopulate = false; if (refMatches && val instanceof Document && (!val.$__.wasPopulated || utils.deepEqual(val.$__.wasPopulated.value, val._id))) { var unpopulatedValue = schema && schema.$isSingleNested ? schema.cast(val, this) : val._id; this.$populated(path, unpopulatedValue, _defineProperty({}, populateModelSymbol, val.constructor)); val.$__.wasPopulated = { value: unpopulatedValue }; didPopulate = true; } var popOpts; var typeKey = this.$__schema.options.typeKey; 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 = _defineProperty({}, populateModelSymbol, val[0].constructor); this.$populated(path, val.map(function (v) { return v._id; }), popOpts); var _iterator6 = _createForOfIteratorHelper(val), _step6; try { for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { var doc = _step6.value; doc.$__.wasPopulated = { value: doc._id }; } } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } didPopulate = true; } 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, options); } if (Array.isArray(val) && !Array.isArray(schema) && schema.$isMongooseDocumentArray && val.length !== 0 && val[0] != null && val[0].$__ != null && val[0].$__.populated != null) { var populatedPaths = Object.keys(val[0].$__.populated); var _loop = function _loop() { var populatedPath = _populatedPaths[_i9]; _this3.$populated(path + '.' + populatedPath, val.map(function (v) { return v.$populated(populatedPath); }), val[0].$__.populated[populatedPath].options); }; for (var _i9 = 0, _populatedPaths = populatedPaths; _i9 < _populatedPaths.length; _i9++) { _loop(); } 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 (var _i10 = 0; _i10 < val.length; ++_i10) { if (val[_i10] instanceof Document) { val.set(_i10, val[_i10]._id, true); } } } delete this.$__.populated[path]; } if (val != null && schema.$isSingleNested) { _checkImmutableSubpaths(val, schema, priorVal); } 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) { var savedState = null; var savedStatePath = null; if (!constructing) { var _doc = this.$isSubdocument ? this.ownerDocument() : this; savedState = _doc.$__.savedState; savedStatePath = this.$isSubdocument ? this.$__.fullPath + '.' + path : path; if (savedState != null) { var firstDot = savedStatePath.indexOf('.'); var topLevelPath = firstDot === -1 ? savedStatePath : savedStatePath.slice(0, firstDot); if (!savedState.hasOwnProperty(topLevelPath)) { savedState[topLevelPath] = utils.clone(_doc.$__getValue(topLevelPath)); } } } this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal); if (savedState != null && savedState.hasOwnProperty(savedStatePath) && utils.deepEqual(val, savedState[savedStatePath])) { this.unmarkModified(path); } } if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) { cleanModifiedSubpaths(this, path); } return this; }; /*! * ignore */ function _isManuallyPopulatedArray(val, ref) { if (!Array.isArray(val)) { return false; } if (val.length === 0) { return false; } var _iterator7 = _createForOfIteratorHelper(val), _step7; try { for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) { var el = _step7.value; if (!(el instanceof Document)) { return false; } var modelName = el.constructor.modelName; if (modelName == null) { return false; } if (el.constructor.modelName != ref && el.constructor.baseModelName != ref) { return false; } } } catch (err) { _iterator7.e(err); } finally { _iterator7.f(); } 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, options, constructing, parts, schema, val, priorVal) { if (options && options._skipMarkModified) { return false; } 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; } if (val === void 0 && !this.$__isSelected(path)) { // when a path is not selected in a query, its initial // value will be undefined. return true; } 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; } if (!deepEqual(val, priorVal || utils.getValue(path, this))) { return true; } 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; }; /** * 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 || __webpack_require__(1568); var shouldModify = this.$__shouldModify(pathToMark, path, options, constructing, parts, schema, val, priorVal); if (shouldModify) { this.markModified(pathToMark); // handle directly setting arrays (gh-1126) MongooseArray || (MongooseArray = __webpack_require__(1362)); if (val && utils.isMongooseArray(val)) { val._registerAtomic('$set', val); // Update embedded document parent references (gh-5189) if (utils.isMongooseDocumentArray(val)) { val.forEach(function (item) { item && item.__parentArray && (item.__parentArray = val); }); } } } else if (Array.isArray(val) && Array.isArray(priorVal) && utils.isMongooseArray(val) && utils.isMongooseArray(priorVal)) { val[arrayAtomicsSymbol] = priorVal[arrayAtomicsSymbol]; val[arrayAtomicsBackupSymbol] = priorVal[arrayAtomicsBackupSymbol]; if (utils.isMongooseDocumentArray(val)) { val.forEach(function (doc) { doc.isNew = false; }); } } var obj = this._doc; var i = 0; var l = parts.length; var cur = ''; for (; i < l; i++) { var next = i + 1; var 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]] && !Array.isArray(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]]; } } } }; /** * 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); }; /** * 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 */ Document.prototype.get = function (path, type, options) { var adhoc; options = options || {}; if (type) { adhoc = this.$__schema.interpretAsType(path, type, this.$__schema.options); } var schema = this.$__path(path); if (schema == null) { schema = this.$__schema.virtualpath(path); } if (schema instanceof MixedSchema) { var virtual = this.$__schema.virtualpath(path); if (virtual != null) { schema = virtual; } } var pieces = path.indexOf('.') === -1 ? [path] : path.split('.'); var obj = this._doc; 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]]; } for (var _i11 = 0, l = pieces.length; _i11 < l; _i11++) { if (obj && obj._doc) { obj = obj._doc; } if (obj == null) { obj = void 0; } else if (obj instanceof Map) { obj = obj.get(pieces[_i11], { getters: false }); } else if (_i11 === l - 1) { obj = utils.getValue(pieces[_i11], obj); } else { obj = obj[pieces[_i11]]; } } if (adhoc) { obj = adhoc.cast(obj); } 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 }); } return obj; }; /*! * ignore */ 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 */ Document.prototype.$__path = function (path) { var adhocs = this.$__.adhocPaths; var adhocType = adhocs && adhocs.hasOwnProperty(path) ? adhocs[path] : null; if (adhocType) { return adhocType; } return this.$__schema.path(path); }; /** * 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 */ 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 */ Document.prototype.unmarkModified = function (path) { this.$__.activePaths.init(path); if (this.$__.pathsToScopes != null) { delete this.$__.pathsToScopes[path]; } }; /** * 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); }; /** * 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) { var isEmptyOptions = { minimize: true, virtuals: false, getters: false, transform: false }; if (arguments.length !== 0) { var 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; } return Object.keys(this.toObject(isEmptyOptions)).length === 0; }; function _isEmpty(v) { if (v == null) { return true; } if (_typeof(v) !== 'object' || Array.isArray(v)) { return false; } for (var _i12 = 0, _Object$keys = Object.keys(v); _i12 < _Object$keys.length; _i12++) { var key = _Object$keys[_i12]; 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 */ Document.prototype.modifiedPaths = function (options) { options = options || {}; var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); var result = new Set(); var i = 0; var j = 0; var len = directModifiedPaths.length; for (i = 0; i < len; ++i) { var path = directModifiedPaths[i]; var parts = parentPaths(path); var pLen = parts.length; for (j = 0; j < pLen; ++j) { result.add(parts[j]); } if (!options.includeChildren) { continue; } var ii = 0; var cur = this.$get(path); if (_typeof(cur) === 'object' && cur !== null) { if (cur._doc) { cur = cur._doc; } var _len3 = cur.length; if (Array.isArray(cur)) { for (ii = 0; ii < _len3; ++ii) { var subPath = path + '.' + ii; if (!result.has(subPath)) { result.add(subPath); if (cur[ii] != null && cur[ii].$__) { var modified = cur[ii].modifiedPaths(); var iii = 0; var iiiLen = modified.length; for (iii = 0; iii < iiiLen; ++iii) { result.add(subPath + '.' + modified[iii]); } } } } } else { var keys = Object.keys(cur); var _ii = 0; var _len4 = keys.length; for (_ii = 0; _ii < _len4; ++_ii) { result.add(path + '.' + keys[_ii]); } } } } return Array.from(result); }; 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) { var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); if (directModifiedPaths.length === 0) { return false; } if (!Array.isArray(paths)) { paths = paths.indexOf(' ') === -1 ? [paths] : paths.split(' '); } var modified = modifiedPaths || this[documentModifiedPaths](); var isModifiedChild = paths.some(function (path) { return !!~modified.indexOf(path); }); return isModifiedChild || paths.some(function (path) { return directModifiedPaths.some(function (mod) { return mod === path || path.startsWith(mod + '.'); }); }); } return this.$__.activePaths.some('modify'); }; Document.prototype.$isModified = Document.prototype.isModified; 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 */ Document.prototype.$isDefault = function (path) { var _this4 = this; if (path == null) { return this.$__.activePaths.some('default'); } if (typeof path === 'string' && path.indexOf(' ') === -1) { return this.$__.activePaths.states["default"].hasOwnProperty(path); } var paths = path; if (!Array.isArray(paths)) { paths = paths.split(' '); } return paths.some(function (path) { return _this4.$__.activePaths.states["default"].hasOwnProperty(path); }); }; /** * 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 */ 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 */ Document.prototype.isDirectModified = function (path) { var _this5 = this; if (path == null) { return this.$__.activePaths.some('modify'); } if (typeof path === 'string' && path.indexOf(' ') === -1) { return this.$__.activePaths.states.modify.hasOwnProperty(path); } var paths = path; if (!Array.isArray(paths)) { paths = paths.split(' '); } return paths.some(function (path) { return _this5.$__.activePaths.states.modify.hasOwnProperty(path); }); }; /** * 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 */ Document.prototype.isInit = function (path) { var _this6 = this; if (path == null) { return this.$__.activePaths.some('init'); } if (typeof path === 'string' && path.indexOf(' ') === -1) { return this.$__.activePaths.states.init.hasOwnProperty(path); } var paths = path; if (!Array.isArray(paths)) { paths = paths.split(' '); } return paths.some(function (path) { return _this6.$__.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 */ Document.prototype.isSelected = function isSelected(path) { var _this7 = this; if (this.$__.selected == null) { return true; } if (!path) { return false; } if (path === '_id') { return this.$__.selected._id !== 0; } if (path.indexOf(' ') !== -1) { path = path.split(' '); } if (Array.isArray(path)) { return path.some(function (p) { return _this7.$__isSelected(p); }); } var paths = Object.keys(this.$__.selected); var inclusive = null; if (paths.length === 1 && paths[0] === '_id') { // only _id was selected. return this.$__.selected._id === 0; } for (var _i13 = 0, _paths = paths; _i13 < _paths.length; _i13++) { var cur = _paths[_i13]; if (cur === '_id') { continue; } if (!isDefiningProjection(this.$__.selected[cur])) { continue; } inclusive = !!this.$__.selected[cur]; break; } if (inclusive === null) { return true; } if (path in this.$__.selected) { return inclusive; } var pathDot = path + '.'; for (var _i14 = 0, _paths2 = paths; _i14 < _paths2.length; _i14++) { var _cur = _paths2[_i14]; if (_cur === '_id') { continue; } if (_cur.startsWith(pathDot)) { return inclusive || _cur !== pathDot; } if (pathDot.startsWith(_cur + '.')) { return inclusive; } } return !inclusive; }; Document.prototype.$__isSelected = Document.prototype.isSelected; /** * 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 */ Document.prototype.isDirectSelected = function isDirectSelected(path) { var _this8 = this; if (this.$__.selected == null) { return true; } if (path === '_id') { return this.$__.selected._id !== 0; } if (path.indexOf(' ') !== -1) { path = path.split(' '); } if (Array.isArray(path)) { return path.some(function (p) { return _this8.isDirectSelected(p); }); } var paths = Object.keys(this.$__.selected); var inclusive = null; if (paths.length === 1 && paths[0] === '_id') { // only _id was selected. return this.$__.selected._id === 0; } for (var _i15 = 0, _paths3 = paths; _i15 < _paths3.length; _i15++) { var cur = _paths3[_i15]; if (cur === '_id') { continue; } if (!isDefiningProjection(this.$__.selected[cur])) { continue; } inclusive = !!this.$__.selected[cur]; break; } if (inclusive === null) { return true; } if (this.$__.selected.hasOwnProperty(path)) { return inclusive; } return !inclusive; }; /** * 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) { var _this9 = this; var parallelValidate; this.$op = 'validate'; 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 }); } 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') { var isOnePathOnly = options.pathsToSkip.indexOf(' ') === -1; options.pathsToSkip = isOnePathOnly ? [options.pathsToSkip] : options.pathsToSkip.split(' '); } return promiseOrCallback(callback, function (cb) { if (parallelValidate != null) { return cb(parallelValidate); } _this9.$__validate(pathsToValidate, options, function (error) { _this9.$op = null; _this9.$__.validating = null; cb(error); }); }, this.constructor.events); }; Document.prototype.$validate = Document.prototype.validate; /*! * ignore */ function _evaluateRequiredFunctions(doc) { var requiredFields = Object.keys(doc.$__.activePaths.states.require); var i = 0; var len = requiredFields.length; for (i = 0; i < len; ++i) { var path = requiredFields[i]; var 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); } } } } /*! * ignore */ function _getPathsToValidate(doc) { var skipSchemaValidators = {}; _evaluateRequiredFunctions(doc); // only validate required fields when necessary var 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; })); 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); } var subdocs = doc.$getAllSubdocs(); var modifiedPaths = doc.modifiedPaths(); var _iterator8 = _createForOfIteratorHelper(subdocs), _step8; try { for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) { var subdoc = _step8.value; if (subdoc.$basePath) { // Remove child paths for now, because we'll be validating the whole // subdoc var fullPathToSubdoc = subdoc.$__fullPathWithIndexes(); var _iterator13 = _createForOfIteratorHelper(paths), _step13; try { for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) { var p = _step13.value; if (p == null || p.startsWith(fullPathToSubdoc + '.')) { paths["delete"](p); } } } catch (err) { _iterator13.e(err); } finally { _iterator13.f(); } if (doc.$isModified(fullPathToSubdoc, modifiedPaths) && !doc.isDirectModified(fullPathToSubdoc) && !doc.$isDefault(fullPathToSubdoc)) { paths.add(fullPathToSubdoc); skipSchemaValidators[fullPathToSubdoc] = true; } } } } catch (err) { _iterator8.e(err); } finally { _iterator8.f(); } var _iterator9 = _createForOfIteratorHelper(paths), _step9; try { for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) { var path = _step9.value; var _pathType = doc.$__schema.path(path); if (!_pathType) { continue; } if (_pathType.$isMongooseDocumentArray) { var _iterator14 = _createForOfIteratorHelper(paths), _step14; try { for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) { var _p = _step14.value; if (_p == null || _p.startsWith(_pathType.path + '.')) { paths["delete"](_p); } } } catch (err) { _iterator14.e(err); } finally { _iterator14.f(); } } // Optimization: if primitive path with no validators, or array of primitives // with no validators, skip validating this path entirely. if (!_pathType.caster && _pathType.validators.length === 0) { paths["delete"](path); } else if (_pathType.$isMongooseArray && !_pathType.$isMongooseDocumentArray && // Skip document arrays... !_pathType.$embeddedSchemaType.$isMongooseArray && // and arrays of arrays _pathType.validators.length === 0 && // and arrays with top-level validators _pathType.$embeddedSchemaType.validators.length === 0) { paths["delete"](path); } } // 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 } catch (err) { _iterator9.e(err); } finally { _iterator9.f(); } var _iterator10 = _createForOfIteratorHelper(paths), _step10; try { for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) { var _path2 = _step10.value; var _pathType2 = doc.$__schema.path(_path2); if (!_pathType2) { continue; } if (!_pathType2.$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 !Array.isArray(_pathType2) && _pathType2.$isMongooseDocumentArray && !(_pathType2 && _pathType2.schemaOptions && _pathType2.schemaOptions.required)) { continue; } // gh-11380: optimization. If the array isn't a document array and there's no validators // on the array type, there's no need to run validation on the individual array elements. if (_pathType2.$isMongooseArray && !_pathType2.$isMongooseDocumentArray && // Skip document arrays... !_pathType2.$embeddedSchemaType.$isMongooseArray && // and arrays of arrays _pathType2.$embeddedSchemaType.validators.length === 0) { continue; } var val = doc.$__getValue(_path2); _pushNestedArrayPaths(val, paths, _path2); } } catch (err) { _iterator10.e(err); } finally { _iterator10.f(); } function _pushNestedArrayPaths(val, paths, path) { if (val != null) { var numElements = val.length; for (var j = 0; j < numElements; ++j) { if (Array.isArray(val[j])) { _pushNestedArrayPaths(val[j], paths, path + '.' + j); } else { paths.add(path + '.' + j); } } } } var flattenOptions = { skipArrays: true }; var _iterator11 = _createForOfIteratorHelper(paths), _step11; try { for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) { var pathToCheck = _step11.value; if (doc.$__schema.nested[pathToCheck]) { var _v = doc.$__getValue(pathToCheck); if (isMongooseObject(_v)) { _v = _v.toObject({ transform: false }); } var flat = flatten(_v, pathToCheck, flattenOptions, doc.$__schema); Object.keys(flat).forEach(addToPaths); } } } catch (err) { _iterator11.e(err); } finally { _iterator11.f(); } var _iterator12 = _createForOfIteratorHelper(paths), _step12; try { for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) { var _path3 = _step12.value; // 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(_path3)) { paths["delete"](_path3); continue; } var _pathType3 = doc.$__schema.path(_path3); if (!_pathType3 || !_pathType3.$isSchemaMap) { continue; } var _val = doc.$__getValue(_path3); if (_val == null) { continue; } var _iterator15 = _createForOfIteratorHelper(_val.keys()), _step15; try { for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) { var key = _step15.value; paths.add(_path3 + '.' + key); } } catch (err) { _iterator15.e(err); } finally { _iterator15.f(); } } } catch (err) { _iterator12.e(err); } finally { _iterator12.f(); } paths = Array.from(paths); return [paths, skipSchemaValidators]; } /*! * ignore */ Document.prototype.$__validate = function (pathsToValidate, options, callback) { var _this10 = this; if (typeof pathsToValidate === 'function') { callback = pathsToValidate; options = null; pathsToValidate = null; } else if (typeof options === 'function') { callback = options; options = null; } var hasValidateModifiedOnlyOption = options && _typeof(options) === 'object' && 'validateModifiedOnly' in options; var pathsToSkip = options && options.pathsToSkip || null; var shouldValidateModifiedOnly; if (hasValidateModifiedOnlyOption) { shouldValidateModifiedOnly = !!options.validateModifiedOnly; } else { shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly; } var _this = this; var _complete = function _complete() { var validationError = _this10.$__.validationError; _this10.$__.validationError = null; _this10.$__.validating = null; if (shouldValidateModifiedOnly && validationError != null) { // Remove any validation errors that aren't from modified paths var errors = Object.keys(validationError.errors); for (var _i16 = 0, _errors = errors; _i16 < _errors.length; _i16++) { var errPath = _errors[_i16]; if (!_this10.$isModified(errPath)) { delete validationError.errors[errPath]; } } if (Object.keys(validationError.errors).length === 0) { validationError = void 0; } } _this10.$__.cachedRequired = {}; _this10.$emit('validate', _this); _this10.constructor.emit('validate', _this); if (validationError) { for (var key in validationError.errors) { // Make sure cast errors persist if (!_this10[documentArrayParent] && validationError.errors[key] instanceof MongooseError.CastError) { _this10.invalidate(key, validationError.errors[key]); } } return validationError; } }; // only validate required fields when necessary var pathDetails = _getPathsToValidate(this); var paths = shouldValidateModifiedOnly ? pathDetails[0].filter(function (path) { return _this10.$isModified(path); }) : pathDetails[0]; var 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 () { var error = _complete(); if (error) { return _this.$__schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function (error) { callback(error); }); } callback(null, _this); }); } var validated = {}; var total = 0; var _iterator16 = _createForOfIteratorHelper(paths), _step16; try { for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) { var path = _step16.value; validatePath(path); } } catch (err) { _iterator16.e(err); } finally { _iterator16.f(); } function validatePath(path) { if (path == null || validated[path]) { return; } validated[path] = true; total++; immediate(function () { var schemaType = _this.$__schema.path(path); if (!schemaType) { return --total || complete(); } // If user marked as invalid or there was a cast error, don't validate if (!_this.$isValid(path)) { --total || complete(); return; } // 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(); } var 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. var 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; } var scope = _this.$__.pathsToScopes != null && path in _this.$__.pathsToScopes ? _this.$__.pathsToScopes[path] : _this; var doValidateOptions = { skipSchemaValidators: skipSchemaValidators[path], path: path, validateModifiedOnly: shouldValidateModifiedOnly }; schemaType.doValidate(val, function (err) { if (err) { var 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); }); } function complete() { var error = _complete(); if (error) { return _this.$__schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function (error) { callback(error); }); } callback(null, _this); } }; /*! * ignore */ function _handlePathsToValidate(paths, pathsToValidate) { var _pathsToValidate = new Set(pathsToValidate); var parentPaths = new Map([]); var _iterator17 = _createForOfIteratorHelper(pathsToValidate), _step17; try { for (_iterator17.s(); !(_step17 = _iterator17.n()).done;) { var path = _step17.value; if (path.indexOf('.') === -1) { continue; } var pieces = path.split('.'); var cur = pieces[0]; for (var _i17 = 1; _i17 < pieces.length; ++_i17) { // 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[_i17]; } } } catch (err) { _iterator17.e(err); } finally { _iterator17.f(); } var ret = []; var _iterator18 = _createForOfIteratorHelper(paths), _step18; try { for (_iterator18.s(); !(_step18 = _iterator18.n()).done;) { var _path4 = _step18.value; if (_pathsToValidate.has(_path4)) { ret.push(_path4); } else if (parentPaths.has(_path4)) { ret.push(parentPaths.get(_path4)); } } } catch (err) { _iterator18.e(err); } finally { _iterator18.f(); } return ret; } /*! * ignore */ function _handlePathsToSkip(paths, pathsToSkip) { pathsToSkip = new Set(pathsToSkip); paths = paths.filter(function (p) { return !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) { var _this11 = this; var _this = this; if (arguments.length === 1 && _typeof(arguments[0]) === 'object' && !Array.isArray(arguments[0])) { options = arguments[0]; pathsToValidate = null; } var hasValidateModifiedOnlyOption = options && _typeof(options) === 'object' && 'validateModifiedOnly' in options; var shouldValidateModifiedOnly; if (hasValidateModifiedOnlyOption) { shouldValidateModifiedOnly = !!options.validateModifiedOnly; } else { shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly; } var pathsToSkip = options && options.pathsToSkip; if (typeof pathsToValidate === 'string') { var isOnePathOnly = pathsToValidate.indexOf(' ') === -1; pathsToValidate = isOnePathOnly ? [pathsToValidate] : pathsToValidate.split(' '); } else if (typeof pathsToSkip === 'string' && pathsToSkip.indexOf(' ') !== -1) { pathsToSkip = pathsToSkip.split(' '); } // only validate required fields when necessary var pathDetails = _getPathsToValidate(this); var paths = shouldValidateModifiedOnly ? pathDetails[0].filter(function (path) { return _this11.$isModified(path); }) : pathDetails[0]; var skipSchemaValidators = pathDetails[1]; if (Array.isArray(pathsToValidate)) { paths = _handlePathsToValidate(paths, pathsToValidate); } else if (Array.isArray(pathsToSkip)) { paths = _handlePathsToSkip(paths, pathsToSkip); } var validating = {}; for (var _i18 = 0, len = paths.length; _i18 < len; ++_i18) { var path = paths[_i18]; if (validating[path]) { continue; } validating[path] = true; var p = _this.$__schema.path(path); if (!p) { continue; } if (!_this.$isValid(path)) { continue; } var val = _this.$__getValue(path); var _err = p.doValidateSync(val, _this, { skipSchemaValidators: skipSchemaValidators[path], path: path, validateModifiedOnly: shouldValidateModifiedOnly }); if (_err) { var isSubdoc = p.$isSingleNested || p.$isArraySubdocument || p.$isMongooseDocumentArray; if (isSubdoc && _err instanceof ValidationError) { continue; } _this.invalidate(path, _err, undefined, true); } } var err = _this.$__.validationError; _this.$__.validationError = undefined; _this.$emit('validate', _this); _this.constructor.emit('validate', _this); if (err) { for (var 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); * 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 */ Document.prototype.invalidate = function (path, err, val, kind) { if (!this.$__.validationError) { this.$__.validationError = new ValidationError(this); } if (this.$__.validationError.errors[path]) { return; } if (!err || typeof err === 'string') { err = new ValidatorError({ path: path, message: err, type: kind || 'user defined', value: val }); } if (this.$__.validationError === err) { return this.$__.validationError; } this.$__.validationError.addError(path, err); return this.$__.validationError; }; /** * 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; } }; /*! * ignore */ function _markValidSubpaths(doc, path) { if (!doc.$__.validationError) { return; } var keys = Object.keys(doc.$__.validationError.errors); for (var _i19 = 0, _keys7 = keys; _i19 < _keys7.length; _i19++) { var key = _keys7[_i19]; if (key.startsWith(path + '.')) { delete doc.$__.validationError.errors[key]; } } if (Object.keys(doc.$__.validationError.errors).length === 0) { doc.$__.validationError = null; } } /*! * ignore */ function _checkImmutableSubpaths(subdoc, schematype, priorVal) { var schema = schematype.schema; if (schema == null) { return; } for (var _i20 = 0, _Object$keys2 = Object.keys(schema.paths); _i20 < _Object$keys2.length; _i20++) { var key = _Object$keys2[_i20]; var path = schema.paths[key]; if (path.$immutableSetter == null) { continue; } var 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](https://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 https://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) { var _this12 = this; if (this.$__.validationError == null || Object.keys(this.$__.validationError.errors).length === 0) { return true; } if (path == null) { return false; } if (path.indexOf(' ') !== -1) { path = path.split(' '); } if (Array.isArray(path)) { return path.some(function (p) { return _this12.$__.validationError.errors[p] == null; }); } 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() { var _this = this; // Skip for subdocuments var subdocs = this.$parent() === this ? this.$getAllSubdocs() : []; var resetArrays = new Set(); var _iterator19 = _createForOfIteratorHelper(subdocs), _step19; try { for (_iterator19.s(); !(_step19 = _iterator19.n()).done;) { var subdoc = _step19.value; var fullPathWithIndexes = subdoc.$__fullPathWithIndexes(); if (this.isModified(fullPathWithIndexes) || isParentInit(fullPathWithIndexes)) { subdoc.$__reset(); if (subdoc.$isDocumentArrayElement) { if (!resetArrays.has(subdoc.parentArray())) { var array = subdoc.parentArray(); this.$__.activePaths.clearPath(fullPathWithIndexes.replace(/\.\d+$/, '').slice(-subdoc.$basePath - 1)); array[arrayAtomicsBackupSymbol] = array[arrayAtomicsSymbol]; array[arrayAtomicsSymbol] = {}; resetArrays.add(array); } } else { if (subdoc.$parent() === this) { this.$__.activePaths.clearPath(subdoc.$basePath); } else if (subdoc.$parent() != null && subdoc.$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 subdoc.$parent().$__reset(); } } } } } catch (err) { _iterator19.e(err); } finally { _iterator19.f(); } function isParentInit(path) { path = path.indexOf('.') === -1 ? [path] : path.split('.'); var cur = ''; for (var _i21 = 0; _i21 < path.length; ++_i21) { cur += (cur.length ? '.' : '') + path[_i21]; if (_this.$__.activePaths[cur] === 'init') { return true; } } return false; } // clear atomics this.$__dirty().forEach(function (dirt) { var type = dirt.value; if (type && type[arrayAtomicsSymbol]) { type[arrayAtomicsBackupSymbol] = type[arrayAtomicsSymbol]; type[arrayAtomicsSymbol] = {}; } }); 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 */ Document.prototype.$__undoReset = function $__undoReset() { if (this.$__.backup == null || this.$__.backup.activePaths == null) { return; } this.$__.activePaths.states.modify = this.$__.backup.activePaths.modify; this.$__.activePaths.states["default"] = this.$__.backup.activePaths["default"]; this.$__.validationError = this.$__.backup.validationError; this.$errors = this.$__.backup.errors; var _iterator20 = _createForOfIteratorHelper(this.$__dirty()), _step20; try { for (_iterator20.s(); !(_step20 = _iterator20.n()).done;) { var dirt = _step20.value; var type = dirt.value; if (type && type[arrayAtomicsSymbol] && type[arrayAtomicsBackupSymbol]) { type[arrayAtomicsSymbol] = type[arrayAtomicsBackupSymbol]; } } } catch (err) { _iterator20.e(err); } finally { _iterator20.f(); } var _iterator21 = _createForOfIteratorHelper(this.$getAllSubdocs()), _step21; try { for (_iterator21.s(); !(_step21 = _iterator21.n()).done;) { var subdoc = _step21.value; subdoc.$__undoReset(); } } catch (err) { _iterator21.e(err); } finally { _iterator21.f(); } }; /** * Returns this documents dirty paths / vals. * * @api private * @method $__dirty * @memberOf Document * @instance */ Document.prototype.$__dirty = function () { var _this = this; var 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) }; })); var allPaths = new Map(all.filter(function (el) { return el != null; }).map(function (el) { return [el.path, el.value]; })); // Ignore "foo.a" if "foo" is dirty already. var minimal = []; all.forEach(function (item) { if (!item) { return; } var top = null; var array = parentPaths(item.path); for (var _i22 = 0; _i22 < array.length - 1; _i22++) { if (allPaths.has(array[_i22])) { top = allPaths.get(array[_i22]); 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; }; /** * Assigns/compiles `schema` into this documents prototype. * * @param {Schema} schema * @api private * @method $__setSchema * @memberOf Document * @instance */ Document.prototype.$__setSchema = function (schema) { compile(schema.tree, this, undefined, schema.options); // Apply default getters if virtual doesn't have any (gh-6262) for (var _i23 = 0, _Object$keys3 = Object.keys(schema.virtuals); _i23 < _Object$keys3.length; _i23++) { var key = _Object$keys3[_i23]; 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 = __webpack_require__(6077)); // validate all document arrays. return this.$__.activePaths.map('init', 'modify', function (i) { return this.$__getValue(i); }.bind(this)).filter(function (val) { return val && Array.isArray(val) && utils.isMongooseDocumentArray(val) && val.length; }).reduce(function (seed, array) { return seed.concat(array); }, []).filter(function (doc) { return doc; }); }; /** * Get all subdocs (by bfs) * * @api public * @method $getAllSubdocs * @memberOf Document * @instance */ Document.prototype.$getAllSubdocs = function () { DocumentArray || (DocumentArray = __webpack_require__(6077)); Embedded = Embedded || __webpack_require__(1568); function docReducer(doc, seed, path) { var val = doc; var 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 && !Array.isArray(val) && val.$isSingleNested) { seed = Object.keys(val._doc).reduce(function (seed, path) { return docReducer(val, seed, path); }, seed); seed.push(val); } else if (val && utils.isMongooseDocumentArray(val)) { 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 (var _i24 = 0, _Object$keys4 = Object.keys(val); _i24 < _Object$keys4.length; _i24++) { var _path5 = _Object$keys4[_i24]; docReducer(val, seed, _path5); } } return seed; } var subDocs = []; for (var _i25 = 0, _Object$keys5 = Object.keys(this._doc); _i25 < _Object$keys5.length; _i25++) { var path = _Object$keys5[_i25]; docReducer(this, subDocs, path); } return subDocs; }; /*! * Runs queued functions */ function applyQueue(doc) { var q = doc.$__schema && doc.$__schema.callQueue; if (!q.length) { return; } var _iterator22 = _createForOfIteratorHelper(q), _step22; try { for (_iterator22.s(); !(_step22 = _iterator22.n()).done;) { var pair = _step22.value; if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') { doc[pair[0]].apply(doc, pair[1]); } } } catch (err) { _iterator22.e(err); } finally { _iterator22.f(); } } /*! * ignore */ 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); } }; /** * Internal helper for toObject() and toJSON() that doesn't manipulate options * * @api private * @method $toObject * @memberOf Document * @instance */ Document.prototype.$toObject = function (options, json) { var defaultOptions = { transform: true, flattenDecimals: true }; var path = json ? 'toJSON' : 'toObject'; var baseOptions = this.constructor && this.constructor.base && this.constructor.base.options && get(this.constructor.base.options, path) || {}; var schemaOptions = this.$__schema && 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) ? _objectSpread({}, options) : {}; options._calledWithOptions = options._calledWithOptions || _objectSpread({}, options); var _minimize; if (options._calledWithOptions.minimize != null) { _minimize = options.minimize; } else if (defaultOptions.minimize != null) { _minimize = defaultOptions.minimize; } else { _minimize = schemaOptions.minimize; } var 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. var cloneOptions = Object.assign({}, options, { _isNested: true, json: json, minimize: _minimize, flattenMaps: flattenMaps, _seen: options && options._seen || new Map() }); if (utils.hasUserDefinedProperty(options, 'getters')) { cloneOptions.getters = options.getters; } if (utils.hasUserDefinedProperty(options, 'virtuals')) { cloneOptions.virtuals = options.virtuals; } var depopulate = options.depopulate || options._parentOptions && options._parentOptions.depopulate || false; // _isNested will only be true if this is not the top level document, we // should never depopulate the top-level document if (depopulate && options._isNested && this.$__.wasPopulated) { return clone(this.$__.wasPopulated.value || this._id, cloneOptions); } // merge default options with input options. options = utils.options(defaultOptions, options); options._isNested = true; options.json = json; options.minimize = _minimize; cloneOptions._parentOptions = options; cloneOptions._skipSingleNestedGetters = true; var gettersOptions = Object.assign({}, cloneOptions); gettersOptions._skipSingleNestedGetters = false; // remember the root transform function // to save it from being overwritten by sub-transform functions var originalTransform = options.transform; var ret = clone(this._doc, cloneOptions) || {}; if (options.getters) { applyGetters(this, ret, gettersOptions); if (options.minimize) { ret = minimize(ret) || {}; } } if (options.virtuals || options.getters && options.virtuals !== false) { applyVirtuals(this, ret, gettersOptions, options); } if (options.versionKey === false && this.$__schema.options.versionKey) { delete ret[this.$__schema.options.versionKey]; } var transform = options.transform; // 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 (options.useProjection) { omitDeselectedFields(this, ret); } if (transform === true || schemaOptions.toObject && transform) { var opts = options.json ? schemaOptions.toJSON : schemaOptions.toObject; if (opts) { transform = typeof options.transform === 'function' ? options.transform : opts.transform; } } else { options.transform = originalTransform; } if (typeof transform === 'function') { var xformed = transform(this, ret, options); if (typeof xformed !== 'undefined') { ret = xformed; } } return ret; }; /** * Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). * * Buffers are converted to instances of [mongodb.Binary](https://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 https://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); }; /*! * Minimizes an object, removing undefined values and empty objects * * @param {Object} object to minimize * @return {Object} */ function minimize(obj) { var keys = Object.keys(obj); var i = keys.length; var hasKeys; var key; var val; while (i--) { key = keys[i]; val = obj[key]; if (utils.isPOJO(val)) { obj[key] = minimize(val); } if (undefined === obj[key]) { delete obj[key]; continue; } hasKeys = true; } return hasKeys ? obj : undefined; } /*! * Applies virtuals properties to `json`. */ function applyVirtuals(self, json, options, toObjectOptions) { var schema = self.$__schema; var paths = Object.keys(schema.virtuals); var i = paths.length; var numPaths = i; var path; var assignPath; var cur = self._doc; var v; var aliases = typeof (toObjectOptions && toObjectOptions.aliases) === 'boolean' ? toObjectOptions.aliases : true; var virtualsToApply = null; if (Array.isArray(options.virtuals)) { virtualsToApply = new Set(options.virtuals); } else if (options.virtuals && options.virtuals.pathsToSkip) { virtualsToApply = new Set(paths); for (var _i26 = 0; _i26 < options.virtuals.pathsToSkip.length; _i26++) { if (virtualsToApply.has(options.virtuals.pathsToSkip[_i26])) { virtualsToApply["delete"](options.virtuals.pathsToSkip[_i26]); } } } if (!cur) { return json; } options = options || {}; for (i = 0; i < numPaths; ++i) { path = paths[i]; if (virtualsToApply != null && !virtualsToApply.has(path)) { continue; } // Allow skipping aliases with `toObject({ virtuals: true, aliases: false })` if (!aliases && schema.aliases.hasOwnProperty(path)) { continue; } // 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.substring(options.path.length + 1); } var parts = assignPath.split('.'); v = clone(self.get(path), options); if (v === void 0) { continue; } var plen = parts.length; cur = json; for (var j = 0; j < plen - 1; ++j) { cur[parts[j]] = cur[parts[j]] || {}; cur = cur[parts[j]]; } cur[parts[plen - 1]] = v; } return json; } /*! * Applies virtuals properties to `json`. * * @param {Document} self * @param {Object} json * @return {Object} `json` */ function applyGetters(self, json, options) { var schema = self.$__schema; var paths = Object.keys(schema.paths); var i = paths.length; var path; var cur = self._doc; var v; if (!cur) { return json; } while (i--) { path = paths[i]; var parts = path.split('.'); var plen = parts.length; var last = plen - 1; var branch = json; var part = void 0; cur = self._doc; if (!self.$__isSelected(path)) { continue; } for (var ii = 0; ii < plen; ++ii) { part = parts[ii]; v = cur[part]; if (ii === last) { var 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; } } return json; } /*! * Applies schema type transforms to `json`. * * @param {Document} self * @param {Object} json * @return {Object} `json` */ function applySchemaTypeTransforms(self, json) { var schema = self.$__schema; var paths = Object.keys(schema.paths || {}); var cur = self._doc; if (!cur) { return json; } for (var _i27 = 0, _paths4 = paths; _i27 < _paths4.length; _i27++) { var path = _paths4[_i27]; var schematype = schema.paths[path]; if (typeof schematype.options.transform === 'function') { var val = self.$get(path); if (val === undefined) { continue; } var 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') { var _val2 = self.$get(path); if (_val2 === undefined) { continue; } var vals = [].concat(_val2); var transform = schematype.$embeddedSchemaType.options.transform; for (var _i28 = 0; _i28 < vals.length; ++_i28) { var _transformedValue = transform.call(self, vals[_i28]); vals[_i28] = _transformedValue; throwErrorIfPromise(path, _transformedValue); } json[path] = vals; } } 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.'); } } /*! * ignore */ function omitDeselectedFields(self, json) { var schema = self.$__schema; var paths = Object.keys(schema.paths || {}); var cur = self._doc; if (!cur) { return json; } var selected = self.$__.selected; if (selected === void 0) { selected = {}; queryhelpers.applyPaths(selected, schema); } if (selected == null || Object.keys(selected).length === 0) { return json; } for (var _i29 = 0, _paths5 = paths; _i29 < _paths5.length; _i29++) { var path = _paths5[_i29]; if (selected[path] != null && !selected[path]) { delete json[path]; } } return json; } /** * The return value of this method is used in calls to [`JSON.stringify(doc)`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript#the-tojson-function). * * 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 }); * * There is one difference between `toJSON()` and `toObject()` options. * When you call `toJSON()`, the [`flattenMaps` option](./document.html#document_Document-toObject) defaults to `true`, because `JSON.stringify()` doesn't convert maps to objects by default. * When you call `toObject()`, the `flattenMaps` option is `false` by default. * * See [schema options](/docs/guide.html#toJSON) for more information on setting `toJSON` option defaults. * * @param {Object} options * @param {Boolean} [options.flattenMaps=true] if true, convert Maps to [POJOs](https://masteringjs.io/tutorials/fundamentals/pojo). Useful if you want to `JSON.stringify()` the result. * @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); }; Document.prototype.ownerDocument = function () { return this; }; /** * 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 */ Document.prototype.parent = function () { if (this.$isSubdocument || this.$__.wasPopulated) { return this.$__.parent; } return this; }; /** * 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) { var isPOJO = utils.isPOJO(options); var opts; if (isPOJO) { opts = options; opts.minimize = false; } var ret = this.toObject(opts); 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 + ' }'; } return ret; }; if (inspect.custom) { /*! * Avoid Node deprecation warning DEP0079 */ Document.prototype[inspect.custom] = Document.prototype.inspect; } /** * Helper for console.log * * @api public * @method toString * @memberOf Document * @instance */ Document.prototype.toString = function () { var ret = this.inspect(); if (typeof ret === 'string') { return ret; } return inspect(ret); }; /** * 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; } var tid = this.$__getValue('_id'); var docid = doc.$__ != null ? doc.$__getValue('_id') : doc; if (!tid && !docid) { return deepEqual(this, doc); } return tid && tid.equals ? tid.equals(docid) : tid === docid; }; /** * 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 {string|PopulateOptions} [options.populate=null] Recursively populate paths in the populated documents. See [deep populate docs](/docs/populate.html#deep-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 */ Document.prototype.populate = function populate() { var pop = {}; var args = Array.prototype.slice.call(arguments); var fn; if (args.length !== 0) { if (typeof args[args.length - 1] === 'function') { fn = args.pop(); } // use hash to remove duplicate paths var res = utils.populate.apply(null, args); var _iterator23 = _createForOfIteratorHelper(res), _step23; try { for (_iterator23.s(); !(_step23 = _iterator23.n()).done;) { var populateOptions = _step23.value; pop[populateOptions.path] = populateOptions; } } catch (err) { _iterator23.e(err); } finally { _iterator23.f(); } } var paths = utils.object.vals(pop); var topLevelModel = this.constructor; if (this.$__isNested) { topLevelModel = this.$__[scopeSymbol].constructor; var nestedPath = this.$__.nestedPath; paths.forEach(function (populateOptions) { populateOptions.path = nestedPath + '.' + populateOptions.path; }); } // Use `$session()` by default if the document has an associated session // See gh-6754 if (this.$session() != null) { var session = this.$session(); paths.forEach(function (path) { if (path.options == null) { path.options = { session: session }; return; } if (!('session' in path.options)) { path.options.session = session; } }); } paths.forEach(function (p) { p._localModel = topLevelModel; }); return topLevelModel.populate(this, paths, fn); }; /** * 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 * @method $getPopulatedDocs * @instance */ Document.prototype.$getPopulatedDocs = function $getPopulatedDocs() { var keys = []; if (this.$__.populated != null) { keys = keys.concat(Object.keys(this.$__.populated)); } var result = []; var _iterator24 = _createForOfIteratorHelper(keys), _step24; try { for (_iterator24.s(); !(_step24 = _iterator24.n()).done;) { var key = _step24.value; var value = this.$get(key); if (Array.isArray(value)) { result = result.concat(value); } else if (value instanceof Document) { result.push(value); } } } catch (err) { _iterator24.e(err); } finally { _iterator24.f(); } return result; }; /** * Gets _id(s) used during population of the given `path`. * * #### Example: * * const doc = await Model.findOne().populate('author'); * * 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 (typeof path !== 'string') { return undefined; } // Map paths can be populated with either `path.$*` or just `path` var _path = path.endsWith('.$*') ? path.replace(/\.\$\*$/, '') : path; var 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) var pieces = path.split('.'); for (var _i30 = 0; _i30 < pieces.length - 1; ++_i30) { var subpath = pieces.slice(0, _i30 + 1).join('.'); var subdoc = this.$get(subpath); if (subdoc != null && subdoc.$__ != null && this.$populated(subpath)) { var rest = pieces.slice(_i30 + 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; } } return val; }; Document.prototype.$populated = Document.prototype.populated; /** * Throws an error if a given path is not populated * * #### Example: * * const doc = await Model.findOne().populate('author'); * * doc.$assertPopulated('author'); // does not throw * doc.$assertPopulated('other path'); // throws an error * * * @param {String|Array} path * @return {Document} this * @memberOf Document * @method $assertPopulated * @instance * @api public */ Document.prototype.$assertPopulated = function $assertPopulated(paths) { var _this13 = this; if (Array.isArray(paths)) { paths.forEach(function (path) { return _this13.$assertPopulated(path); }); return this; } if (!this.$populated(paths)) { throw new MongooseError("Expected path \"".concat(paths, "\" to be populated")); } return this; }; /** * 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.indexOf(' ') === -1 ? [path] : path.split(' '); } var populatedIds; var virtualKeys = this.$$populatedVirtuals ? Object.keys(this.$$populatedVirtuals) : []; var populated = this.$__ && this.$__.populated || {}; if (arguments.length === 0) { // Depopulate all var _iterator25 = _createForOfIteratorHelper(virtualKeys), _step25; try { for (_iterator25.s(); !(_step25 = _iterator25.n()).done;) { var virtualKey = _step25.value; delete this.$$populatedVirtuals[virtualKey]; delete this._doc[virtualKey]; delete populated[virtualKey]; } } catch (err) { _iterator25.e(err); } finally { _iterator25.f(); } var keys = Object.keys(populated); for (var _i31 = 0, _keys8 = keys; _i31 < _keys8.length; _i31++) { var key = _keys8[_i31]; populatedIds = this.$populated(key); if (!populatedIds) { continue; } delete populated[key]; utils.setValue(key, populatedIds, this._doc); } return this; } var _iterator26 = _createForOfIteratorHelper(path), _step26; try { for (_iterator26.s(); !(_step26 = _iterator26.n()).done;) { var singlePath = _step26.value; populatedIds = this.$populated(singlePath); delete populated[singlePath]; if (virtualKeys.indexOf(singlePath) !== -1) { delete this.$$populatedVirtuals[singlePath]; delete this._doc[singlePath]; } else if (populatedIds) { utils.setValue(singlePath, populatedIds, this._doc); } } } catch (err) { _iterator26.e(err); } finally { _iterator26.f(); } return this; }; /** * 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 || ''; }; /** * 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 () { var delta = this.$__delta(); var changes = delta ? delta[1] : {}; return changes; }; /*! * Module exports. */ Document.ValidationError = ValidationError; module.exports = exports = Document; /***/ }), /***/ 4304: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* eslint-env browser */ /*! * Module dependencies. */ var Document = __webpack_require__(8727); var BrowserDocument = __webpack_require__(3434); var isBrowser = false; /** * Returns the Document constructor for the current context * * @api private */ module.exports = function () { if (isBrowser) { return BrowserDocument; } return Document; }; /*! * ignore */ module.exports.setBrowser = function (flag) { isBrowser = flag; }; /***/ }), /***/ 9906: /***/ ((module) => { "use strict"; /*! * ignore */ var driver = null; module.exports.get = function () { return driver; }; module.exports.set = function (v) { driver = v; }; /***/ }), /***/ 5427: /***/ ((module) => { "use strict"; /*! * ignore */ module.exports = function () {}; /***/ }), /***/ 655: /***/ ((module, exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ var Binary = (__webpack_require__(3873)/* .Binary */ .Kb); /*! * Module exports. */ module.exports = exports = Binary; /***/ }), /***/ 4267: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * ignore */ module.exports = __webpack_require__(3873).Decimal128; /***/ }), /***/ 6333: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /*! * Module exports. */ exports.Binary = __webpack_require__(655); exports.Collection = function () { throw new Error('Cannot create a collection from browser library'); }; exports.getConnection = function () { return function () { throw new Error('Cannot create a connection from browser library'); }; }; exports.Decimal128 = __webpack_require__(4267); exports.ObjectId = __webpack_require__(7906); exports.ReadPreference = __webpack_require__(5427); /***/ }), /***/ 7906: /***/ ((module, exports, __webpack_require__) => { "use strict"; /*! * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId * @constructor NodeMongoDbObjectId * @see ObjectId */ var ObjectId = (__webpack_require__(3873)/* .ObjectID */ .t4); /*! * Getter for convenience with populate, see gh-6115 */ Object.defineProperty(ObjectId.prototype, '_id', { enumerable: false, configurable: true, get: function get() { return this; } }); /*! * ignore */ module.exports = exports = ObjectId; /***/ }), /***/ 1795: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseError = __webpack_require__(5202); var util = __webpack_require__(161); /** * Casting Error constructor. * * @param {String} type * @param {String} value * @inherits MongooseError * @api private */ var CastError = /*#__PURE__*/function (_MongooseError) { _inherits(CastError, _MongooseError); var _super = _createSuper(CastError); function CastError(type, value, path, reason, schemaType) { var _this; _classCallCheck(this, CastError); // If no args, assume we'll `init()` later. if (arguments.length > 0) { var stringValue = getStringValue(value); var valueType = getValueType(value); var messageFormat = getMessageFormat(schemaType); var msg = formatMessage(null, type, stringValue, path, messageFormat, valueType, reason); _this = _super.call(this, msg); _this.init(type, value, path, reason, schemaType); } else { _this = _super.call(this, formatMessage()); } return _possibleConstructorReturn(_this); } _createClass(CastError, [{ key: "toJSON", value: function 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 */ }, { key: "init", value: function 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 */ }, { key: "copy", value: function 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 */ }, { key: "setModel", value: function setModel(model) { this.model = model; this.message = formatMessage(model, this.kind, this.stringValue, this.path, this.messageFormat, this.valueType); } }]); return CastError; }(MongooseError); Object.defineProperty(CastError.prototype, 'name', { value: 'CastError' }); function getStringValue(value) { var stringValue = util.inspect(value); stringValue = stringValue.replace(/^'|'$/g, '"'); if (!stringValue.startsWith('"')) { stringValue = '"' + stringValue + '"'; } return stringValue; } function getValueType(value) { if (value == null) { return '' + value; } var t = _typeof(value); if (t !== 'object') { return t; } if (typeof value.constructor !== 'function') { return t; } return value.constructor.name; } function getMessageFormat(schemaType) { var messageFormat = schemaType && schemaType.options && schemaType.options.cast || null; if (typeof messageFormat === 'string') { return messageFormat; } } /*! * ignore */ function formatMessage(model, kind, stringValue, path, messageFormat, valueType, reason) { if (messageFormat != null) { var ret = messageFormat.replace('{KIND}', kind).replace('{VALUE}', stringValue).replace('{PATH}', path); if (model != null) { ret = ret.replace('{MODEL}', model.modelName); } return ret; } else { var valueTypeMsg = valueType ? ' (type ' + valueType + ')' : ''; var _ret = 'Cast to ' + kind + ' failed for value ' + stringValue + valueTypeMsg + ' at path "' + path + '"'; if (model != null) { _ret += ' for model "' + model.modelName + '"'; } if (reason != null && typeof reason.constructor === 'function' && reason.constructor.name !== 'AssertionError' && reason.constructor.name !== 'Error') { _ret += ' because of "' + reason.constructor.name + '"'; } return _ret; } } /*! * exports */ module.exports = CastError; /***/ }), /***/ 6067: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseError = __webpack_require__(4888); var DivergentArrayError = /*#__PURE__*/function (_MongooseError) { _inherits(DivergentArrayError, _MongooseError); var _super = _createSuper(DivergentArrayError); /*! * DivergentArrayError constructor. * @param {Array} paths */ function DivergentArrayError(paths) { _classCallCheck(this, DivergentArrayError); var 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 return _super.call(this, msg); } return _createClass(DivergentArrayError); }(MongooseError); Object.defineProperty(DivergentArrayError.prototype, 'name', { value: 'DivergentArrayError' }); /*! * exports */ module.exports = DivergentArrayError; /***/ }), /***/ 4888: /***/ ((module, exports, __webpack_require__) => { "use strict"; /** * MongooseError constructor. MongooseError is the base class for all * Mongoose-specific errors. * * #### Example: * const Model = mongoose.model('Test', new mongoose.Schema({ answer: Number })); * const doc = new Model({ answer: 'not a number' }); * const err = doc.validateSync(); * * err instanceof mongoose.Error.ValidationError; // true * * @constructor Error * @param {String} msg Error message * @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error */ var MongooseError = __webpack_require__(5202); /** * 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 = __webpack_require__(983); // 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 = __webpack_require__(3640); /** * An instance of this error class will be returned when mongoose failed to * cast a value. * * @api public * @memberOf Error * @static CastError */ MongooseError.CastError = __webpack_require__(1795); /** * 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 = __webpack_require__(122); /** * 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 = __webpack_require__(2037); /** * 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 = __webpack_require__(8809); /** * 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 = __webpack_require__(5007); /** * 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 = __webpack_require__(5676); /** * Thrown when you try to access a model that has not been registered yet * * @api public * @memberOf Error * @static MissingSchemaError */ MongooseError.MissingSchemaError = __webpack_require__(1511); /** * Thrown when the MongoDB Node driver can't connect to a valid server * to send an operation to. * * @api public * @memberOf Error * @static MongooseServerSelectionError */ MongooseError.MongooseServerSelectionError = __webpack_require__(1870); /** * 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 = __webpack_require__(6067); /** * 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 = __webpack_require__(3328); /***/ }), /***/ 983: /***/ ((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 */ var 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}).'; /***/ }), /***/ 1511: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseError = __webpack_require__(4888); var MissingSchemaError = /*#__PURE__*/function (_MongooseError) { _inherits(MissingSchemaError, _MongooseError); var _super = _createSuper(MissingSchemaError); /*! * MissingSchema Error constructor. * @param {String} name */ function MissingSchemaError(name) { _classCallCheck(this, MissingSchemaError); var msg = 'Schema hasn\'t been registered for model "' + name + '".\n' + 'Use mongoose.model(name, schema)'; return _super.call(this, msg); } return _createClass(MissingSchemaError); }(MongooseError); Object.defineProperty(MissingSchemaError.prototype, 'name', { value: 'MissingSchemaError' }); /*! * exports */ module.exports = MissingSchemaError; /***/ }), /***/ 5202: /***/ ((module) => { "use strict"; /*! * ignore */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseError = /*#__PURE__*/function (_Error) { _inherits(MongooseError, _Error); var _super = _createSuper(MongooseError); function MongooseError() { _classCallCheck(this, MongooseError); return _super.apply(this, arguments); } return _createClass(MongooseError); }( /*#__PURE__*/_wrapNativeSuper(Error)); Object.defineProperty(MongooseError.prototype, 'name', { value: 'MongooseError' }); module.exports = MongooseError; /***/ }), /***/ 3640: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseError = __webpack_require__(4888); var util = __webpack_require__(161); var DocumentNotFoundError = /*#__PURE__*/function (_MongooseError) { _inherits(DocumentNotFoundError, _MongooseError); var _super = _createSuper(DocumentNotFoundError); /*! * OverwriteModel Error constructor. */ function DocumentNotFoundError(filter, model, numAffected, result) { var _this; _classCallCheck(this, DocumentNotFoundError); var msg; var 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 + '"'; } _this = _super.call(this, msg); _this.result = result; _this.numAffected = numAffected; _this.filter = filter; // Backwards compat _this.query = filter; return _this; } return _createClass(DocumentNotFoundError); }(MongooseError); Object.defineProperty(DocumentNotFoundError.prototype, 'name', { value: 'DocumentNotFoundError' }); /*! * exports */ module.exports = DocumentNotFoundError; /***/ }), /***/ 4107: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseError = __webpack_require__(4888); var ObjectExpectedError = /*#__PURE__*/function (_MongooseError) { _inherits(ObjectExpectedError, _MongooseError); var _super = _createSuper(ObjectExpectedError); /** * Strict mode error constructor * * @param {string} type * @param {string} value * @api private */ function ObjectExpectedError(path, val) { var _this; _classCallCheck(this, ObjectExpectedError); var typeDescription = Array.isArray(val) ? 'array' : 'primitive value'; _this = _super.call(this, 'Tried to set nested object field `' + path + "` to ".concat(typeDescription, " `") + val + '`'); _this.path = path; return _this; } return _createClass(ObjectExpectedError); }(MongooseError); Object.defineProperty(ObjectExpectedError.prototype, 'name', { value: 'ObjectExpectedError' }); module.exports = ObjectExpectedError; /***/ }), /***/ 900: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseError = __webpack_require__(4888); var ObjectParameterError = /*#__PURE__*/function (_MongooseError) { _inherits(ObjectParameterError, _MongooseError); var _super = _createSuper(ObjectParameterError); /** * 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 */ function ObjectParameterError(value, paramName, fnName) { _classCallCheck(this, ObjectParameterError); return _super.call(this, 'Parameter "' + paramName + '" to ' + fnName + '() must be an object, got ' + value.toString()); } return _createClass(ObjectParameterError); }(MongooseError); Object.defineProperty(ObjectParameterError.prototype, 'name', { value: 'ObjectParameterError' }); module.exports = ObjectParameterError; /***/ }), /***/ 5676: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseError = __webpack_require__(4888); var OverwriteModelError = /*#__PURE__*/function (_MongooseError) { _inherits(OverwriteModelError, _MongooseError); var _super = _createSuper(OverwriteModelError); /*! * OverwriteModel Error constructor. * @param {String} name */ function OverwriteModelError(name) { _classCallCheck(this, OverwriteModelError); return _super.call(this, 'Cannot overwrite `' + name + '` model once compiled.'); } return _createClass(OverwriteModelError); }(MongooseError); Object.defineProperty(OverwriteModelError.prototype, 'name', { value: 'OverwriteModelError' }); /*! * exports */ module.exports = OverwriteModelError; /***/ }), /***/ 5007: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseError = __webpack_require__(4888); var ParallelSaveError = /*#__PURE__*/function (_MongooseError) { _inherits(ParallelSaveError, _MongooseError); var _super = _createSuper(ParallelSaveError); /** * ParallelSave Error constructor. * * @param {Document} doc * @api private */ function ParallelSaveError(doc) { _classCallCheck(this, ParallelSaveError); var msg = 'Can\'t save() the same doc multiple times in parallel. Document: '; return _super.call(this, msg + doc._id); } return _createClass(ParallelSaveError); }(MongooseError); Object.defineProperty(ParallelSaveError.prototype, 'name', { value: 'ParallelSaveError' }); /*! * exports */ module.exports = ParallelSaveError; /***/ }), /***/ 7962: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseError = __webpack_require__(5202); var ParallelValidateError = /*#__PURE__*/function (_MongooseError) { _inherits(ParallelValidateError, _MongooseError); var _super = _createSuper(ParallelValidateError); /** * ParallelValidate Error constructor. * * @param {Document} doc * @api private */ function ParallelValidateError(doc) { _classCallCheck(this, ParallelValidateError); var msg = 'Can\'t validate() the same doc multiple times in parallel. Document: '; return _super.call(this, msg + doc._id); } return _createClass(ParallelValidateError); }(MongooseError); Object.defineProperty(ParallelValidateError.prototype, 'name', { value: 'ParallelValidateError' }); /*! * exports */ module.exports = ParallelValidateError; /***/ }), /***/ 1870: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseError = __webpack_require__(5202); var allServersUnknown = __webpack_require__(5285); var isAtlas = __webpack_require__(2082); var isSSLError = __webpack_require__(3871); /*! * ignore */ var 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/'; var 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'; var MongooseServerSelectionError = /*#__PURE__*/function (_MongooseError) { _inherits(MongooseServerSelectionError, _MongooseError); var _super = _createSuper(MongooseServerSelectionError); function MongooseServerSelectionError() { _classCallCheck(this, MongooseServerSelectionError); return _super.apply(this, arguments); } _createClass(MongooseServerSelectionError, [{ key: "assimilateError", value: /** * MongooseServerSelectionError constructor * * @api private */ function assimilateError(err) { var reason = err.reason; // Special message for a case that is likely due to IP whitelisting issues. var 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 (var key in err) { if (key !== 'name') { this[key] = err[key]; } } return this; } }]); return MongooseServerSelectionError; }(MongooseError); Object.defineProperty(MongooseServerSelectionError.prototype, 'name', { value: 'MongooseServerSelectionError' }); module.exports = MongooseServerSelectionError; /***/ }), /***/ 3328: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseError = __webpack_require__(4888); var StrictModeError = /*#__PURE__*/function (_MongooseError) { _inherits(StrictModeError, _MongooseError); var _super = _createSuper(StrictModeError); /** * Strict mode error constructor * * @param {String} path * @param {String} [msg] * @param {Boolean} [immutable] * @inherits MongooseError * @api private */ function StrictModeError(path, msg, immutable) { var _this; _classCallCheck(this, StrictModeError); msg = msg || 'Field `' + path + '` is not in schema and strict ' + 'mode is set to throw.'; _this = _super.call(this, msg); _this.isImmutableError = !!immutable; _this.path = path; return _this; } return _createClass(StrictModeError); }(MongooseError); Object.defineProperty(StrictModeError.prototype, 'name', { value: 'StrictModeError' }); module.exports = StrictModeError; /***/ }), /***/ 122: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module requirements */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseError = __webpack_require__(5202); var getConstructorName = __webpack_require__(1981); var util = __webpack_require__(161); var ValidationError = /*#__PURE__*/function (_MongooseError) { _inherits(ValidationError, _MongooseError); var _super = _createSuper(ValidationError); /** * Document Validation Error * * @api private * @param {Document} [instance] * @inherits MongooseError */ function ValidationError(instance) { var _this; _classCallCheck(this, ValidationError); var _message; if (getConstructorName(instance) === 'model') { _message = instance.constructor.modelName + ' validation failed'; } else { _message = 'Validation failed'; } _this = _super.call(this, _message); _this.errors = {}; _this._message = _message; if (instance) { instance.$errors = _this.errors; } return _this; } /** * Console.log helper */ _createClass(ValidationError, [{ key: "toString", value: function toString() { return this.name + ': ' + _generateMessage(this); } /*! * inspect helper */ }, { key: "inspect", value: function inspect() { return Object.assign(new Error(this.message), this); } /*! * add message */ }, { key: "addError", value: function addError(path, error) { this.errors[path] = error; this.message = this._message + ': ' + _generateMessage(this); } }]); return ValidationError; }(MongooseError); if (util.inspect.custom) { /*! * Avoid Node deprecation warning DEP0079 */ ValidationError.prototype[util.inspect.custom] = ValidationError.prototype.inspect; } /*! * 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 value() { return Object.assign({}, this, { name: this.name, message: this.message }); } }); Object.defineProperty(ValidationError.prototype, 'name', { value: 'ValidationError' }); /*! * ignore */ function _generateMessage(err) { var keys = Object.keys(err.errors || {}); var len = keys.length; var msgs = []; var key; for (var i = 0; i < len; ++i) { key = keys[i]; if (err === err.errors[key]) { continue; } msgs.push(key + ': ' + err.errors[key].message); } return msgs.join(', '); } /*! * Module exports */ module.exports = ValidationError; /***/ }), /***/ 2037: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseError = __webpack_require__(4888); var ValidatorError = /*#__PURE__*/function (_MongooseError) { _inherits(ValidatorError, _MongooseError); var _super = _createSuper(ValidatorError); /** * Schema validator error * * @param {Object} properties * @api private */ function ValidatorError(properties) { var _this; _classCallCheck(this, ValidatorError); var msg = properties.message; if (!msg) { msg = MongooseError.messages.general["default"]; } var message = formatMessage(msg, properties); _this = _super.call(this, message); 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; return _this; } /*! * toString helper * TODO remove? This defaults to `${this.name}: ${this.message}` */ _createClass(ValidatorError, [{ key: "toString", value: function toString() { return this.message; } /*! * Ensure `name` and `message` show up in toJSON output re: gh-9296 */ }, { key: "toJSON", value: function toJSON() { return Object.assign({ name: this.name, message: this.message }, this); } }]); return ValidatorError; }(MongooseError); Object.defineProperty(ValidatorError.prototype, 'name', { value: 'ValidatorError' }); /*! * 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; /*! * Formats error messages */ function formatMessage(msg, properties) { if (typeof msg === 'function') { return msg(properties); } var propertyNames = Object.keys(properties); for (var _i = 0, _propertyNames = propertyNames; _i < _propertyNames.length; _i++) { var propertyName = _propertyNames[_i]; if (propertyName === 'message') { continue; } msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]); } return msg; } /*! * exports */ module.exports = ValidatorError; /***/ }), /***/ 8809: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseError = __webpack_require__(4888); var VersionError = /*#__PURE__*/function (_MongooseError) { _inherits(VersionError, _MongooseError); var _super = _createSuper(VersionError); /** * Version Error constructor. * * @param {Document} doc * @param {Number} currentVersion * @param {Array} modifiedPaths * @api private */ function VersionError(doc, currentVersion, modifiedPaths) { var _this; _classCallCheck(this, VersionError); var modifiedPathsStr = modifiedPaths.join(', '); _this = _super.call(this, 'No matching document found for id "' + doc._id + '" version ' + currentVersion + ' modifiedPaths "' + modifiedPathsStr + '"'); _this.version = currentVersion; _this.modifiedPaths = modifiedPaths; return _this; } return _createClass(VersionError); }(MongooseError); Object.defineProperty(VersionError.prototype, 'name', { value: 'VersionError' }); /*! * exports */ module.exports = VersionError; /***/ }), /***/ 6069: /***/ ((module) => { "use strict"; module.exports = arrayDepth; 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 }; } var res = arrayDepth(arr[0]); for (var i = 1; i < arr.length; ++i) { var _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; } res.min = res.min + 1; res.max = res.max + 1; return res; } /***/ }), /***/ 1973: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var Decimal = __webpack_require__(5003); var ObjectId = __webpack_require__(6079); var specialProperties = __webpack_require__(2862); var isMongooseObject = __webpack_require__(6584); var getFunctionName = __webpack_require__(6749); var isBsonType = __webpack_require__(1563); var isObject = __webpack_require__(5721); var symbols = __webpack_require__(8770); var trustedSymbol = (__webpack_require__(3636).trustedSymbol); var utils = __webpack_require__(6872); /*! * 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(utils.isMongooseArray(obj) ? obj.__array : 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 }); } var isSingleNested = obj.$isSingleNested; if (utils.isPOJO(obj) && obj.$__ != null && obj._doc != null) { return obj._doc; } var ret; if (options && options.json && typeof obj.toJSON === 'function') { ret = obj.toJSON(options); } else { ret = obj.toObject(options); } if (options && options.minimize && isSingleNested && Object.keys(ret).length === 0) { return undefined; } return ret; } var objConstructor = obj.constructor; if (objConstructor) { switch (getFunctionName(objConstructor)) { case 'Object': return cloneObject(obj, options, isArrayChild); case 'Date': return new objConstructor(+obj); case 'RegExp': return cloneRegExp(obj); default: // ignore break; } } if (isBsonType(obj, 'ObjectID')) { return new ObjectId(obj.id); } if (isBsonType(obj, 'Decimal128')) { if (options && options.flattenDecimals) { return obj.toJSON(); } return Decimal.fromString(obj.toString()); } // object created with Object.create(null) if (!objConstructor && isObject(obj)) { return cloneObject(obj, options, isArrayChild); } if (_typeof(obj) === 'object' && obj[symbols.schemaTypeSymbol]) { return obj.clone(); } // 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; } if (typeof obj.valueOf === 'function') { return obj.valueOf(); } return cloneObject(obj, options, isArrayChild); } module.exports = clone; /*! * ignore */ function cloneObject(obj, options, isArrayChild) { var minimize = options && options.minimize; var omitUndefined = options && options.omitUndefined; var seen = options && options._seen; var ret = {}; var hasKeys; if (seen && seen.has(obj)) { return seen.get(obj); } else if (seen) { seen.set(obj, ret); } if (trustedSymbol in obj) { ret[trustedSymbol] = obj[trustedSymbol]; } var i = 0; var key = ''; var keys = Object.keys(obj); var len = keys.length; for (i = 0; i < len; ++i) { if (specialProperties.has(key = keys[i])) { continue; } // Don't pass `isArrayChild` down var val = clone(obj[key], options, false); if ((minimize === false || omitUndefined) && typeof val === 'undefined') { delete ret[key]; } else if (minimize !== true || typeof val !== 'undefined') { hasKeys || (hasKeys = true); ret[key] = val; } } return minimize && !isArrayChild ? hasKeys && ret : ret; } function cloneArray(arr, options) { var i = 0; var len = arr.length; var ret = new Array(len); for (i = 0; i < len; ++i) { ret[i] = clone(arr[i], options, true); } return ret; } function cloneRegExp(regexp) { var ret = new RegExp(regexp.source, regexp.flags); if (ret.lastIndex !== regexp.lastIndex) { ret.lastIndex = regexp.lastIndex; } return ret; } /***/ }), /***/ 2829: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var __webpack_unused_export__; /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var Binary = (__webpack_require__(9906).get)().Binary; var isBsonType = __webpack_require__(1563); var isMongooseObject = __webpack_require__(6584); exports.x = flatten; __webpack_unused_export__ = modifiedPaths; /*! * ignore */ function flatten(update, path, options, schema) { var keys; if (update && isMongooseObject(update) && !Buffer.isBuffer(update)) { keys = Object.keys(update.toObject({ transform: false, virtuals: false }) || {}); } else { keys = Object.keys(update || {}); } var numKeys = keys.length; var result = {}; path = path ? path + '.' : ''; for (var i = 0; i < numKeys; ++i) { var key = keys[i]; var val = update[key]; result[path + key] = val; // Avoid going into mixed paths if schema is specified var keySchema = schema && schema.path && schema.path(path + key); var isNested = schema && schema.nested && schema.nested[path + key]; if (keySchema && keySchema.instance === 'Mixed') continue; if (shouldFlatten(val)) { if (options && options.skipArrays && Array.isArray(val)) { continue; } var flat = flatten(val, path + key, options, schema); for (var k in flat) { result[k] = flat[k]; } if (Array.isArray(val)) { result[path + key] = val; } } if (isNested) { var paths = Object.keys(schema.paths); for (var _i = 0, _paths = paths; _i < _paths.length; _i++) { var p = _paths[_i]; if (p.startsWith(path + key + '.') && !result.hasOwnProperty(p)) { result[p] = void 0; } } } } return result; } /*! * ignore */ function modifiedPaths(update, path, result) { var keys = Object.keys(update || {}); var numKeys = keys.length; result = result || {}; path = path ? path + '.' : ''; for (var i = 0; i < numKeys; ++i) { var key = keys[i]; var val = update[key]; var _path = path + key; result[_path] = true; if (!Buffer.isBuffer(val) && isMongooseObject(val)) { val = val.toObject({ transform: false, virtuals: false }); } if (shouldFlatten(val)) { modifiedPaths(val, path + key, result); } } return result; } /*! * ignore */ function shouldFlatten(val) { return val && _typeof(val) === 'object' && !(val instanceof Date) && !isBsonType(val, 'ObjectID') && (!Array.isArray(val) || val.length !== 0) && !(val instanceof Buffer) && !isBsonType(val, 'Decimal128') && !(val instanceof Binary); } /***/ }), /***/ 2794: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isBsonType = __webpack_require__(1563); 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 (isBsonType(a, 'ObjectID') && isBsonType(b, 'ObjectID')) { return a.toString() === b.toString(); } return false; }; /***/ }), /***/ 4531: /***/ ((module) => { "use strict"; module.exports = function checkEmbeddedDiscriminatorKeyProjection(userProjection, path, schema, selected, addedPaths) { var userProjectedInPath = Object.keys(userProjection).reduce(function (cur, key) { return cur || key.startsWith(path + '.'); }, false); var _discriminatorKey = path + '.' + schema.options.discriminatorKey; if (!userProjectedInPath && addedPaths.length === 1 && addedPaths[0] === _discriminatorKey) { selected.splice(selected.indexOf(_discriminatorKey), 1); } }; /***/ }), /***/ 8413: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var getDiscriminatorByValue = __webpack_require__(7291); /*! * Find the correct constructor, taking into account discriminators */ module.exports = function getConstructor(Constructor, value) { var discriminatorKey = Constructor.schema.options.discriminatorKey; if (value != null && Constructor.discriminators && value[discriminatorKey] != null) { if (Constructor.discriminators[value[discriminatorKey]]) { Constructor = Constructor.discriminators[value[discriminatorKey]]; } else { var constructorByValue = getDiscriminatorByValue(Constructor.discriminators, value[discriminatorKey]); if (constructorByValue) { Constructor = constructorByValue; } } } return Constructor; }; /***/ }), /***/ 7291: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var areDiscriminatorValuesEqual = __webpack_require__(2794); /*! * returns discriminator by discriminatorMapping.value * * @param {Model} model * @param {string} value */ module.exports = function getDiscriminatorByValue(discriminators, value) { if (discriminators == null) { return null; } for (var _i = 0, _Object$keys = Object.keys(discriminators); _i < _Object$keys.length; _i++) { var name = _Object$keys[_i]; var it = discriminators[name]; if (it.schema && it.schema.discriminatorMapping && areDiscriminatorValuesEqual(it.schema.discriminatorMapping.value, value)) { return it; } } return null; }; /***/ }), /***/ 2392: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var areDiscriminatorValuesEqual = __webpack_require__(2794); /*! * returns discriminator by discriminatorMapping.value * * @param {Schema} schema * @param {string} value */ module.exports = function getSchemaDiscriminatorByValue(schema, value) { if (schema == null || schema.discriminators == null) { return null; } for (var _i = 0, _Object$keys = Object.keys(schema.discriminators); _i < _Object$keys.length; _i++) { var key = _Object$keys[_i]; var discriminatorSchema = schema.discriminators[key]; if (discriminatorSchema.discriminatorMapping == null) { continue; } if (areDiscriminatorValuesEqual(discriminatorSchema.discriminatorMapping.value, value)) { return discriminatorSchema; } } return null; }; /***/ }), /***/ 4134: /***/ ((module) => { "use strict"; /*! * ignore */ module.exports = function cleanModifiedSubpaths(doc, path, options) { options = options || {}; var skipDocArrays = options.skipDocArrays; var deleted = 0; if (!doc) { return deleted; } for (var _i = 0, _Object$keys = Object.keys(doc.$__.activePaths.states.modify); _i < _Object$keys.length; _i++) { var modifiedPath = _Object$keys[_i]; if (skipDocArrays) { var schemaType = doc.$__schema.path(modifiedPath); if (schemaType && schemaType.$isMongooseDocumentArray) { continue; } } if (modifiedPath.startsWith(path + '.')) { delete doc.$__.activePaths.states.modify[modifiedPath]; ++deleted; if (doc.$isSubdocument) { var owner = doc.ownerDocument(); var fullPath = doc.$__fullPath(modifiedPath); delete owner.$__.activePaths.states.modify[fullPath]; } } } return deleted; }; /***/ }), /***/ 8724: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var documentSchemaSymbol = (__webpack_require__(8770).documentSchemaSymbol); var internalToObjectOptions = (__webpack_require__(4962)/* .internalToObjectOptions */ .h); var utils = __webpack_require__(6872); var Document; var getSymbol = (__webpack_require__(8770).getSymbol); var scopeSymbol = (__webpack_require__(8770).scopeSymbol); var isPOJO = utils.isPOJO; /*! * exports */ exports.M = compile; exports.c = defineKey; /*! * Compiles schemas. */ function compile(tree, proto, prefix, options) { Document = Document || __webpack_require__(8727); var typeKey = options.typeKey; for (var _i = 0, _Object$keys = Object.keys(tree); _i < _Object$keys.length; _i++) { var key = _Object$keys[_i]; var limb = tree[key]; var hasSubprops = isPOJO(limb) && Object.keys(limb).length > 0 && (!limb[typeKey] || typeKey === 'type' && isPOJO(limb.type) && limb.type.type); var subprops = hasSubprops ? limb : null; defineKey({ prop: key, subprops: subprops, prototype: proto, prefix: prefix, options: options }); } } /*! * Defines the accessor named prop on the incoming prototype. */ function defineKey(_ref) { var prop = _ref.prop, subprops = _ref.subprops, prototype = _ref.prototype, prefix = _ref.prefix, options = _ref.options; Document = Document || __webpack_require__(8727); var path = (prefix ? prefix + '.' : '') + prop; prefix = prefix || ''; if (subprops) { Object.defineProperty(prototype, prop, { enumerable: true, configurable: true, get: function get() { var _this = this; if (!this.$__.getters) { this.$__.getters = {}; } if (!this.$__.getters[path]) { var nested = Object.create(Document.prototype, getOwnPropertyDescriptors(this)); // save scope for nested getters/setters if (!prefix) { nested.$__[scopeSymbol] = this; } nested.$__.nestedPath = path; 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 }); Object.defineProperty(nested, 'toObject', { enumerable: false, configurable: true, writable: false, value: function value() { return utils.clone(_this.get(path, null, { virtuals: this && this.schema && this.schema.options && this.schema.options.toObject && this.schema.options.toObject.virtuals || null })); } }); Object.defineProperty(nested, '$__get', { enumerable: false, configurable: true, writable: false, value: function value() { return _this.get(path, null, { virtuals: this && this.schema && this.schema.options && this.schema.options.toObject && this.schema.options.toObject.virtuals || null }); } }); Object.defineProperty(nested, 'toJSON', { enumerable: false, configurable: true, writable: false, value: function value() { return _this.get(path, null, { virtuals: this && this.schema && this.schema.options && this.schema.options.toJSON && this.schema.options.toJSON.virtuals || null }); } }); Object.defineProperty(nested, '$__isNested', { enumerable: false, configurable: true, writable: false, value: true }); var _isEmptyOptions = Object.freeze({ minimize: true, virtuals: false, getters: false, transform: false }); Object.defineProperty(nested, '$isEmpty', { enumerable: false, configurable: true, writable: false, value: function value() { return Object.keys(this.get(path, null, _isEmptyOptions) || {}).length === 0; } }); Object.defineProperty(nested, '$__parent', { enumerable: false, configurable: true, writable: false, value: this }); compile(subprops, nested, path, options); this.$__.getters[path] = nested; } return this.$__.getters[path]; }, set: function set(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); } var doc = this.$__[scopeSymbol] || this; doc.$set(path, v); } }); } else { Object.defineProperty(prototype, prop, { enumerable: true, configurable: true, get: function get() { return this[getSymbol].call(this.$__[scopeSymbol] || this, path); }, set: function set(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) { var result = {}; Object.getOwnPropertyNames(object).forEach(function (key) { var skip = ['isNew', '$__', '$errors', 'errors', '_doc', '$locals', '$op', '__parentArray', '__index', '$isDocumentArrayElement'].indexOf(key) === -1; if (skip) { return; } result[key] = Object.getOwnPropertyDescriptor(object, key); result[key].enumerable = false; }); return result; } /***/ }), /***/ 111: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var get = __webpack_require__(9981); var getSchemaDiscriminatorByValue = __webpack_require__(2392); /*! * 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 || {}; var typeOnly = options.typeOnly; var parts = path.indexOf('.') === -1 ? [path] : path.split('.'); var schemaType = null; var type = 'adhocOrUndefined'; var schema = getSchemaDiscriminatorByValue(doc.schema, doc.get(doc.schema.options.discriminatorKey)) || doc.schema; for (var i = 0; i < parts.length; ++i) { var 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) { var discriminators = schemaType.schema.discriminators; var discriminatorKey = doc.get(subpath + '.' + get(schemaType, 'schema.options.discriminatorKey')); if (discriminatorKey == null || discriminators[discriminatorKey] == null) { continue; } var 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 : schemaType; }; /***/ }), /***/ 719: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var utils = __webpack_require__(6872); var keysToSkip = new Set(['__index', '__parentArray', '_doc']); /** * 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. */ module.exports = function handleSpreadDoc(v, includeExtraKeys) { if (utils.isPOJO(v) && v.$__ != null && v._doc != null) { if (includeExtraKeys) { var extraKeys = {}; for (var _i = 0, _Object$keys = Object.keys(v); _i < _Object$keys.length; _i++) { var key = _Object$keys[_i]; if (_typeof(key) === 'symbol') { continue; } if (key[0] === '$') { continue; } if (keysToSkip.has(key)) { continue; } extraKeys[key] = v[key]; } return _objectSpread(_objectSpread({}, v._doc), extraKeys); } return v._doc; } return v; }; /***/ }), /***/ 9981: /***/ ((module) => { "use strict"; /*! * Simplified lodash.get to work around the annoying null quirk. See: * https://github.com/lodash/lodash/issues/3659 */ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } module.exports = function get(obj, path, def) { var parts; var isPathArray = false; if (typeof path === 'string') { if (path.indexOf('.') === -1) { var _v = getProperty(obj, path); if (_v == null) { return def; } return _v; } parts = path.split('.'); } else { isPathArray = true; parts = path; if (parts.length === 1) { var _v2 = getProperty(obj, parts[0]); if (_v2 == null) { return def; } return _v2; } } var rest = path; var cur = obj; var _iterator = _createForOfIteratorHelper(parts), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var part = _step.value; 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]; } cur = getProperty(cur, part); if (!isPathArray) { rest = rest.substr(part.length + 1); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return cur == null ? def : cur; }; function getProperty(obj, prop) { if (obj == null) { return obj; } if (obj instanceof Map) { return obj.get(prop); } return obj[prop]; } /***/ }), /***/ 1981: /***/ ((module) => { "use strict"; /*! * If `val` is an object, returns constructor name, if possible. Otherwise returns undefined. */ module.exports = function getConstructorName(val) { if (val == null) { return void 0; } if (typeof val.constructor !== 'function') { return void 0; } return val.constructor.name; }; /***/ }), /***/ 6749: /***/ ((module) => { "use strict"; var functionNameRE = /^function\s*([^\s(]+)/; module.exports = function (fn) { return fn.name || (fn.toString().trim().match(functionNameRE) || [])[1]; }; /***/ }), /***/ 1490: /***/ ((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 */ var nextTick = typeof ({env:{}}) !== 'undefined' && typeof ({env:{}}).nextTick === 'function' ? ({env:{}}).nextTick.bind(({env:{}})) : function (cb) { return setTimeout(cb, 0); }; // Fallback for browser build module.exports = function immediate(cb) { return nextTick(cb); }; /***/ }), /***/ 1605: /***/ ((module) => { "use strict"; module.exports = function decorateDiscriminatorIndexOptions(schema, indexOptions) { // If the model is a discriminator and has an index, add a // partialFilterExpression by default so the index will only apply // to that discriminator. var discriminatorName = schema.discriminatorMapping && schema.discriminatorMapping.value; if (discriminatorName && !('sparse' in indexOptions)) { var discriminatorKey = schema.options.discriminatorKey; indexOptions.partialFilterExpression = indexOptions.partialFilterExpression || {}; indexOptions.partialFilterExpression[discriminatorKey] = discriminatorName; } return indexOptions; }; /***/ }), /***/ 8857: /***/ ((module) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } var asyncFunctionPrototype = null; // try/catch for Babel compatibility, because Babel preset-env requires // regenerator-runtime for async/await and we don't want to include that // for a simple check. try { asyncFunctionPrototype = Object.getPrototypeOf( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: case "end": return _context.stop(); } } }, _callee); }))); } catch (err) {} if (asyncFunctionPrototype == null) { module.exports = function isAsyncFunction() { return false; }; } else { module.exports = function isAsyncFunction(v) { return typeof v === 'function' && Object.getPrototypeOf(v) === asyncFunctionPrototype; }; } /***/ }), /***/ 1563: /***/ ((module) => { "use strict"; /*! * Get the bson type, if it exists */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function isBsonType(obj, typename) { return _typeof(obj) === 'object' && obj !== null && obj._bsontype === typename; } module.exports = isBsonType; /***/ }), /***/ 6584: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isMongooseArray = (__webpack_require__(7339).isMongooseArray); /*! * 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 */ module.exports = function (v) { return v != null && (isMongooseArray(v) || // Array or Document Array v.$__ != null || // Document v.isMongooseBuffer || // Buffer v.$isMongooseMap // Map ); }; /***/ }), /***/ 5721: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; /*! * Determines if `arg` is an object. * * @param {Object|Array|String|Function|RegExp|any} arg * @api private * @return {Boolean} */ module.exports = function (arg) { return Buffer.isBuffer(arg) || Object.prototype.toString.call(arg) === '[object Object]'; }; /***/ }), /***/ 5543: /***/ ((module) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function isPromise(val) { return !!val && (_typeof(val) === 'object' || typeof val === 'function') && typeof val.then === 'function'; } module.exports = isPromise; /***/ }), /***/ 9130: /***/ ((module) => { "use strict"; /*! * Determines if `arg` is a flat object. * * @param {Object|Array|String|Function|RegExp|any} arg * @api private * @return {Boolean} */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } module.exports = function isSimpleValidator(obj) { var keys = Object.keys(obj); var result = true; for (var i = 0, len = keys.length; i < len; ++i) { if (_typeof(obj[keys[i]]) === 'object' && obj[keys[i]] !== null) { result = false; break; } } return result; }; /***/ }), /***/ 8859: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var symbols = __webpack_require__(8107); var promiseOrCallback = __webpack_require__(8486); /*! * ignore */ module.exports = applyHooks; /*! * ignore */ applyHooks.middlewareFunctions = ['deleteOne', 'save', 'validate', 'remove', 'updateOne', 'init']; /*! * Register hooks for this model * * @param {Model} model * @param {Schema} schema */ function applyHooks(model, schema, options) { options = options || {}; var kareemOptions = { useErrorHandlers: true, numCallbackParams: 1, nullResultByDefault: true, contextParameter: true }; var objToDecorate = options.decorateDoc ? model : model.prototype; model.$appliedHooks = true; for (var _i = 0, _Object$keys = Object.keys(schema.paths); _i < _Object$keys.length; _i++) { var key = _Object$keys[_i]; var type = schema.paths[key]; var childModel = null; if (type.$isSingleNested) { childModel = type.caster; } else if (type.$isMongooseDocumentArray) { childModel = type.Constructor; } else { continue; } if (childModel.$appliedHooks) { continue; } applyHooks(childModel, type.schema, options); if (childModel.discriminators != null) { var keys = Object.keys(childModel.discriminators); for (var _i2 = 0, _keys = keys; _i2 < _keys.length; _i2++) { var _key = _keys[_i2]; 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. var middleware = schema.s.hooks.filter(function (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(function (hook) { // If user has overwritten the method, don't apply built-in middleware if (schema.methods[hook.name]) { return !hook.fn[symbols.builtInMiddleware]; } return true; }); model._middleware = middleware; objToDecorate.$__originalValidate = objToDecorate.$__originalValidate || objToDecorate.$__validate; for (var _i3 = 0, _arr = ['save', 'validate', 'remove', 'deleteOne']; _i3 < _arr.length; _i3++) { var method = _arr[_i3]; var toWrap = method === 'validate' ? '$__originalValidate' : "$__".concat(method); var wrapped = middleware.createWrapper(method, objToDecorate[toWrap], null, kareemOptions); objToDecorate["$__".concat(method)] = wrapped; } objToDecorate.$__init = middleware.createWrapperSync('init', objToDecorate.$__init, null, kareemOptions); // Support hooks for custom methods var customMethods = Object.keys(schema.methods); var 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 }); var _loop = function _loop() { var method = _customMethods[_i4]; 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. return "continue"; } var originalMethod = objToDecorate[method]; objToDecorate[method] = function () { var _this = this; var args = Array.prototype.slice.call(arguments); var cb = args.slice(-1).pop(); var argsWithoutCallback = typeof cb === 'function' ? args.slice(0, args.length - 1) : args; return promiseOrCallback(cb, function (callback) { return _this["$__".concat(method)].apply(_this, argsWithoutCallback.concat([callback])); }, model.events); }; objToDecorate["$__".concat(method)] = middleware.createWrapper(method, originalMethod, null, customMethodOptions); }; for (var _i4 = 0, _customMethods = customMethods; _i4 < _customMethods.length; _i4++) { var _ret = _loop(); if (_ret === "continue") continue; } } /***/ }), /***/ 9181: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var Mixed = __webpack_require__(3861); var defineKey = (__webpack_require__(8724)/* .defineKey */ .c); var get = __webpack_require__(9981); var utils = __webpack_require__(6872); var CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = { toJSON: true, toObject: true, _id: true, id: true }; /*! * ignore */ module.exports = function discriminator(model, name, schema, tiedValue, applyPlugins) { if (!(schema && schema.instanceOfSchema)) { throw new Error('You must pass a valid discriminator Schema'); } if (model.schema.discriminatorMapping && !model.schema.discriminatorMapping.isRoot) { throw new Error('Discriminator "' + name + '" can only be a discriminator of the root model'); } if (applyPlugins) { var 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 }); } var key = model.schema.options.discriminatorKey; var existingPath = model.schema.path(key); if (existingPath != null) { if (!utils.hasUserDefinedProperty(existingPath.options, 'select')) { existingPath.options.select = true; } existingPath.options.$skipDiscriminatorCheck = true; } else { var 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 }); } if (schema.path(key) && schema.path(key).options.$skipDiscriminatorCheck !== true) { throw new Error('Discriminator "' + name + '" cannot have field with name "' + key + '"'); } var 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'); } // 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 var baseSchemaPaths = Object.keys(baseSchema.paths); var conflictingPaths = []; for (var _i = 0, _baseSchemaPaths = baseSchemaPaths; _i < _baseSchemaPaths.length; _i++) { var path = _baseSchemaPaths[_i]; if (schema.nested[path]) { conflictingPaths.push(path); continue; } if (path.indexOf('.') === -1) { continue; } var sp = path.split('.').slice(0, -1); var cur = ''; var _iterator = _createForOfIteratorHelper(sp), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var piece = _step.value; cur += (cur.length ? '.' : '') + piece; if (schema.paths[cur] instanceof Mixed || schema.singleNestedPaths[cur] instanceof Mixed) { conflictingPaths.push(path); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } utils.merge(schema, baseSchema, { isDiscriminatorSchemaMerge: true, omit: { discriminators: true, base: true, _applyDiscriminators: true }, omitNested: conflictingPaths.reduce(function (cur, path) { cur['tree.' + path] = true; return cur; }, {}) }); // Clean up conflicting paths _after_ merging re: gh-6076 for (var _i2 = 0, _conflictingPaths = conflictingPaths; _i2 < _conflictingPaths.length; _i2++) { var conflictingPath = _conflictingPaths[_i2]; delete schema.paths[conflictingPath]; } // Rebuild schema models because schemas may have been merged re: #7884 schema.childSchemas.forEach(function (obj) { obj.model.prototype.$__setSchema(obj.schema); }); var obj = {}; obj[key] = { "default": value, select: true, set: function set(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 }; if (baseSchema.options.collection) { schema.options.collection = baseSchema.options.collection; } var toJSON = schema.options.toJSON; var toObject = schema.options.toObject; var _id = schema.options._id; var id = schema.options.id; var keys = Object.keys(schema.options); schema.options.discriminatorKey = baseSchema.options.discriminatorKey; for (var _i3 = 0, _keys = keys; _i3 < _keys.length; _i3++) { var _key = _keys[_i3]; 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); 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 } // merges base schema into new discriminator schema and sets new type field. merge(schema, model.schema); if (!model.discriminators) { model.discriminators = {}; } if (!model.schema.discriminatorMapping) { model.schema.discriminatorMapping = { key: key, value: null, isRoot: true }; } if (!model.schema.discriminators) { model.schema.discriminators = {}; } model.schema.discriminators[name] = schema; if (model.discriminators[name] && !schema.options.overwriteModels) { throw new Error('Discriminator with name "' + name + '" already exists'); } return schema; }; /***/ }), /***/ 207: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var MongooseError = __webpack_require__(5202); var setDottedPath = __webpack_require__(2736); var util = __webpack_require__(161); /** * Given an object that may contain dotted paths, flatten the paths out. * For example: `flattenObjectWithDottedPaths({ a: { 'b.c': 42 } })` => `{ a: { b: { c: 42 } } }` */ module.exports = function flattenObjectWithDottedPaths(obj) { if (obj == null || _typeof(obj) !== 'object' || Array.isArray(obj)) { return; } // Avoid Mongoose docs if (obj.$__) { return; } var keys = Object.keys(obj); for (var _i = 0, _keys = keys; _i < _keys.length; _i++) { var key = _keys[_i]; var 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: \"".concat(key, "\", value: ").concat(util.inspect(val))); } continue; } flattenObjectWithDottedPaths(obj[key]); } }; /***/ }), /***/ 251: /***/ ((module) => { "use strict"; var dotRE = /\./g; module.exports = function parentPaths(path) { if (path.indexOf('.') === -1) { return [path]; } var pieces = path.split(dotRE); var len = pieces.length; var ret = new Array(len); var cur = ''; for (var i = 0; i < len; ++i) { cur += cur.length !== 0 ? '.' + pieces[i] : pieces[i]; ret[i] = cur; } return ret; }; /***/ }), /***/ 2736: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var specialProperties = __webpack_require__(2862); module.exports = function setDottedPath(obj, path, val) { if (path.indexOf('.') === -1) { if (specialProperties.has(path)) { return; } obj[path] = val; return; } var parts = path.split('.'); var last = parts.pop(); var cur = obj; var _iterator = _createForOfIteratorHelper(parts), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var part = _step.value; if (specialProperties.has(part)) { continue; } if (cur[part] == null) { cur[part] = {}; } cur = cur[part]; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } if (!specialProperties.has(last)) { cur[last] = val; } }; /***/ }), /***/ 5837: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var utils = __webpack_require__(6872); /*! * 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; } var id = String(doc._id); var _iterator = _createForOfIteratorHelper(populated), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var item = _step.value; if (item.isVirtual) { continue; } var path = item.path; var pieces = path.split('.'); for (var i = 0; i < pieces.length - 1; ++i) { var subpath = pieces.slice(0, i + 1).join('.'); var rest = pieces.slice(i + 1).join('.'); var val = doc.get(subpath); if (val == null) { continue; } if (utils.isMongooseDocumentArray(val)) { for (var j = 0; j < val.length; ++j) { val[j].populated(rest, item._docs[id] == null ? void 0 : item._docs[id][j], item); } break; } } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } }; /***/ }), /***/ 6870: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var MongooseError = __webpack_require__(5202); var util = __webpack_require__(161); module.exports = validateRef; function validateRef(ref, path) { if (typeof ref === 'string') { return; } if (typeof ref === 'function') { return; } throw new MongooseError('Invalid ref at path "' + path + '". Got ' + util.inspect(ref, { depth: 0 })); } /***/ }), /***/ 7427: /***/ ((module) => { "use strict"; /*! * Creates an object that precomputes whether a given path has child fields in * the projection. * * #### Example: * const res = hasIncludedChildren({ 'a.b.c': 0 }); * res.a; // 1 * res['a.b']; // 1 * res['a.b.c']; // 1 * res['a.c']; // undefined */ module.exports = function hasIncludedChildren(fields) { var hasIncludedChildren = {}; var keys = Object.keys(fields); for (var _i = 0, _keys = keys; _i < _keys.length; _i++) { var key = _keys[_i]; if (key.indexOf('.') === -1) { hasIncludedChildren[key] = 1; continue; } var parts = key.split('.'); var c = parts[0]; for (var i = 0; i < parts.length; ++i) { hasIncludedChildren[c] = 1; if (i + 1 < parts.length) { c = c + '.' + parts[i + 1]; } } } return hasIncludedChildren; }; /***/ }), /***/ 2183: /***/ ((module) => { "use strict"; /*! * ignore */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } 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; }; /***/ }), /***/ 9098: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var isDefiningProjection = __webpack_require__(2183); /*! * ignore */ module.exports = function isExclusive(projection) { if (projection == null) { return null; } var keys = Object.keys(projection); var ki = keys.length; var 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` var key = keys[ki]; if (key !== '_id' && isDefiningProjection(projection[key])) { exclude = projection[key] != null && _typeof(projection[key]) === 'object' ? isExclusive(projection[key]) : !projection[key]; break; } } } return exclude; }; /***/ }), /***/ 8486: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var PromiseProvider = __webpack_require__(6755); var immediate = __webpack_require__(1490); var 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(function () { throw error; }); } return; } callback.apply(this, arguments); }); } Promise = Promise || PromiseProvider.get(); return new Promise(function (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); }); }); }; /***/ }), /***/ 5130: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * ignore */ module.exports = applyQueryMiddleware; var validOps = __webpack_require__(9853); /*! * ignore */ applyQueryMiddleware.middlewareFunctions = validOps.concat(['validate']); /*! * Apply query middleware * * @param {Query} query constructor * @param {Model} model */ function applyQueryMiddleware(Query, model) { var kareemOptions = { useErrorHandlers: true, numCallbackParams: 1, nullResultByDefault: true }; var middleware = model.hooks.filter(function (hook) { var 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(function (v) { return v !== 'update' && v !== 'distinct' && v !== 'validate'; }).forEach(function (fn) { Query.prototype["_".concat(fn)] = middleware.createWrapper(fn, Query.prototype["_".concat(fn)], null, kareemOptions); }); } function _getContexts(hook) { var ret = {}; if (hook.hasOwnProperty('query')) { ret.query = hook.query; } if (hook.hasOwnProperty('document')) { ret.document = hook.document; } return ret; } /***/ }), /***/ 9739: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var CastError = __webpack_require__(1795); var StrictModeError = __webpack_require__(3328); var castNumber = __webpack_require__(3065); var booleanComparison = new Set(['$and', '$or']); var comparisonOperator = new Set(['$cmp', '$eq', '$lt', '$lte', '$gt', '$gte']); var arithmeticOperatorArray = new Set([// avoid casting '$add' or '$subtract', because expressions can be either number or date, // and we don't have a good way of inferring which arguments should be numbers and which should // be dates. '$multiply', '$divide', '$log', '$mod', '$trunc', '$avg', '$max', '$min', '$stdDevPop', '$stdDevSamp', '$sum']); var arithmeticOperatorNumber = new Set(['$abs', '$exp', '$ceil', '$floor', '$ln', '$log10', '$round', '$sqrt', '$sin', '$cos', '$tan', '$asin', '$acos', '$atan', '$atan2', '$asinh', '$acosh', '$atanh', '$sinh', '$cosh', '$tanh', '$degreesToRadians', '$radiansToDegrees']); var arrayElementOperators = new Set(['$arrayElemAt', '$first', '$last']); var dateOperators = new Set(['$year', '$month', '$week', '$dayOfMonth', '$dayOfYear', '$hour', '$minute', '$second', '$isoDayOfWeek', '$isoWeekYear', '$isoWeek', '$millisecond']); var expressionOperator = new Set(['$not']); module.exports = function cast$expr(val, schema, strictQuery) { if (_typeof(val) !== 'object' || val === null) { throw new Error('`$expr` must be an object'); } return _castExpression(val, schema, strictQuery); }; function _castExpression(val, schema, strictQuery) { if (isPath(val)) { // Assume path return val; } if (val.$cond != null) { if (Array.isArray(val.$cond)) { val.$cond = val.$cond.map(function (expr) { return _castExpression(expr, schema, strictQuery); }); } else { val.$cond["if"] = _castExpression(val.$cond["if"], schema, strictQuery); val.$cond.then = _castExpression(val.$cond.then, schema, strictQuery); val.$cond["else"] = _castExpression(val.$cond["else"], schema, strictQuery); } } else if (val.$ifNull != null) { val.$ifNull.map(function (v) { return _castExpression(v, schema, strictQuery); }); } else if (val.$switch != null) { val.branches.map(function (v) { return _castExpression(v, schema, strictQuery); }); val["default"] = _castExpression(val["default"], schema, strictQuery); } var keys = Object.keys(val); for (var _i = 0, _keys = keys; _i < _keys.length; _i++) { var key = _keys[_i]; if (booleanComparison.has(key)) { val[key] = val[key].map(function (v) { return _castExpression(v, schema, strictQuery); }); } else if (comparisonOperator.has(key)) { val[key] = castComparison(val[key], schema, strictQuery); } else if (arithmeticOperatorArray.has(key)) { val[key] = castArithmetic(val[key], schema, strictQuery); } else if (arithmeticOperatorNumber.has(key)) { val[key] = castNumberOperator(val[key], schema, strictQuery); } else if (expressionOperator.has(key)) { val[key] = _castExpression(val[key], schema, strictQuery); } } if (val.$in) { val.$in = castIn(val.$in, schema, strictQuery); } if (val.$size) { val.$size = castNumberOperator(val.$size, schema, strictQuery); } _omitUndefined(val); return val; } function _omitUndefined(val) { var keys = Object.keys(val); for (var i = 0, len = keys.length; i < len; ++i) { val[keys[i]] === void 0 && delete val[keys[i]]; } } // { $op: } function castNumberOperator(val) { if (!isLiteral(val)) { return val; } try { return castNumber(val); } catch (err) { throw new CastError('Number', val); } } function castIn(val, schema, strictQuery) { var path = val[1]; if (!isPath(path)) { return val; } var search = val[0]; var schematype = schema.path(path.slice(1)); if (schematype === null) { if (strictQuery === false) { return val; } else if (strictQuery === 'throw') { throw new StrictModeError('$in'); } return void 0; } if (!schematype.$isMongooseArray) { throw new Error('Path must be an array for $in'); } return [schematype.$isMongooseDocumentArray ? schematype.$embeddedSchemaType.cast(search) : schematype.caster.cast(search), path]; } // { $op: [, ] } function castArithmetic(val) { if (!Array.isArray(val)) { if (!isLiteral(val)) { return val; } try { return castNumber(val); } catch (err) { throw new CastError('Number', val); } } return val.map(function (v) { if (!isLiteral(v)) { return v; } try { return castNumber(v); } catch (err) { throw new CastError('Number', v); } }); } // { $op: [expression, expression] } function castComparison(val, schema, strictQuery) { if (!Array.isArray(val) || val.length !== 2) { throw new Error('Comparison operator must be an array of length 2'); } val[0] = _castExpression(val[0], schema, strictQuery); var lhs = val[0]; if (isLiteral(val[1])) { var path = null; var schematype = null; var caster = null; if (isPath(lhs)) { path = lhs.slice(1); schematype = schema.path(path); } else if (_typeof(lhs) === 'object' && lhs != null) { for (var _i2 = 0, _Object$keys = Object.keys(lhs); _i2 < _Object$keys.length; _i2++) { var key = _Object$keys[_i2]; if (dateOperators.has(key) && isPath(lhs[key])) { path = lhs[key].slice(1) + '.' + key; caster = castNumber; } else if (arrayElementOperators.has(key) && isPath(lhs[key])) { path = lhs[key].slice(1) + '.' + key; schematype = schema.path(lhs[key].slice(1)); if (schematype != null) { if (schematype.$isMongooseDocumentArray) { schematype = schematype.$embeddedSchemaType; } else if (schematype.$isMongooseArray) { schematype = schematype.caster; } } } } } var is$literal = _typeof(val[1]) === 'object' && val[1] != null && val[1].$literal != null; if (schematype != null) { if (is$literal) { val[1] = { $literal: schematype.cast(val[1].$literal) }; } else { val[1] = schematype.cast(val[1]); } } else if (caster != null) { if (is$literal) { try { val[1] = { $literal: caster(val[1].$literal) }; } catch (err) { throw new CastError(caster.name.replace(/^cast/, ''), val[1], path + '.$literal'); } } else { try { val[1] = caster(val[1]); } catch (err) { throw new CastError(caster.name.replace(/^cast/, ''), val[1], path); } } } else if (path != null && strictQuery === true) { return void 0; } else if (path != null && strictQuery === 'throw') { throw new StrictModeError(path); } } else { val[1] = _castExpression(val[1]); } return val; } function isPath(val) { return typeof val === 'string' && val[0] === '$'; } function isLiteral(val) { if (typeof val === 'string' && val[0] === '$') { return false; } if (_typeof(val) === 'object' && val !== null && Object.keys(val).find(function (key) { return key[0] === '$'; })) { // The `$literal` expression can make an object a literal // https://docs.mongodb.com/manual/reference/operator/aggregation/literal/#mongodb-expression-exp.-literal return val.$literal != null; } return true; } /***/ }), /***/ 9627: /***/ ((module) => { "use strict"; var specialKeys = new Set(['$ref', '$id', '$db']); module.exports = function isOperator(path) { return path[0] === '$' && !specialKeys.has(path); }; /***/ }), /***/ 3636: /***/ ((__unused_webpack_module, exports) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var trustedSymbol = Symbol('mongoose#trustedSymbol'); exports.trustedSymbol = trustedSymbol; exports.trusted = function trusted(obj) { if (obj == null || _typeof(obj) !== 'object') { return obj; } obj[trustedSymbol] = true; return obj; }; /***/ }), /***/ 9853: /***/ ((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']); /***/ }), /***/ 4133: /***/ ((module) => { "use strict"; module.exports = function addAutoId(schema) { var _obj = { _id: { auto: true } }; _obj._id[schema.options.typeKey] = 'ObjectId'; schema.add(_obj); }; /***/ }), /***/ 7658: /***/ ((module) => { "use strict"; /** * For consistency's sake, we replace positional operator `$` and array filters * `$[]` and `$[foo]` with `0` when looking up schema paths. */ module.exports = function cleanPositionalOperators(path) { return path.replace(/\.\$(\[[^\]]*\])?(?=\.)/g, '.0').replace(/\.\$(\[[^\]]*\])?$/g, '.0'); }; /***/ }), /***/ 5379: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var get = __webpack_require__(9981); var helperIsObject = __webpack_require__(5721); var decorateDiscriminatorIndexOptions = __webpack_require__(1605); /*! * Gather all indexes defined in the schema, including single nested, * document arrays, and embedded discriminators. */ module.exports = function getIndexes(schema) { var indexes = []; var schemaStack = new WeakMap(); var indexTypes = schema.constructor.indexTypes; var 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 || ''; var keys = Object.keys(schema.paths); for (var _i = 0, _keys = keys; _i < _keys.length; _i++) { var key = _keys[_i]; var 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; } 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) { var discriminators = path.schema.discriminators; var discriminatorKeys = Object.keys(discriminators); for (var _i2 = 0, _discriminatorKeys = discriminatorKeys; _i2 < _discriminatorKeys.length; _i2++) { var discriminatorKey = _discriminatorKeys[_i2]; collectIndexes(discriminators[discriminatorKey], prefix + key + '.', path.schema); } } // Retained to minimize risk of backwards breaking changes due to // gh-6113 if (path.$isMongooseDocumentArray) { continue; } } var index = path._index || path.caster && path.caster._index; if (index !== false && index !== null && index !== undefined) { var field = {}; var isObject = helperIsObject(index); var options = isObject ? index : {}; var 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 { var isDescendingIndex = Number(index) === -1; field[prefix + key] = isDescendingIndex ? -1 : 1; } delete options.type; if (!('background' in options)) { options.background = true; } if (schema.options.autoIndex != null) { options._autoIndex = schema.options.autoIndex; } var 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); } } } schemaStack["delete"](schema); if (prefix) { fixSubIndexPaths(schema, prefix); } else { schema._indexes.forEach(function (index) { var options = index[1]; if (!('background' in options)) { options.background = true; } decorateDiscriminatorIndexOptions(schema, options); }); indexes = indexes.concat(schema._indexes); } } /*! * Checks for indexes added to subdocs using Schema.index(). * These indexes need their paths prefixed properly. * * schema._indexes = [ [indexObj, options], [indexObj, options] ..] */ function fixSubIndexPaths(schema, prefix) { var subindexes = schema._indexes; var len = subindexes.length; for (var i = 0; i < len; ++i) { var indexObj = subindexes[i][0]; var indexOptions = subindexes[i][1]; var keys = Object.keys(indexObj); var klen = keys.length; var newindex = {}; // use forward iteration, order matters for (var j = 0; j < klen; ++j) { var key = keys[j]; newindex[prefix + key] = indexObj[key]; } var newIndexOptions = Object.assign({}, indexOptions); if (indexOptions != null && indexOptions.partialFilterExpression != null) { newIndexOptions.partialFilterExpression = {}; var partialFilterExpression = indexOptions.partialFilterExpression; for (var _i3 = 0, _Object$keys = Object.keys(partialFilterExpression); _i3 < _Object$keys.length; _i3++) { var _key = _Object$keys[_i3]; newIndexOptions.partialFilterExpression[prefix + _key] = partialFilterExpression[_key]; } } indexes.push([newindex, newIndexOptions]); } } }; /***/ }), /***/ 37: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var get = __webpack_require__(9981); module.exports = function getKeysInSchemaOrder(schema, val, path) { var schemaKeys = path != null ? Object.keys(get(schema.tree, path, {})) : Object.keys(schema.tree); var valKeys = new Set(Object.keys(val)); var keys; if (valKeys.size > 1) { keys = new Set(); var _iterator = _createForOfIteratorHelper(schemaKeys), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var key = _step.value; if (valKeys.has(key)) { keys.add(key); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } var _iterator2 = _createForOfIteratorHelper(valKeys), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var _key = _step2.value; if (!keys.has(_key)) { keys.add(_key); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } keys = Array.from(keys); } else { keys = Array.from(valKeys); } return keys; }; /***/ }), /***/ 9691: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var addAutoId = __webpack_require__(4133); module.exports = function handleIdOption(schema, options) { if (options == null || options._id == null) { return schema; } schema = schema.clone(); if (!options._id) { schema.remove('_id'); schema.options._id = false; } else if (!schema.paths['_id']) { addAutoId(schema); schema.options._id = true; } return schema; }; /***/ }), /***/ 6370: /***/ ((module) => { "use strict"; module.exports = handleTimestampOption; /*! * ignore */ function handleTimestampOption(arg, prop) { if (arg == null) { return null; } 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]; } /***/ }), /***/ 1879: /***/ ((module) => { "use strict"; /*! * ignore */ module.exports = function addIdGetter(schema) { // ensure the documents receive an id getter unless disabled var autoIdGetter = !schema.paths['id'] && schema.paths['_id'] && schema.options.id; if (!autoIdGetter) { return schema; } schema.virtual('id').get(idGetter); return schema; }; /*! * Returns this documents _id cast to a string. */ function idGetter() { if (this._id != null) { return String(this._id); } return null; } /***/ }), /***/ 4913: /***/ ((module) => { "use strict"; module.exports = function merge(s1, s2, skipConflictingPaths) { var paths = Object.keys(s2.tree); var pathsToAdd = {}; for (var _i = 0, _paths = paths; _i < _paths.length; _i++) { var key = _paths[_i]; if (skipConflictingPaths && (s1.paths[key] || s1.nested[key] || s1.singleNestedPaths[key])) { continue; } pathsToAdd[key] = s2.tree[key]; } s1.add(pathsToAdd); s1.callQueue = s1.callQueue.concat(s2.callQueue); s1.method(s2.methods); s1["static"](s2.statics); for (var query in s2.query) { s1.query[query] = s2.query[query]; } for (var virtual in s2.virtuals) { s1.virtuals[virtual] = s2.virtuals[virtual].clone(); } s1.s.hooks.merge(s2.s.hooks, false); }; /***/ }), /***/ 8828: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var StrictModeError = __webpack_require__(3328); /*! * ignore */ 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(function (fn) { return fn !== schematype.$immutableSetter; }); delete schematype.$immutableSetter; } }; function createImmutableSetter(path, immutable) { return function immutableSetter(v, _priorVal, _doc, options) { if (this == null || this.$__ == null) { return v; } if (this.isNew) { return v; } if (options && options.overwriteImmutable) { return v; } var _immutable = typeof immutable === 'function' ? immutable.call(this, this) : immutable; if (!_immutable) { return v; } var _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); } return _value; }; } /***/ }), /***/ 2862: /***/ ((module) => { "use strict"; module.exports = new Set(['__proto__', 'constructor', 'prototype']); /***/ }), /***/ 8770: /***/ ((__unused_webpack_module, exports) => { "use strict"; 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'); /***/ }), /***/ 3767: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var applyTimestampsToChildren = __webpack_require__(4843); var applyTimestampsToUpdate = __webpack_require__(6434); var get = __webpack_require__(9981); var handleTimestampOption = __webpack_require__(6370); var symbols = __webpack_require__(8107); module.exports = function setupTimestamps(schema, timestamps) { var childHasTimestamp = schema.childSchemas.find(withTimestamp); function withTimestamp(s) { var ts = s.schema.options.timestamps; return !!ts; } if (!timestamps && !childHasTimestamp) { return; } var createdAt = handleTimestampOption(timestamps, 'createdAt'); var updatedAt = handleTimestampOption(timestamps, 'updatedAt'); var currentTime = timestamps != null && timestamps.hasOwnProperty('currentTime') ? timestamps.currentTime : null; var schemaAdditions = {}; schema.$timestamps = { createdAt: createdAt, updatedAt: updatedAt }; if (updatedAt && !schema.paths[updatedAt]) { schemaAdditions[updatedAt] = Date; } if (createdAt && !schema.paths[createdAt]) { var _schemaAdditions$crea; var baseImmutableCreatedAt = schema.base.get('timestamps.createdAt.immutable'); var immutable = baseImmutableCreatedAt != null ? baseImmutableCreatedAt : true; schemaAdditions[createdAt] = (_schemaAdditions$crea = {}, _defineProperty(_schemaAdditions$crea, schema.options.typeKey || 'type', Date), _defineProperty(_schemaAdditions$crea, "immutable", immutable), _schemaAdditions$crea); } schema.add(schemaAdditions); schema.pre('save', function (next) { var timestampOption = get(this, '$__.saveOptions.timestamps'); if (timestampOption === false) { return next(); } var skipUpdatedAt = timestampOption != null && timestampOption.updatedAt === false; var skipCreatedAt = timestampOption != null && timestampOption.createdAt === false; var defaultTimestamp = currentTime != null ? currentTime() : this.ownerDocument().constructor.base.now(); if (!skipCreatedAt && (this.isNew || this.$isSubdocument) && createdAt && !this.$__getValue(createdAt) && this.$__isSelected(createdAt)) { this.$set(createdAt, defaultTimestamp, undefined, { overwriteImmutable: true }); } if (!skipUpdatedAt && updatedAt && (this.isNew || this.$isModified())) { var ts = defaultTimestamp; if (this.isNew && createdAt != null) { ts = this.$__getValue(createdAt); } this.$set(updatedAt, ts); } next(); }); schema.methods.initializeTimestamps = function () { var 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; }; _setTimestampsOnUpdate[symbols.builtInMiddleware] = true; var 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) { var 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(); } }; /***/ }), /***/ 5285: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var getConstructorName = __webpack_require__(1981); module.exports = function allServersUnknown(topologyDescription) { if (getConstructorName(topologyDescription) !== 'TopologyDescription') { return false; } var servers = Array.from(topologyDescription.servers.values()); return servers.length > 0 && servers.every(function (server) { return server.type === 'Unknown'; }); }; /***/ }), /***/ 2082: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var getConstructorName = __webpack_require__(1981); module.exports = function isAtlas(topologyDescription) { if (getConstructorName(topologyDescription) !== 'TopologyDescription') { return false; } var hostnames = Array.from(topologyDescription.servers.keys()); if (hostnames.length === 0) { return false; } for (var i = 0, il = hostnames.length; i < il; ++i) { var url = new URL(hostnames[i]); if (url.hostname.endsWith('.mongodb.net') === false || url.port !== '27017') { return false; } } return true; }; /***/ }), /***/ 3871: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var getConstructorName = __webpack_require__(1981); var nonSSLMessage = 'Client network socket disconnected before secure TLS ' + 'connection was established'; module.exports = function isSSLError(topologyDescription) { if (getConstructorName(topologyDescription) !== 'TopologyDescription') { return false; } var descriptions = Array.from(topologyDescription.servers.values()); return descriptions.length > 0 && descriptions.every(function (descr) { return descr.error && descr.error.message.indexOf(nonSSLMessage) !== -1; }); }; /***/ }), /***/ 4843: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var cleanPositionalOperators = __webpack_require__(7658); var handleTimestampOption = __webpack_require__(6370); module.exports = applyTimestampsToChildren; /*! * ignore */ function applyTimestampsToChildren(now, update, schema) { if (update == null) { return; } var keys = Object.keys(update); var hasDollarKey = keys.some(function (key) { return key[0] === '$'; }); if (hasDollarKey) { if (update.$push) { _applyTimestampToUpdateOperator(update.$push); } if (update.$addToSet) { _applyTimestampToUpdateOperator(update.$addToSet); } if (update.$set != null) { var _keys = Object.keys(update.$set); for (var _i = 0, _keys2 = _keys; _i < _keys2.length; _i++) { var key = _keys2[_i]; applyTimestampsToUpdateKey(schema, key, update.$set, now); } } if (update.$setOnInsert != null) { var _keys3 = Object.keys(update.$setOnInsert); for (var _i2 = 0, _keys4 = _keys3; _i2 < _keys4.length; _i2++) { var _key = _keys4[_i2]; applyTimestampsToUpdateKey(schema, _key, update.$setOnInsert, now); } } } var updateKeys = Object.keys(update).filter(function (key) { return key[0] !== '$'; }); var _iterator = _createForOfIteratorHelper(updateKeys), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _key2 = _step.value; applyTimestampsToUpdateKey(schema, _key2, update, now); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } function _applyTimestampToUpdateOperator(op) { var _loop = function _loop() { var key = _Object$keys[_i3]; var $path = schema.path(key.replace(/\.\$\./i, '.').replace(/.\$$/, '')); if (op[key] && $path && $path.$isMongooseDocumentArray && $path.schema.options.timestamps) { var timestamps = $path.schema.options.timestamps; var createdAt = handleTimestampOption(timestamps, 'createdAt'); var 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; } applyTimestampsToChildren(now, subdoc, $path.schema); }); } else { if (updatedAt != null) { op[key][updatedAt] = now; } if (createdAt != null) { op[key][createdAt] = now; } applyTimestampsToChildren(now, op[key], $path.schema); } } }; for (var _i3 = 0, _Object$keys = Object.keys(op); _i3 < _Object$keys.length; _i3++) { _loop(); } } } function applyTimestampsToDocumentArray(arr, schematype, now) { var timestamps = schematype.schema.options.timestamps; if (!timestamps) { return; } var len = arr.length; var createdAt = handleTimestampOption(timestamps, 'createdAt'); var updatedAt = handleTimestampOption(timestamps, 'updatedAt'); for (var 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); } } function applyTimestampsToSingleNested(subdoc, schematype, now) { var timestamps = schematype.schema.options.timestamps; if (!timestamps) { return; } var createdAt = handleTimestampOption(timestamps, 'createdAt'); var updatedAt = handleTimestampOption(timestamps, 'updatedAt'); if (updatedAt != null) { subdoc[updatedAt] = now; } if (createdAt != null) { subdoc[createdAt] = now; } applyTimestampsToChildren(now, subdoc, schematype.schema); } function applyTimestampsToUpdateKey(schema, key, update, now) { // Replace positional operator `$` and array filters `$[]` and `$[.*]` var keyToSearch = cleanPositionalOperators(key); var path = schema.path(keyToSearch); if (!path) { return; } var parentSchemaTypes = []; var pieces = keyToSearch.split('.'); for (var i = pieces.length - 1; i > 0; --i) { var 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) { var _iterator2 = _createForOfIteratorHelper(parentSchemaTypes), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var item = _step2.value; var parentPath = item.parentPath; var parentSchemaType = item.parentSchemaType; var timestamps = parentSchemaType.schema.options.timestamps; var updatedAt = handleTimestampOption(timestamps, 'updatedAt'); if (!timestamps || updatedAt == null) { continue; } if (parentSchemaType.$isSingleNested) { // Single nested is easy update[parentPath + '.' + updatedAt] = now; } else if (parentSchemaType.$isMongooseDocumentArray) { var childPath = key.substring(parentPath.length + 1); if (/^\d+$/.test(childPath)) { update[parentPath + '.' + childPath][updatedAt] = now; continue; } var firstDot = childPath.indexOf('.'); childPath = firstDot !== -1 ? childPath.substring(0, firstDot) : childPath; update[parentPath + '.' + childPath + '.' + updatedAt] = now; } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } else if (path.schema != null && path.schema != schema && update[key]) { var _timestamps = path.schema.options.timestamps; var createdAt = handleTimestampOption(_timestamps, 'createdAt'); var _updatedAt = handleTimestampOption(_timestamps, 'updatedAt'); if (!_timestamps) { return; } if (_updatedAt != null) { update[key][_updatedAt] = now; } if (createdAt != null) { update[key][createdAt] = now; } } } /***/ }), /***/ 6434: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * ignore */ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var get = __webpack_require__(9981); module.exports = applyTimestampsToUpdate; /*! * ignore */ function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, options) { var updates = currentUpdate; var _updates = updates; var overwrite = get(options, 'overwrite', false); var timestamps = get(options, 'timestamps', true); // Support skipping timestamps at the query level, see gh-6980 if (!timestamps || updates == null) { return currentUpdate; } var skipCreatedAt = timestamps != null && timestamps.createdAt === false; var 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: _defineProperty({}, updatedAt, now) }); return updates; } updates.$set = updates.$set || {}; if (!skipUpdatedAt && updatedAt && (!currentUpdate.$currentDate || !currentUpdate.$currentDate[updatedAt])) { var timestampSet = false; if (updatedAt.indexOf('.') !== -1) { var pieces = updatedAt.split('.'); for (var i = 1; i < pieces.length; ++i) { var remnant = pieces.slice(-i).join('.'); var 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; } } } 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]; } var _timestampSet = false; if (createdAt.indexOf('.') !== -1) { var _pieces = createdAt.split('.'); for (var _i = 1; _i < _pieces.length; ++_i) { var _remnant = _pieces.slice(-_i).join('.'); var _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; } } } if (!_timestampSet) { updates.$setOnInsert = updates.$setOnInsert || {}; updates.$setOnInsert[createdAt] = now; } } if (Object.keys(updates.$set).length === 0) { delete updates.$set; } return updates; } /***/ }), /***/ 6379: /***/ ((module, exports, __webpack_require__) => { "use strict"; /*! * Dependencies */ var StateMachine = __webpack_require__(489); var ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default', 'ignore'); module.exports = exports = InternalCache; function InternalCache() { this.activePaths = new ActiveRoster(); } 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 /** * If `false`, this document was not the result of population. * If `true`, this document is a populated doc underneath another doc * If an object, this document is a populated doc and the `value` property of the * object contains the original depopulated value. */ InternalCache.prototype.wasPopulated = false; InternalCache.prototype.scope = undefined; InternalCache.prototype.session = null; InternalCache.prototype.pathsToScopes = null; InternalCache.prototype.cachedRequired = null; /***/ }), /***/ 4962: /***/ ((__unused_webpack_module, exports) => { "use strict"; /*! * ignore */ exports.h = { transform: false, virtuals: false, getters: false, _skipDepopulateTopLevel: true, depopulate: true, flattenDecimals: false, useProjection: false }; /***/ }), /***/ 4034: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var clone = __webpack_require__(1973); var PopulateOptions = /*#__PURE__*/_createClass(function PopulateOptions(obj) { _classCallCheck(this, PopulateOptions); 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; /***/ }), /***/ 4756: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var SchemaTypeOptions = __webpack_require__(1764); /** * 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 */ var SchemaArrayOptions = /*#__PURE__*/function (_SchemaTypeOptions) { _inherits(SchemaArrayOptions, _SchemaTypeOptions); var _super = _createSuper(SchemaArrayOptions); function SchemaArrayOptions() { _classCallCheck(this, SchemaArrayOptions); return _super.apply(this, arguments); } return _createClass(SchemaArrayOptions); }(SchemaTypeOptions); var opts = __webpack_require__(3439); /** * 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; /***/ }), /***/ 9586: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var SchemaTypeOptions = __webpack_require__(1764); /** * 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 */ var SchemaBufferOptions = /*#__PURE__*/function (_SchemaTypeOptions) { _inherits(SchemaBufferOptions, _SchemaTypeOptions); var _super = _createSuper(SchemaBufferOptions); function SchemaBufferOptions() { _classCallCheck(this, SchemaBufferOptions); return _super.apply(this, arguments); } return _createClass(SchemaBufferOptions); }(SchemaTypeOptions); var opts = __webpack_require__(3439); /** * 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; /***/ }), /***/ 2869: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var SchemaTypeOptions = __webpack_require__(1764); /** * 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 */ var SchemaDateOptions = /*#__PURE__*/function (_SchemaTypeOptions) { _inherits(SchemaDateOptions, _SchemaTypeOptions); var _super = _createSuper(SchemaDateOptions); function SchemaDateOptions() { _classCallCheck(this, SchemaDateOptions); return _super.apply(this, arguments); } return _createClass(SchemaDateOptions); }(SchemaTypeOptions); var opts = __webpack_require__(3439); /** * 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. * * mongo TTL index `expireAfterSeconds` value will take 'expires' value expressed in seconds. * * #### Example: * * const schema = new Schema({ "expireAt": { type: Date, expires: 11 } }); * // if 'expireAt' is set, then document expires at expireAt + 11 seconds * * @api public * @property expires * @memberOf SchemaDateOptions * @type Date * @instance */ Object.defineProperty(SchemaDateOptions.prototype, 'expires', opts); /*! * ignore */ module.exports = SchemaDateOptions; /***/ }), /***/ 887: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var SchemaTypeOptions = __webpack_require__(1764); /** * 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 */ var SchemaDocumentArrayOptions = /*#__PURE__*/function (_SchemaTypeOptions) { _inherits(SchemaDocumentArrayOptions, _SchemaTypeOptions); var _super = _createSuper(SchemaDocumentArrayOptions); function SchemaDocumentArrayOptions() { _classCallCheck(this, SchemaDocumentArrayOptions); return _super.apply(this, arguments); } return _createClass(SchemaDocumentArrayOptions); }(SchemaTypeOptions); var opts = __webpack_require__(3439); /** * 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); /** * 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; /***/ }), /***/ 8227: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var SchemaTypeOptions = __webpack_require__(1764); /** * 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 */ var SchemaMapOptions = /*#__PURE__*/function (_SchemaTypeOptions) { _inherits(SchemaMapOptions, _SchemaTypeOptions); var _super = _createSuper(SchemaMapOptions); function SchemaMapOptions() { _classCallCheck(this, SchemaMapOptions); return _super.apply(this, arguments); } return _createClass(SchemaMapOptions); }(SchemaTypeOptions); var opts = __webpack_require__(3439); /** * 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; /***/ }), /***/ 8491: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var SchemaTypeOptions = __webpack_require__(1764); /** * 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 */ var SchemaNumberOptions = /*#__PURE__*/function (_SchemaTypeOptions) { _inherits(SchemaNumberOptions, _SchemaTypeOptions); var _super = _createSuper(SchemaNumberOptions); function SchemaNumberOptions() { _classCallCheck(this, SchemaNumberOptions); return _super.apply(this, arguments); } return _createClass(SchemaNumberOptions); }(SchemaTypeOptions); var opts = __webpack_require__(3439); /** * 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; /***/ }), /***/ 8172: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var SchemaTypeOptions = __webpack_require__(1764); /** * 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 */ var SchemaObjectIdOptions = /*#__PURE__*/function (_SchemaTypeOptions) { _inherits(SchemaObjectIdOptions, _SchemaTypeOptions); var _super = _createSuper(SchemaObjectIdOptions); function SchemaObjectIdOptions() { _classCallCheck(this, SchemaObjectIdOptions); return _super.apply(this, arguments); } return _createClass(SchemaObjectIdOptions); }(SchemaTypeOptions); var opts = __webpack_require__(3439); /** * 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; /***/ }), /***/ 3209: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var SchemaTypeOptions = __webpack_require__(1764); /** * 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 */ var SchemaStringOptions = /*#__PURE__*/function (_SchemaTypeOptions) { _inherits(SchemaStringOptions, _SchemaTypeOptions); var _super = _createSuper(SchemaStringOptions); function SchemaStringOptions() { _classCallCheck(this, SchemaStringOptions); return _super.apply(this, arguments); } return _createClass(SchemaStringOptions); }(SchemaTypeOptions); var opts = __webpack_require__(3439); /** * 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()`](https://masteringjs.io/tutorials/fundamentals/trim-string). * * @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()`](https://masteringjs.io/tutorials/fundamentals/uppercase). * * @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; /***/ }), /***/ 5446: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var SchemaTypeOptions = __webpack_require__(1764); /** * 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 */ var SchemaSubdocumentOptions = /*#__PURE__*/function (_SchemaTypeOptions) { _inherits(SchemaSubdocumentOptions, _SchemaTypeOptions); var _super = _createSuper(SchemaSubdocumentOptions); function SchemaSubdocumentOptions() { _classCallCheck(this, SchemaSubdocumentOptions); return _super.apply(this, arguments); } return _createClass(SchemaSubdocumentOptions); }(SchemaTypeOptions); var opts = __webpack_require__(3439); /** * 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); module.exports = SchemaSubdocumentOptions; /***/ }), /***/ 1764: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var clone = __webpack_require__(1973); /** * 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 */ var SchemaTypeOptions = /*#__PURE__*/_createClass(function SchemaTypeOptions(obj) { _classCallCheck(this, SchemaTypeOptions); if (obj == null) { return this; } Object.assign(this, clone(obj)); }); var opts = __webpack_require__(3439); /** * 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 * 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); /** * The path in the document that `populate()` should use to find the model * to use. * * @api public * @property ref * @memberOf SchemaTypeOptions * @type Function|String * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'refPath', 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](https://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; /***/ }), /***/ 1902: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var opts = __webpack_require__(3439); var VirtualOptions = /*#__PURE__*/_createClass(function VirtualOptions(obj) { _classCallCheck(this, VirtualOptions); Object.assign(this, obj); if (obj != null && obj.options != null) { this.options = Object.assign({}, obj.options); } }); /** * 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; /***/ }), /***/ 3439: /***/ ((module) => { "use strict"; module.exports = Object.freeze({ enumerable: true, configurable: true, writable: true, value: void 0 }); /***/ }), /***/ 6755: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * ignore */ var assert = __webpack_require__(9373); var mquery = __webpack_require__(5417); /** * Helper for multiplexing promise implementations * * @api private */ var store = { _promise: null }; /** * Get the current promise constructor * * @api private */ store.get = function () { return store._promise; }; /** * Set the current promise constructor * * @api private */ store.set = function (lib) { assert.ok(typeof lib === 'function', "mongoose.Promise must be a function, got ".concat(lib)); store._promise = lib; mquery.Promise = lib; }; /*! * Use native promises by default */ store.set(__webpack_require__.g.Promise); module.exports = store; /***/ }), /***/ 2888: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /*! * Module dependencies */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var checkEmbeddedDiscriminatorKeyProjection = __webpack_require__(4531); var get = __webpack_require__(9981); var getDiscriminatorByValue = __webpack_require__(7291); var isDefiningProjection = __webpack_require__(2183); var clone = __webpack_require__(1973); /*! * Prepare a set of path options for query population. * * @param {Query} query * @param {Object} options * @return {Array} */ exports.preparePopulationOptions = function preparePopulationOptions(query, options) { var _populate = query.options.populate; var pop = Object.keys(_populate).reduce(function (vals, key) { return vals.concat([_populate[key]]); }, []); // lean options should trickle through all queries if (options.lean != null) { pop.filter(function (p) { return (p && p.options && p.options.lean) == null; }).forEach(makeLean(options.lean)); } pop.forEach(function (opts) { opts._localModel = query.model; }); return pop; }; /*! * 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) { var _populate = query._mongooseOptions.populate; var pop = Object.keys(_populate).reduce(function (vals, key) { return vals.concat([_populate[key]]); }, []); // lean options should trickle through all queries if (options.lean != null) { pop.filter(function (p) { return (p && p.options && p.options.lean) == null; }).forEach(makeLean(options.lean)); } var session = query && query.options && query.options.session || null; if (session != null) { pop.forEach(function (path) { if (path.options == null) { path.options = { session: session }; return; } if (!('session' in path.options)) { path.options.session = session; } }); } var projection = query._fieldsForExec(); pop.forEach(function (p) { p._queryProjection = projection; }); pop.forEach(function (opts) { opts._localModel = query.model; }); return pop; }; /*! * 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); var discriminatorMapping = model.schema ? model.schema.discriminatorMapping : null; var key = discriminatorMapping && discriminatorMapping.isRoot ? discriminatorMapping.key : null; var value = doc[key]; if (key && value && model.discriminators) { var discriminator = model.discriminators[value] || getDiscriminatorByValue(model.discriminators, value); if (discriminator) { var _fields = clone(userProvidedFields); exports.applyPaths(_fields, discriminator.schema); return new discriminator(undefined, _fields, true); } } var _opts = { skipId: true, isNew: false, willInit: true }; if (options != null && 'defaults' in options) { _opts.defaults = options.defaults; } return new model(undefined, fields, _opts); }; /*! * ignore */ exports.createModelAndInit = function createModelAndInit(model, doc, fields, userProvidedFields, options, populatedIds, callback) { var initOpts = populatedIds ? { populated: populatedIds } : undefined; var casted = exports.createModel(model, doc, fields, userProvidedFields, options); try { casted.$init(doc, initOpts, callback); } catch (error) { callback(error, casted); } }; /*! * ignore */ exports.applyPaths = function applyPaths(fields, schema) { // determine if query is selecting or excluding fields var exclude; var keys; var keyIndex; if (fields) { keys = Object.keys(fields); keyIndex = keys.length; while (keyIndex--) { if (keys[keyIndex][0] === '+') { continue; } var field = fields[keys[keyIndex]]; // Skip `$meta` and `$slice` if (!isDefiningProjection(field)) { continue; } exclude = !field; break; } } // if selecting, apply default schematype select:true fields // if excluding, apply schematype select:false fields var selected = []; var excluded = []; var stack = []; analyzeSchema(schema); switch (exclude) { case true: var _iterator = _createForOfIteratorHelper(excluded), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var fieldName = _step.value; fields[fieldName] = 0; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } break; case false: if (schema && schema.paths['_id'] && schema.paths['_id'].options && schema.paths['_id'].options.select === false) { fields._id = 0; } var _iterator2 = _createForOfIteratorHelper(selected), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var _fieldName = _step2.value; fields[_fieldName] = fields[_fieldName] || 1; } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } break; case undefined: if (fields == null) { break; } // Any leftover plus paths must in the schema, so delete them (gh-7017) for (var _i = 0, _Object$keys = Object.keys(fields || {}); _i < _Object$keys.length; _i++) { var key = _Object$keys[_i]; if (key.startsWith('+')) { delete fields[key]; } } // user didn't specify fields, implies returning all fields. // only need to apply excluded fields and delete any plus paths var _iterator3 = _createForOfIteratorHelper(excluded), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var _fieldName2 = _step3.value; if (fields[_fieldName2] != null) { // Skip applying default projections to fields with non-defining // projections, like `$slice` continue; } fields[_fieldName2] = 0; } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } break; } function analyzeSchema(schema, prefix) { prefix || (prefix = ''); // avoid recursion if (stack.indexOf(schema) !== -1) { return []; } stack.push(schema); var addedPaths = []; schema.eachPath(function (path, type) { if (prefix) path = prefix + '.' + path; if (type.$isSchemaMap || path.endsWith('.$*')) { return; } var addedPath = analyzePath(path, type); // arrays if (addedPath == null && !Array.isArray(type) && type.$isMongooseArray && !type.$isMongooseDocumentArray) { addedPath = analyzePath(path, type.caster); } if (addedPath != null) { addedPaths.push(addedPath); } // nested schemas if (type.schema) { var _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); } } }); stack.pop(); return addedPaths; } function analyzePath(path, type) { var plusPath = '+' + path; var hasPlusPath = fields && plusPath in fields; if (hasPlusPath) { // forced inclusion delete fields[plusPath]; } if (typeof type.selected !== 'boolean') { return; } // If set to 0, we're explicitly excluding the discriminator key. Can't do this for all fields, // because we have tests that assert that using `-path` to exclude schema-level `select: true` // fields counts as an exclusive projection. See gh-11546 if (exclude && type.selected && path === schema.options.discriminatorKey && fields[path] != null && !fields[path]) { delete fields[path]; return; } if (hasPlusPath) { // forced inclusion delete fields[plusPath]; // 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; } // check for parent exclusions var pieces = path.split('.'); var cur = ''; for (var i = 0; i < pieces.length; ++i) { cur += cur.length ? '.' + pieces[i] : pieces[i]; if (excluded.indexOf(cur) !== -1) { return; } } // 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 && (type && type.options && type.options.$skipDiscriminatorCheck || false)) { var _cur = ''; for (var _i2 = 0; _i2 < pieces.length; ++_i2) { _cur += (_cur.length === 0 ? '' : '.') + pieces[_i2]; var projection = get(fields, _cur, false) || get(fields, _cur + '.$', false); if (projection && _typeof(projection) !== 'object') { return; } } } (type.selected ? selected : excluded).push(path); return path; } }; /*! * 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(function (path) { return typeof path === 'string' && path.startsWith(option.path + '.'); }).map(function (path) { return path.slice(option.path.length + 1); }); } option.options.lean = val; }; } /***/ }), /***/ 5506: /***/ ((module, exports, __webpack_require__) => { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; /*! * Module dependencies. */ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var EventEmitter = (__webpack_require__(9620).EventEmitter); var Kareem = __webpack_require__(3138); var MongooseError = __webpack_require__(5202); var SchemaType = __webpack_require__(4289); var SchemaTypeOptions = __webpack_require__(1764); var VirtualOptions = __webpack_require__(1902); var VirtualType = __webpack_require__(459); var addAutoId = __webpack_require__(4133); var get = __webpack_require__(9981); var getConstructorName = __webpack_require__(1981); var getIndexes = __webpack_require__(5379); var idGetter = __webpack_require__(1879); var merge = __webpack_require__(4913); var mpath = __webpack_require__(3564); var readPref = (__webpack_require__(9906).get)().ReadPreference; var setupTimestamps = __webpack_require__(3767); var utils = __webpack_require__(6872); var validateRef = __webpack_require__(6870); var util = __webpack_require__(161); var MongooseTypes; var queryHooks = (__webpack_require__(5130).middlewareFunctions); var documentHooks = (__webpack_require__(8859).middlewareFunctions); var hookNames = queryHooks.concat(documentHooks).reduce(function (s, hook) { return s.add(hook); }, new Set()); var isPOJO = utils.isPOJO; var 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 | number | object - 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. * - [pluginTags](/docs/guide.html#pluginTags): array of strings - defaults to `undefined`. If set and plugin called with `tags` option, will only apply that plugin to schemas with a matching tag. * * #### 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 https://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 = options && options.methods || {}; this.methodOptions = {}; this.statics = options && options.statics || {}; this.tree = {}; this.query = options && options.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); // build paths if (Array.isArray(obj)) { var _iterator = _createForOfIteratorHelper(obj), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var definition = _step.value; this.add(definition); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } else if (obj) { this.add(obj); } // check if _id's value is a subdocument (gh-2276) var _idSubDoc = obj && obj._id && utils.isObject(obj._id); // ensure the documents get an auto _id unless disabled var auto_id = !this.paths['_id'] && this.options._id && !_idSubDoc; if (auto_id) { addAutoId(this); } this.setupTimestamp(this.options.timestamps); } /*! * Create virtual properties with alias field */ function aliasFields(schema, paths) { paths = paths || Object.keys(schema.paths); var _iterator2 = _createForOfIteratorHelper(paths), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var path = _step2.value; var options = get(schema.paths[path], 'options'); if (options == null) { continue; } var prop = schema.paths[path].path; var alias = options.alias; if (!alias) { continue; } if (typeof alias !== 'string') { throw new Error('Invalid value for alias option on ' + prop + ', got ' + alias); } schema.aliases[alias] = prop; 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)); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } /*! * Inherit from EventEmitter. */ Schema.prototype = Object.create(EventEmitter.prototype); Schema.prototype.constructor = Schema; Schema.prototype.instanceOfSchema = true; /*! * ignore */ Object.defineProperty(Schema.prototype, '$schemaType', { configurable: false, enumerable: false, writable: true }); /** * 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 }); /** * 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 */ Object.defineProperty(Schema.prototype, 'virtuals', { configurable: false, enumerable: true, writable: true }); /** * 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 () { var _this2 = this; var s = this._clone(); // Bubble up `init` for backwards compat s.on('init', function (v) { return _this2.emit('init', v); }); return s; }; /*! * ignore */ Schema.prototype._clone = function _clone(Constructor) { Constructor = Constructor || (this.base == null ? Schema : this.base.Schema); var 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); } if (this._applyDiscriminators != null) { s._applyDiscriminators = Object.assign({}, this._applyDiscriminators); } s.aliases = Object.assign({}, this.aliases); return s; }; /** * 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) { var newSchema = new Schema({}, options || this.options); if (!Array.isArray(paths)) { throw new MongooseError('Schema#pick() only accepts an array argument, ' + 'got "' + _typeof(paths) + '"'); } var _iterator3 = _createForOfIteratorHelper(paths), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var path = _step3.value; if (this.nested[path]) { newSchema.add(_defineProperty({}, path, get(this.tree, path))); } else { var schematype = this.path(path); if (schematype == null) { throw new MongooseError('Path `' + path + '` is not in the schema'); } newSchema.add(_defineProperty({}, path, schematype)); } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return newSchema; }; /** * Returns default options for this schema, merged with `options`. * * @param {Object} options * @return {Object} * @api private */ Schema.prototype.defaultOptions = function (options) { this._userProvidedOptions = options == null ? {} : utils.clone(options); var baseOptions = this.base && this.base.options || {}; var 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) + '`'); } if (options.optimisticConcurrency && !options.versionKey) { throw new MongooseError('Must set `versionKey` if using `optimisticConcurrency`'); } return options; }; /** * Inherit a Schema by applying a discriminator on an existing Schema. * * * ####Example: * * const options = { discriminatorKey: 'kind' }; * * const eventSchema = new mongoose.Schema({ time: Date }, options); * const Event = mongoose.model('Event', eventSchema); * * // ClickedLinkEvent is a special type of Event that has * // a URL. * const ClickedLinkEvent = Event.discriminator('ClickedLink', * new mongoose.Schema({ url: String }, options)); * * // When you create a generic event, it can't have a URL field... * const genericEvent = new Event({ time: Date.now(), url: 'google.com' }); * assert.ok(!genericEvent.url); * // But a ClickedLinkEvent can * const clickedEvent = new ClickedLinkEvent({ time: Date.now(), url: 'google.com' }); * assert.ok(clickedEvent.url); * * @param {String} name the name of the discriminator * @param {Schema} schema the Schema of the discriminated Schema * @return {Schema} the Schema instance * @api public */ Schema.prototype.discriminator = function (name, schema) { this._applyDiscriminators = Object.assign(this._applyDiscriminators || {}, _defineProperty({}, name, schema)); return this; }; /** * 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); return this; } // 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; } prefix = prefix || ''; // avoid prototype pollution if (prefix === '__proto__.' || prefix === 'constructor.' || prefix === 'prototype.') { return this; } var keys = Object.keys(obj); var typeKey = this.options.typeKey; for (var _i = 0, _keys = keys; _i < _keys.length; _i++) { var key = _keys[_i]; var fullPath = prefix + key; var val = obj[key]; if (val == null) { throw new TypeError('Invalid value for schema path `' + fullPath + '`, got value "' + val + '"'); } // Retain `_id: false` but don't set it as a path, re: gh-8274. if (key === '_id' && val === false) { continue; } if (val instanceof VirtualType || (val.constructor && val.constructor.name || null) === 'VirtualType') { this.virtual(val); continue; } if (Array.isArray(val) && val.length === 1 && val[0] == null) { throw new TypeError('Invalid value for schema Array path `' + fullPath + '`, got value "' + val[0] + '"'); } if (!(isPOJO(val) || val instanceof SchemaTypeOptions)) { // Special-case: Non-options definitely a path so leaf at this node // Examples: Schema instances, SchemaType instances if (prefix) { this.nested[prefix.substring(0, prefix.length - 1)] = true; } this.path(prefix + key, val); if (val[0] != null && !val[0].instanceOfSchema && utils.isPOJO(val[0].discriminators)) { var schemaType = this.path(prefix + key); for (var _key in val[0].discriminators) { schemaType.discriminator(_key, val[0].discriminators[_key]); } } else if (val[0] != null && val[0].instanceOfSchema && utils.isPOJO(val[0]._applyDiscriminators)) { var applyDiscriminators = val[0]._applyDiscriminators || []; var _schemaType2 = this.path(prefix + key); for (var disc in applyDiscriminators) { _schemaType2.discriminator(disc, applyDiscriminators[disc]); } } else if (val != null && val.instanceOfSchema && utils.isPOJO(val._applyDiscriminators)) { var _applyDiscriminators = val._applyDiscriminators || []; var _schemaType3 = this.path(prefix + key); for (var _disc in _applyDiscriminators) { _schemaType3.discriminator(_disc, _applyDiscriminators[_disc]); } } } else if (Object.keys(val).length < 1) { // Special-case: {} always interpreted as Mixed path so leaf at this node if (prefix) { this.nested[prefix.substring(0, prefix.length - 1)] = true; } this.path(fullPath, val); // mixed type } else if (!val[typeKey] || typeKey === 'type' && isPOJO(val.type) && val.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(val, fullPath + '.'); } else { // There IS a bona-fide type key that may also be a POJO var _typeDef = val[typeKey]; if (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.substring(0, prefix.length - 1)] = true; } var _schema = new Schema(_typeDef); var schemaWrappedPath = Object.assign({}, val, { 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.substring(0, prefix.length - 1)] = true; } this.path(prefix + key, val); if (val != null && !val.instanceOfSchema && utils.isPOJO(val.discriminators)) { var _schemaType4 = this.path(prefix + key); for (var _key2 in val.discriminators) { _schemaType4.discriminator(_key2, val.discriminators[_key2]); } } } } } var addedKeys = Object.keys(obj).map(function (key) { return prefix ? prefix + key : key; }); aliasFields(this, addedKeys); return this; }; /** * Remove an index by name or index specification. * * removeIndex only removes indexes from your schema object. Does **not** affect the indexes * in MongoDB. * * ####Example: * * const ToySchema = new Schema({ name: String, color: String, price: Number }); * * // Add a new index on { name, color } * ToySchema.index({ name: 1, color: 1 }); * * // Remove index on { name, color } * // Keep in mind that order matters! `removeIndex({ color: 1, name: 1 })` won't remove the index * ToySchema.removeIndex({ name: 1, color: 1 }); * * // Add an index with a custom name * ToySchema.index({ color: 1 }, { name: 'my custom index name' }); * // Remove index by name * ToySchema.removeIndex('my custom index name'); * * @param {Object|string} index name or index specification * @return {Schema} the Schema instance * @api public */ Schema.prototype.removeIndex = function removeIndex(index) { if (arguments.length > 1) { throw new Error('removeIndex() takes only 1 argument'); } if (_typeof(index) !== 'object' && typeof index !== 'string') { throw new Error('removeIndex() may only take either an object or a string as an argument'); } if (_typeof(index) === 'object') { for (var i = this._indexes.length - 1; i >= 0; --i) { if (util.isDeepStrictEqual(this._indexes[i][0], index)) { this._indexes.splice(i, 1); } } } else { for (var _i2 = this._indexes.length - 1; _i2 >= 0; --_i2) { if (this._indexes[_i2][1] != null && this._indexes[_i2][1].name === index) { this._indexes.splice(_i2, 1); } } } return this; }; /** * Remove all indexes from this schema. * * clearIndexes only removes indexes from your schema object. Does **not** affect the indexes * in MongoDB. * * ####Example: * * const ToySchema = new Schema({ name: String, color: String, price: Number }); * ToySchema.index({ name: 1 }); * ToySchema.index({ color: 1 }); * * // Remove all indexes on this schema * ToySchema.clearIndexes(); * * ToySchema.indexes(); // [] * * @return {Schema} the Schema instance * @api public */ Schema.prototype.clearIndexes = function clearIndexes() { this._indexes.length = 0; return this; }; /** * 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 */ Schema.reserved = Object.create(null); Schema.prototype.reserved = Schema.reserved; var reserved = Schema.reserved; // Core object reserved['prototype'] = // EventEmitter reserved.emit = reserved.listeners = 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 */ Schema.prototype.path = function (path, obj) { // Convert to '.$' to check subpaths re: gh-6405 var cleanPath = _pathToPositionalSyntax(path); if (obj === undefined) { var schematype = _getPath(this, path, cleanPath); if (schematype != null) { return schematype; } // Look for maps var mapPath = getMapPath(this, path); if (mapPath != null) { return mapPath; } // Look if a parent of this path is mixed schematype = this.hasMixedParent(cleanPath); if (schematype != null) { return schematype; } // subpaths? return /\.\d+\.?.*$/.test(path) ? getPositionalPath(this, path) : undefined; } // some path names conflict with document methods var firstPieceOfPath = path.split('.')[0]; if (reserved[firstPieceOfPath] && !this.options.supressReservedKeysWarning) { var errorMessage = "`".concat(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.'; utils.warn(errorMessage); } if (_typeof(obj) === 'object' && utils.hasUserDefinedProperty(obj, 'ref')) { validateRef(obj.ref, path); } // update the tree var subpaths = path.split(/\./); var last = subpaths.pop(); var branch = this.tree; var fullPath = ''; var _iterator4 = _createForOfIteratorHelper(subpaths), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var sub = _step4.value; fullPath = fullPath += (fullPath.length > 0 ? '.' : '') + sub; if (!branch[sub]) { this.nested[fullPath] = true; branch[sub] = {}; } if (_typeof(branch[sub]) !== 'object') { var msg = 'Cannot set nested path `' + path + '`. ' + 'Parent path `' + fullPath + '` already set to type ' + branch[sub].name + '.'; throw new Error(msg); } branch = branch[sub]; } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } branch[last] = utils.clone(obj); this.paths[path] = this.interpretAsType(path, obj, this.options); var 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." var _mapPath = path + '.$*'; this.paths[_mapPath] = schemaType.$__schemaType; this.mapPaths.push(this.paths[_mapPath]); } if (schemaType.$isSingleNested) { for (var _i3 = 0, _Object$keys = Object.keys(schemaType.schema.paths); _i3 < _Object$keys.length; _i3++) { var key = _Object$keys[_i3]; this.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key]; } for (var _i4 = 0, _Object$keys2 = Object.keys(schemaType.schema.singleNestedPaths); _i4 < _Object$keys2.length; _i4++) { var _key3 = _Object$keys2[_i4]; this.singleNestedPaths[path + '.' + _key3] = schemaType.schema.singleNestedPaths[_key3]; } for (var _i5 = 0, _Object$keys3 = Object.keys(schemaType.schema.subpaths); _i5 < _Object$keys3.length; _i5++) { var _key4 = _Object$keys3[_i5]; this.singleNestedPaths[path + '.' + _key4] = schemaType.schema.subpaths[_key4]; } for (var _i6 = 0, _Object$keys4 = Object.keys(schemaType.schema.nested); _i6 < _Object$keys4.length; _i6++) { var _key5 = _Object$keys4[_i6]; this.singleNestedPaths[path + '.' + _key5] = 'nested'; } Object.defineProperty(schemaType.schema, 'base', { configurable: true, enumerable: false, writable: false, value: this.base }); 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 }); schemaType.casterConstructor.base = this.base; this.childSchemas.push({ schema: schemaType.schema, model: schemaType.casterConstructor }); } if (schemaType.$isMongooseArray && schemaType.caster instanceof SchemaType) { var arrayPath = path; var _schemaType = schemaType; var 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(); } _schemaType.path = arrayPath; toAdd.push(_schemaType); } for (var _i7 = 0, _toAdd = toAdd; _i7 < _toAdd.length; _i7++) { var _schemaType5 = _toAdd[_i7]; this.subpaths[_schemaType5.path] = _schemaType5; } } if (schemaType.$isMongooseDocumentArray) { for (var _i8 = 0, _Object$keys5 = Object.keys(schemaType.schema.paths); _i8 < _Object$keys5.length; _i8++) { var _key6 = _Object$keys5[_i8]; var _schemaType6 = schemaType.schema.paths[_key6]; this.subpaths[path + '.' + _key6] = _schemaType6; if (_typeof(_schemaType6) === 'object' && _schemaType6 != null) { _schemaType6.$isUnderneathDocArray = true; } } for (var _i9 = 0, _Object$keys6 = Object.keys(schemaType.schema.subpaths); _i9 < _Object$keys6.length; _i9++) { var _key7 = _Object$keys6[_i9]; var _schemaType7 = schemaType.schema.subpaths[_key7]; this.subpaths[path + '.' + _key7] = _schemaType7; if (_typeof(_schemaType7) === 'object' && _schemaType7 != null) { _schemaType7.$isUnderneathDocArray = true; } } for (var _i10 = 0, _Object$keys7 = Object.keys(schemaType.schema.singleNestedPaths); _i10 < _Object$keys7.length; _i10++) { var _key8 = _Object$keys7[_i10]; var _schemaType8 = schemaType.schema.singleNestedPaths[_key8]; this.subpaths[path + '.' + _key8] = _schemaType8; if (_typeof(_schemaType8) === 'object' && _schemaType8 != null) { _schemaType8.$isUnderneathDocArray = true; } } } return this; }; /*! * ignore */ function gatherChildSchemas(schema) { var childSchemas = []; for (var _i11 = 0, _Object$keys8 = Object.keys(schema.paths); _i11 < _Object$keys8.length; _i11++) { var path = _Object$keys8[_i11]; var schematype = schema.paths[path]; if (schematype.$isMongooseDocumentArray || schematype.$isSingleNested) { childSchemas.push({ schema: schematype.schema, model: schematype.caster }); } } return childSchemas; } /*! * ignore */ 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 null; } /*! * ignore */ function _pathToPositionalSyntax(path) { if (!/\.\d+/.test(path)) { return path; } return path.replace(/\.\d+\./g, '.$.').replace(/\.\d+$/, '.$'); } /*! * ignore */ function getMapPath(schema, path) { if (schema.mapPaths.length === 0) { return null; } var _iterator5 = _createForOfIteratorHelper(schema.mapPaths), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var val = _step5.value; var _path = val.path; var re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$'); if (re.test(path)) { return schema.paths[_path]; } } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } return null; } /** * 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 }); /** * 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; } var 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 var MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types; if (!utils.isPOJO(obj) && !(obj instanceof SchemaTypeOptions)) { var constructorName = utils.getFunctionName(obj.constructor); if (constructorName !== 'Object') { var oldObj = obj; obj = {}; obj[options.typeKey] = oldObj; } } // Get the type making sure to allow keys named "type" // and default to mixed if not specified. // { type: { type: String, default: 'freshcut' } } var type = obj[options.typeKey] && (obj[options.typeKey] instanceof Function || options.typeKey !== 'type' || !obj.type.type) ? obj[options.typeKey] : {}; var name; if (utils.isPOJO(type) || type === 'mixed') { return new MongooseTypes.Mixed(path, obj); } if (Array.isArray(type) || type === Array || type === 'array' || type === MongooseTypes.Array) { // if it was specified through { type } look for `cast` var cast = type === Array || type === 'array' ? obj.cast || obj.of : type[0]; // 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`. If you are still ' + 'getting this error, please add `new Schema()` around the path: ' + "".concat(path, ": new Schema(...)")); } 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`. If you are still ' + 'getting this error, please add `new Schema()` around the path: ' + "".concat(path, ": new Schema(...)")); } return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast); } if (Array.isArray(cast)) { return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj); } // Handle both `new Schema({ arr: [{ subpath: String }] })` and `new Schema({ arr: [{ type: { subpath: string } }] })` var 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 var 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; } var 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); } } if (cast) { type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type) ? cast[options.typeKey] : cast; if (Array.isArray(type)) { return new MongooseTypes.Array(path, this.interpretAsType(path, type, options), obj); } name = typeof type === 'string' ? type : type.schemaName || utils.getFunctionName(type); // For Jest 26+, see #10296 if (name === 'ClockDate') { name = 'Date'; } if (name === void 0) { throw new TypeError('Invalid schema configuration: ' + "Could not determine the embedded type for array `".concat(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: ' + "`".concat(name, "` is not a valid type within the array `").concat(path, "`.") + 'See https://bit.ly/mongoose-schematypes for a list of valid schema types.'); } } return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options); } 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(); } 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'; } if (name === void 0) { throw new TypeError("Invalid schema configuration: `".concat(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: `".concat(name, "` is not ") + "a valid type at path `".concat(path, "`. See ") + 'https://bit.ly/mongoose-schematypes for a list of valid schema types.'); } var schemaType = new MongooseTypes[name](path, obj); if (schemaType.$isSchemaMap) { createMapNestedSchemaType(this, schemaType, path, obj, options); } return schemaType; }; /*! * ignore */ function createMapNestedSchemaType(schema, schemaType, path, obj, options) { var mapPath = path + '.$*'; var _mapType = { type: {} }; if (utils.hasUserDefinedProperty(obj, 'of')) { var isInlineSchema = utils.isPOJO(obj.of) && Object.keys(obj.of).length > 0 && !utils.hasUserDefinedProperty(obj.of, schema.options.typeKey); if (isInlineSchema) { _mapType = _defineProperty({}, schema.options.typeKey, new Schema(obj.of)); } else if (utils.isPOJO(obj.of)) { _mapType = Object.assign({}, obj.of); } else { _mapType = _defineProperty({}, schema.options.typeKey, obj.of); } if (_mapType[schema.options.typeKey] && _mapType[schema.options.typeKey].instanceOfSchema) { var subdocumentSchema = _mapType[schema.options.typeKey]; subdocumentSchema.eachPath(function (subpath, type) { if (type.options.select === true || type.options.select === false) { throw new MongooseError('Cannot use schema-level projections (`select: true` or `select: false`) within maps at path "' + path + '.' + subpath + '"'); } }); } if (utils.hasUserDefinedProperty(obj, 'ref')) { _mapType.ref = obj.ref; } } schemaType.$__schemaType = schema.interpretAsType(mapPath, _mapType, options); } /** * 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) { var keys = Object.keys(this.paths); var len = keys.length; for (var i = 0; i < len; ++i) { fn(keys[i], this.paths[keys[i]]); } 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} */ Schema.prototype.requiredPaths = function requiredPaths(invalidate) { if (this._requiredpaths && !invalidate) { return this._requiredpaths; } var paths = Object.keys(this.paths); var i = paths.length; var ret = []; while (i--) { var path = paths[i]; if (this.paths[path].isRequired) { ret.push(path); } } this._requiredpaths = ret; return this._requiredpaths; }; /** * Returns indexes from fields and schema-level indexes (cached). * * @api private * @return {Array} */ Schema.prototype.indexedPaths = function indexedPaths() { if (this._indexedpaths) { return this._indexedpaths; } this._indexedpaths = this.indexes(); return this._indexedpaths; }; /** * 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 var 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'; } var singleNestedPath = this.singleNestedPaths.hasOwnProperty(cleanPath) || this.singleNestedPaths.hasOwnProperty(path); if (singleNestedPath) { return singleNestedPath === 'nested' ? 'nested' : 'real'; } // Look for maps var mapPath = getMapPath(this, path); if (mapPath != null) { return 'real'; } if (/\.\d+\.|\.\d+$/.test(path)) { return getPositionalPathType(this, path); } return 'adhocOrUndefined'; }; /** * Returns true iff this path is a child of a mixed schema. * * @param {String} path * @return {Boolean} * @api private */ Schema.prototype.hasMixedParent = function (path) { var subpaths = path.split(/\./g); path = ''; for (var 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]; } } return null; }; /** * 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); }; /*! * ignore. Deprecated re: #6405 */ function getPositionalPathType(self, path) { var subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); if (subpaths.length < 2) { return self.paths.hasOwnProperty(subpaths[0]) ? self.paths[subpaths[0]] : 'adhocOrUndefined'; } var val = self.path(subpaths[0]); var isNested = false; if (!val) { return 'adhocOrUndefined'; } var last = subpaths.length - 1; for (var i = 1; i < subpaths.length; ++i) { isNested = false; var subpath = subpaths[i]; 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 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 (!(val && val.schema)) { val = undefined; break; } var type = val.schema.pathType(subpath); isNested = type === 'nested'; val = val.schema.path(subpath); } self.subpaths[path] = val; if (val) { return 'real'; } if (isNested) { return 'nested'; } return 'adhocOrUndefined'; } /*! * ignore */ function getPositionalPath(self, path) { getPositionalPathType(self, path); return self.subpaths[path]; } /** * 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 */ Schema.prototype.queue = function (name, args) { this.callQueue.push([name, args]); return this; }; /** * 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) { var remainingArgs = Array.prototype.slice.call(arguments, 1); var _iterator6 = _createForOfIteratorHelper(hookNames), _step6; try { for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { var fn = _step6.value; if (name.test(fn)) { this.pre.apply(this, [fn].concat(remainingArgs)); } } } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } return this; } if (Array.isArray(name)) { var _remainingArgs = Array.prototype.slice.call(arguments, 1); var _iterator7 = _createForOfIteratorHelper(name), _step7; try { for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) { var el = _step7.value; this.pre.apply(this, [el].concat(_remainingArgs)); } } catch (err) { _iterator7.e(err); } finally { _iterator7.f(); } return this; } this.s.hooks.pre.apply(this.s.hooks, arguments); return this; }; /** * 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 https://mongoosejs.com/docs/middleware.html * @see kareem https://npmjs.org/package/kareem * @api public */ Schema.prototype.post = function (name) { if (name instanceof RegExp) { var remainingArgs = Array.prototype.slice.call(arguments, 1); var _iterator8 = _createForOfIteratorHelper(hookNames), _step8; try { for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) { var fn = _step8.value; if (name.test(fn)) { this.post.apply(this, [fn].concat(remainingArgs)); } } } catch (err) { _iterator8.e(err); } finally { _iterator8.f(); } return this; } if (Array.isArray(name)) { var _remainingArgs2 = Array.prototype.slice.call(arguments, 1); var _iterator9 = _createForOfIteratorHelper(name), _step9; try { for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) { var el = _step9.value; this.post.apply(this, [el].concat(_remainingArgs2)); } } catch (err) { _iterator9.e(err); } finally { _iterator9.f(); } return this; } this.s.hooks.post.apply(this.s.hooks, arguments); return this; }; /** * 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) + '"'); } if (opts && opts.deduplicate) { var _iterator10 = _createForOfIteratorHelper(this.plugins), _step10; try { for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) { var plugin = _step10.value; if (plugin.fn === fn) { return this; } } } catch (err) { _iterator10.e(err); } finally { _iterator10.f(); } } this.plugins.push({ fn: fn, opts: opts }); fn(this, opts); return this; }; /** * 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 (var 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; }; /** * 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 (var i in name) { this.statics[i] = name[i]; } } else { this.statics[name] = fn; } return this; }; /** * 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](https://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 */ Schema.prototype.index = function (fields, options) { fields || (fields = {}); options || (options = {}); if (options.expires) { utils.expires(options); } this._indexes.push([fields, options]); return this; }; /** * 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 '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; } 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 */ Schema.prototype.get = function (key) { return this.options[key]; }; /** * The allowed index types * * @receiver Schema * @static indexTypes * @api public */ var indexTypes = '2d 2dsphere hashed text'.split(' '); Object.defineProperty(Schema, 'indexTypes', { get: function get() { return indexTypes; }, set: function set() { throw new Error('Cannot overwrite Schema.indexTypes'); } }); /** * 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); }; /** * 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} */ Schema.prototype.virtual = function (name, options) { if (name instanceof VirtualType || getConstructorName(name) === 'VirtualType') { return this.virtual(name.path, name.options); } options = new VirtualOptions(options); if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) { if (options.localField == null) { throw new Error('Reference virtuals require `localField` option'); } if (options.foreignField == null) { throw new Error('Reference virtuals require `foreignField` option'); } this.pre('init', function (obj) { if (mpath.has(name, obj)) { var _v = mpath.get(name, obj); if (!this.$$populatedVirtuals) { this.$$populatedVirtuals = {}; } 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]; } mpath.unset(name, obj); } }); var virtual = this.virtual(name); virtual.options = options; virtual.set(function (_v) { if (!this.$$populatedVirtuals) { this.$$populatedVirtuals = {}; } if (options.justOne || options.count) { this.$$populatedVirtuals[name] = Array.isArray(_v) ? _v[0] : _v; 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'; }); } }); if (typeof options.get === 'function') { virtual.get(options.get); } // Workaround for gh-8198: if virtual is under document array, make a fake // virtual. See gh-8210 var _parts = name.split('.'); var cur = _parts[0]; for (var i = 0; i < _parts.length - 1; ++i) { if (this.paths[cur] != null && this.paths[cur].$isMongooseDocumentArray) { var remnant = _parts.slice(i + 1).join('.'); this.paths[cur].schema.virtual(remnant, options); break; } cur += '.' + _parts[i + 1]; } return virtual; } var virtuals = this.virtuals; var parts = name.split('.'); if (this.pathType(name) === 'real') { throw new Error('Virtual path "' + name + '"' + ' conflicts with a real path in the schema'); } 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); return virtuals[name]; }; /** * Returns the virtual type with the given `name`. * * @param {String} name * @return {VirtualType} */ Schema.prototype.virtualpath = function (name) { return this.virtuals.hasOwnProperty(name) ? this.virtuals[name] : null; }; /** * 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]) { var allKeys = Object.keys(this.paths).concat(Object.keys(this.nested)); var _iterator11 = _createForOfIteratorHelper(allKeys), _step11; try { for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) { var _path2 = _step11.value; if (_path2.startsWith(name + '.')) { delete this.paths[_path2]; delete this.nested[_path2]; _deletePath(this, _path2); } } } catch (err) { _iterator11.e(err); } finally { _iterator11.f(); } delete this.nested[name]; _deletePath(this, name); return; } delete this.paths[name]; _deletePath(this, name); }, this); } return this; }; /*! * ignore */ function _deletePath(schema, name) { var pieces = name.split('.'); var last = pieces.pop(); var branch = schema.tree; var _iterator12 = _createForOfIteratorHelper(pieces), _step12; try { for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) { var piece = _step12.value; branch = branch[piece]; } } catch (err) { _iterator12.e(err); } finally { _iterator12.f(); } 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; } this.loadClass(Object.getPrototypeOf(model), virtualsOnly); // Add static methods if (!virtualsOnly) { Object.getOwnPropertyNames(model).forEach(function (name) { if (name.match(/^(length|name|prototype|constructor|__proto__)$/)) { return; } var prop = Object.getOwnPropertyDescriptor(model, name); if (prop.hasOwnProperty('value')) { this["static"](name, prop.value); } }, this); } // Add methods and virtuals Object.getOwnPropertyNames(model.prototype).forEach(function (name) { if (name.match(/^(constructor)$/)) { return; } var 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 */ Schema.prototype._getSchema = function (path) { var _this = this; var pathschema = _this.path(path); var resultPath = []; if (pathschema) { pathschema.$fullPath = path; return pathschema; } function search(parts, schema) { var p = parts.length + 1; var foundschema; var 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) { var ret = void 0; 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; } var _ret = search(parts.slice(p + 1), foundschema.$__schemaType.schema); return _ret; } foundschema.$fullPath = resultPath.join('.'); return foundschema; } } } // look for arrays var parts = path.split('.'); for (var 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); }; /*! * ignore */ Schema.prototype._getPathType = function (path) { var _this = this; var pathschema = _this.path(path); if (pathschema) { return 'real'; } function search(parts, schema) { var 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 { 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' }; } // look for arrays return search(path.split('.'), _this); }; /*! * ignore */ function isArrayFilter(piece) { return piece.startsWith('$[') && piece.endsWith(']'); } /*! * Called by `compile()` _right before_ compiling. Good for making any changes to * the schema that should respect options set by plugins, like `id` */ Schema.prototype._preCompile = function _preCompile() { idGetter(this); }; /*! * 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 = __webpack_require__(5251); /*! * ignore */ exports.ObjectId = MongooseTypes.ObjectId; /***/ }), /***/ 3617: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var CastError = __webpack_require__(1795); var EventEmitter = (__webpack_require__(9620).EventEmitter); var ObjectExpectedError = __webpack_require__(4107); var SchemaSubdocumentOptions = __webpack_require__(5446); var SchemaType = __webpack_require__(4289); var $exists = __webpack_require__(8702); var castToNumber = (__webpack_require__(1521)/* .castToNumber */ .W); var discriminator = __webpack_require__(9181); var geospatial = __webpack_require__(5008); var getConstructor = __webpack_require__(8413); var handleIdOption = __webpack_require__(9691); var internalToObjectOptions = (__webpack_require__(4962)/* .internalToObjectOptions */ .h); var utils = __webpack_require__(6872); var Subdocument; module.exports = SubdocumentPath; /** * Single nested subdocument SchemaType constructor. * * @param {Schema} schema * @param {String} path * @param {Object} options * @inherits SchemaType * @api public */ function SubdocumentPath(schema, path, options) { var schemaTypeIdOption = SubdocumentPath.defaultOptions && SubdocumentPath.defaultOptions._id; if (schemaTypeIdOption != null) { options = options || {}; options._id = schemaTypeIdOption; } 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 */ SubdocumentPath.prototype = Object.create(SchemaType.prototype); SubdocumentPath.prototype.constructor = SubdocumentPath; SubdocumentPath.prototype.OptionsConstructor = SchemaSubdocumentOptions; /*! * ignore */ function _createConstructor(schema, baseClass) { // lazy load Subdocument || (Subdocument = __webpack_require__(2591)); var _embedded = function SingleNested(value, path, parent) { this.$__parent = parent; Subdocument.apply(this, arguments); if (parent == null) { return; } this.$session(parent.$session()); }; schema._preCompile(); var 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); }; // apply methods for (var i in schema.methods) { _embedded.prototype[i] = schema.methods[i]; } // apply statics for (var _i in schema.statics) { _embedded[_i] = schema.statics[_i]; } for (var _i2 in EventEmitter.prototype) { _embedded[_i2] = EventEmitter.prototype[_i2]; } return _embedded; } /*! * 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 */ SubdocumentPath.prototype.$conditionalHandlers.$geoWithin = function handle$geoWithin(val) { return { $geometry: this.castForQuery(val.$geometry) }; }; /*! * ignore */ SubdocumentPath.prototype.$conditionalHandlers.$near = SubdocumentPath.prototype.$conditionalHandlers.$nearSphere = geospatial.cast$near; SubdocumentPath.prototype.$conditionalHandlers.$within = SubdocumentPath.prototype.$conditionalHandlers.$geoWithin = geospatial.cast$within; SubdocumentPath.prototype.$conditionalHandlers.$geoIntersects = geospatial.cast$geoIntersects; SubdocumentPath.prototype.$conditionalHandlers.$minDistance = castToNumber; SubdocumentPath.prototype.$conditionalHandlers.$maxDistance = castToNumber; SubdocumentPath.prototype.$conditionalHandlers.$exists = $exists; /** * Casts contents * * @param {Object} value * @api private */ SubdocumentPath.prototype.cast = function (val, doc, init, priorVal, options) { if (val && val.$isSingleNested && val.parent === doc) { return val; } if (val != null && (_typeof(val) !== 'object' || Array.isArray(val))) { throw new ObjectExpectedError(this.path, val); } var Constructor = getConstructor(this.caster, val); var subdoc; // Only pull relevant selected paths and pull out the base path var parentSelected = doc && doc.$__ && doc.$__.selected || {}; var path = this.path; var selected = Object.keys(parentSelected).reduce(function (obj, key) { if (key.startsWith(path + '.')) { obj = obj || {}; obj[key.substring(path.length + 1)] = parentSelected[key]; } return obj; }, null); 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 new Constructor(val, selected, doc, undefined, options); } return subdoc; }; /** * Casts contents for query * * @param {string} [$conditional] optional query operator (like `$eq` or `$in`) * @param {any} value * @api private */ SubdocumentPath.prototype.castForQuery = function ($conditional, val, options) { var 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; } if (this.options.runSetters) { val = this._applySetters(val); } var Constructor = getConstructor(this.caster, val); var 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; }; /** * Async validation on this single nested doc. * * @api private */ SubdocumentPath.prototype.doValidate = function (value, fn, scope, options) { var Constructor = getConstructor(this.caster, value); if (value && !(value instanceof Constructor)) { value = new Constructor(value, null, scope != null && scope.$__ != null ? scope : null); } if (options && options.skipSchemaValidators) { if (!value) { return fn(null); } return value.validate(fn); } SchemaType.prototype.doValidate.call(this, value, function (error) { if (error) { return fn(error); } if (!value) { return fn(null); } value.validate(fn); }, scope, options); }; /** * Synchronously validate this single nested doc * * @api private */ SubdocumentPath.prototype.doValidateSync = function (value, scope, options) { if (!options || !options.skipSchemaValidators) { var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope); if (schemaTypeError) { return schemaTypeError; } } if (!value) { return; } return value.validateSync(); }; /** * 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 */ SubdocumentPath.prototype.discriminator = function (name, schema, options) { options = options || {}; var value = utils.isPOJO(options) ? options.value : options; var clone = typeof options.clone === 'boolean' ? options.clone : true; if (schema.instanceOfSchema && clone) { schema = schema.clone(); } schema = discriminator(this.caster, name, schema, value); this.caster.discriminators[name] = _createConstructor(schema, this.caster); return this.caster.discriminators[name]; }; /** * 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 */ SubdocumentPath.defaultOptions = {}; SubdocumentPath.set = SchemaType.set; /*! * ignore */ SubdocumentPath.prototype.clone = function () { var options = Object.assign({}, this.options); var 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; }; /***/ }), /***/ 94: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var $exists = __webpack_require__(8702); var $type = __webpack_require__(3053); var MongooseError = __webpack_require__(5202); var SchemaArrayOptions = __webpack_require__(4756); var SchemaType = __webpack_require__(4289); var CastError = SchemaType.CastError; var Mixed = __webpack_require__(3861); var arrayDepth = __webpack_require__(6069); var cast = __webpack_require__(6787); var isOperator = __webpack_require__(9627); var util = __webpack_require__(161); var utils = __webpack_require__(6872); var castToNumber = (__webpack_require__(1521)/* .castToNumber */ .W); var geospatial = __webpack_require__(5008); var getDiscriminatorByValue = __webpack_require__(7291); var MongooseArray; var EmbeddedDoc; var isNestedArraySymbol = Symbol('mongoose#isNestedArray'); var emptyOpts = Object.freeze({}); /** * Array SchemaType constructor * * @param {String} key * @param {SchemaType} cast * @param {Object} options * @param {Object} schemaOptions * @inherits SchemaType * @api public */ function SchemaArray(key, cast, options, schemaOptions) { // lazy load EmbeddedDoc || (EmbeddedDoc = (__webpack_require__(8941).Embedded)); var typeKey = 'type'; if (schemaOptions && schemaOptions.typeKey) { typeKey = schemaOptions.typeKey; } this.schemaOptions = schemaOptions; if (cast) { var 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; } } if (options != null && options.ref != null && castOptions.ref == null) { castOptions.ref = options.ref; } if (cast === Object) { cast = Mixed; } // support { type: 'String' } var name = typeof cast === 'string' ? cast : utils.getFunctionName(cast); var Types = __webpack_require__(5251); var caster = Types.hasOwnProperty(name) ? Types[name] : cast; this.casterConstructor = caster; if (this.casterConstructor instanceof SchemaArray) { this.casterConstructor[isNestedArraySymbol] = true; } if (typeof caster === 'function' && !caster.$isArraySubdocument && !caster.$isSchemaMap) { var 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; } } this.$embeddedSchemaType = this.caster; } this.$isMongooseArray = true; SchemaType.call(this, key, options, 'Array'); var defaultArr; var fn; if (this.defaultValue != null) { defaultArr = this.defaultValue; fn = typeof defaultArr === 'function'; } if (!('defaultValue' in this) || this.defaultValue !== void 0) { var defaultFn = function defaultFn() { // Leave it up to `cast()` to convert the array return fn ? defaultArr.call(this) : defaultArr != null ? [].concat(defaultArr) : []; }; 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 (_typeof(value) === 'object' && 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. var _checkRequired = typeof this.constructor.checkRequired === 'function' ? this.constructor.checkRequired() : SchemaArray.checkRequired(); return _checkRequired(value); }; /** * 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 */ SchemaArray.prototype["enum"] = function () { var arr = this; while (true) { var instance = arr && arr.caster && 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; } var enumArray = arguments; if (!Array.isArray(arguments) && utils.isObject(arguments)) { enumArray = utils.object.vals(enumArray); } arr.caster["enum"].apply(arr.caster, enumArray); return this; }; /** * 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; } var ret = SchemaType.prototype.applyGetters.call(this, value, scope); if (Array.isArray(ret)) { var rawValue = utils.isMongooseArray(ret) ? ret.__array : ret; var len = rawValue.length; for (var 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 var depth = 0; var 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) { var valueDepth = arrayDepth(value); if (valueDepth.min === valueDepth.max && valueDepth.max < depth && valueDepth.containsNonArrayItem) { for (var i = valueDepth.max; i < depth; ++i) { value = [value]; } } } } 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 */ SchemaArray.prototype.cast = function (value, doc, init, prev, options) { // lazy load MongooseArray || (MongooseArray = (__webpack_require__(8941).Array)); var i; var l; if (Array.isArray(value)) { var len = value.length; if (!len && doc) { var indexes = doc.schema.indexedPaths(); var arrayPath = this.path; for (i = 0, l = indexes.length; i < l; ++i) { var pathIndex = indexes[i][0][arrayPath]; if (pathIndex === '2dsphere' || pathIndex === '2d') { return; } } // Special case: if this index is on the parent of what looks like // GeoJSON, skip setting the default to empty array re: #1668, #3233 var arrayGeojsonPath = this.path.endsWith('.coordinates') ? this.path.substring(0, this.path.lastIndexOf('.')) : null; if (arrayGeojsonPath != null) { for (i = 0, l = indexes.length; i < l; ++i) { var _pathIndex = indexes[i][0][arrayGeojsonPath]; if (_pathIndex === '2dsphere') { return; } } } } options = options || emptyOpts; var rawValue = utils.isMongooseArray(value) ? value.__array : value; value = MongooseArray(rawValue, options.path || this._arrayPath || this.path, doc, this); rawValue = value.__array; if (init && doc != null && doc.$__ != null && doc.$populated(this.path)) { return value; } var caster = this.caster; var isMongooseArray = caster.$isMongooseArray; if (caster && this.casterConstructor !== Mixed) { try { var _len = rawValue.length; for (i = 0; i < _len; i++) { var 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); } } return value; } 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); } throw new CastError('Array', util.inspect(value), this.path, null, this); }; /*! * ignore */ SchemaArray.prototype._castForPopulate = function _castForPopulate(value, doc) { // lazy load MongooseArray || (MongooseArray = (__webpack_require__(8941).Array)); if (Array.isArray(value)) { var i; var rawValue = value.__array ? value.__array : value; var len = rawValue.length; var caster = this.caster; if (caster && this.casterConstructor !== Mixed) { try { for (i = 0; i < len; i++) { var 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; } 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); } } return value; } throw new CastError('Array', util.inspect(value), this.path, null, this); }; SchemaArray.prototype.$toObject = SchemaArray.prototype.toObject; /*! * Ignore */ SchemaArray.prototype.discriminator = function (name, schema) { var 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 */ SchemaArray.prototype.clone = function () { var options = Object.assign({}, this.options); var 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; }; /** * Casts values for queries. * * @param {String} $conditional * @param {any} [value] * @api private */ SchemaArray.prototype.castForQuery = function ($conditional, value) { var _this = this; var handler; var val; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional + ' with Array.'); } val = handler.call(this, value); } else { val = $conditional; var 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 { var constructorByValue = getDiscriminatorByValue(Constructor.discriminators, val[Constructor.schema.options.discriminatorKey]); if (constructorByValue) { Constructor = constructorByValue; } } } var proto = this.casterConstructor.prototype; var method = proto && (proto.castForQuery || proto.cast); if (!method && Constructor.castForQuery) { method = Constructor.castForQuery; } var caster = this.caster; if (Array.isArray(val)) { this.setters.reverse().forEach(function (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); } } return val; }; function cast$all(val) { if (!Array.isArray(val)) { val = [val]; } val = val.map(function (v) { if (!utils.isObject(v)) { return v; } if (v.$elemMatch != null) { return { $elemMatch: cast(this.casterConstructor.schema, v.$elemMatch) }; } var o = {}; o[this.path] = v; return cast(this.casterConstructor.schema, o)[this.path]; }, this); return this.castForQuery(val); } function cast$elemMatch(val) { var keys = Object.keys(val); var numKeys = keys.length; for (var i = 0; i < numKeys; ++i) { var key = keys[i]; var value = val[key]; if (isOperator(key) && value != null) { val[key] = this.castForQuery(key, value); } } // Is this an embedded discriminator and is the discriminator key set? // If so, use the discriminator schema. See gh-7449 var discriminatorKey = this && this.casterConstructor && this.casterConstructor.schema && this.casterConstructor.schema.options && this.casterConstructor.schema.options.discriminatorKey; var discriminators = this && this.casterConstructor && this.casterConstructor.schema && this.casterConstructor.schema.discriminators || {}; if (discriminatorKey != null && val[discriminatorKey] != null && discriminators[val[discriminatorKey]] != null) { return cast(discriminators[val[discriminatorKey]], val); } return cast(this.casterConstructor.schema, val); } var handle = SchemaArray.prototype.$conditionalHandlers = {}; 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'); function createLogicalQueryOperatorHandler(op) { return function logicalQueryOperatorHandler(val) { if (!Array.isArray(val)) { throw new TypeError('conditional ' + op + ' requires an array'); } var ret = []; var _iterator = _createForOfIteratorHelper(val), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var obj = _step.value; ret.push(cast(this.casterConstructor.schema, obj)); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return ret; }; } handle.$near = handle.$nearSphere = geospatial.cast$near; handle.$within = handle.$geoWithin = geospatial.cast$within; handle.$size = handle.$minDistance = handle.$maxDistance = castToNumber; handle.$exists = $exists; handle.$type = $type; handle.$eq = handle.$gt = handle.$gte = handle.$lt = handle.$lte = handle.$ne = handle.$not = handle.$regex = SchemaArray.prototype.castForQuery; // `$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 = SchemaArray; /***/ }), /***/ 6470: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ var CastError = __webpack_require__(1795); var SchemaType = __webpack_require__(4289); var castBoolean = __webpack_require__(6670); var utils = __webpack_require__(6872); /** * 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; }; /*! * ignore */ SchemaBoolean._defaultCaster = function (v) { if (v != null && typeof v !== 'boolean') { throw new Error(); } return v; }; /*! * ignore */ SchemaBoolean._checkRequired = function (v) { return 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: function get() { return castBoolean.convertToTrue; }, set: function 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: function get() { return castBoolean.convertToFalse; }, set: function set(v) { castBoolean.convertToFalse = v; } }); /** * Casts to boolean * * @param {Object} value * @param {Object} model - this value is optional * @api private */ SchemaBoolean.prototype.cast = function (value) { var castBoolean; if (typeof this._castFunction === 'function') { castBoolean = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castBoolean = this.constructor.cast(); } else { castBoolean = SchemaBoolean.cast(); } try { return castBoolean(value); } catch (error) { throw new CastError('Boolean', value, this.path, error, this); } }; SchemaBoolean.$conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, {}); /** * Casts contents for queries. * * @param {String} $conditional * @param {any} val * @api private */ SchemaBoolean.prototype.castForQuery = function ($conditional, val) { var handler; if (arguments.length === 2) { handler = SchemaBoolean.$conditionalHandlers[$conditional]; if (handler) { return handler.call(this, val); } return this._castForQuery(val); } return this._castForQuery($conditional); }; /** * * @api private */ SchemaBoolean.prototype._castNullish = function _castNullish(v) { if (typeof v === 'undefined') { return v; } var 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; }; /*! * Module exports. */ module.exports = SchemaBoolean; /***/ }), /***/ 8800: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var MongooseBuffer = __webpack_require__(4051); var SchemaBufferOptions = __webpack_require__(9586); var SchemaType = __webpack_require__(4289); var handleBitwiseOperator = __webpack_require__(4282); var utils = __webpack_require__(6872); var Binary = MongooseBuffer.Binary; var 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 = function (v) { return !!(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); }; /** * 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) { var ret; if (SchemaType._isRef(this, value, doc, init)) { if (value && value.isMongooseBuffer) { return value; } 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 (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 (value == null || utils.isNonBuiltinObject(value)) { return this._castRef(value, doc, init); } } // documents if (value && value._id) { value = value._id; } if (value && value.isMongooseBuffer) { return value; } 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 (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 (value === null) { return value; } var 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; } throw new CastError('Buffer', value, this.path, null, this); }; /** * 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](https://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; }; /*! * 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 }); /** * Casts contents for queries. * * @param {String} $conditional * @param {any} [value] * @api private */ SchemaBuffer.prototype.castForQuery = function ($conditional, val) { var 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; var casted = this._castForQuery(val); return casted ? casted.toObject({ transform: false, virtuals: false }) : casted; }; /*! * Module exports. */ module.exports = SchemaBuffer; /***/ }), /***/ 6535: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module requirements. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var MongooseError = __webpack_require__(4888); var SchemaDateOptions = __webpack_require__(2869); var SchemaType = __webpack_require__(4289); var castDate = __webpack_require__(195); var getConstructorName = __webpack_require__(1981); var utils = __webpack_require__(6872); var 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; }; /*! * ignore */ SchemaDate._defaultCaster = function (v) { if (v != null && !(v instanceof Date)) { throw new Error(); } 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 = function (v) { return 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 (_typeof(value) === 'object' && SchemaType._isRef(this, value, doc, true)) { return value != null; } // `require('util').inherits()` does **not** copy static properties, and // plugins like mongoose-float use `inherits()` for pre-ES6. var _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); } if (value) { var msg = message || MongooseError.messages.Date.min; if (typeof msg === 'string') { msg = msg.replace(/{MIN}/, value === Date.now ? 'Date.now()' : value.toString()); } var _this = this; this.validators.push({ validator: this.minValidator = function (val) { var _value = value; if (typeof value === 'function' && value !== Date.now) { _value = _value.call(this); } var min = _value === Date.now ? _value() : _this.cast(_value); return val === null || val.valueOf() >= min.valueOf(); }, message: msg, type: 'min', min: value }); } return this; }; /** * 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 (value) { var msg = message || MongooseError.messages.Date.max; if (typeof msg === 'string') { msg = msg.replace(/{MAX}/, value === Date.now ? 'Date.now()' : value.toString()); } var _this = this; this.validators.push({ validator: this.maxValidator = function (val) { var _value = value; if (typeof _value === 'function' && _value !== Date.now) { _value = _value.call(this); } var max = _value === Date.now ? _value() : _this.cast(_value); return val === null || val.valueOf() <= max.valueOf(); }, message: msg, type: 'max', max: value }); } return this; }; /** * Casts to date * * @param {Object} value to cast * @api private */ SchemaDate.prototype.cast = function (value) { var castDate; if (typeof this._castFunction === 'function') { castDate = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castDate = this.constructor.cast(); } else { castDate = SchemaDate.cast(); } try { return castDate(value); } catch (error) { throw new CastError('date', value, this.path, error, this); } }; /*! * Date Query casting. * * @api private */ function handleSingle(val) { return this.cast(val); } SchemaDate.prototype.$conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle }); /** * Casts contents for queries. * * @param {String} $conditional * @param {any} [value] * @api private */ SchemaDate.prototype.castForQuery = function ($conditional, val) { if (arguments.length !== 2) { return this._castForQuery($conditional); } var handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional + ' with Date.'); } return handler.call(this, val); }; /*! * Module exports. */ module.exports = SchemaDate; /***/ }), /***/ 6621: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ var SchemaType = __webpack_require__(4289); var CastError = SchemaType.CastError; var castDecimal128 = __webpack_require__(6209); var utils = __webpack_require__(6872); var isBsonType = __webpack_require__(1563); /** * 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 */ Decimal128._defaultCaster = function (v) { if (v != null && !isBsonType(v, 'Decimal128')) { throw new Error(); } return v; }; /*! * ignore */ Decimal128._checkRequired = function (v) { return isBsonType(v, 'Decimal128'); }; /** * 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. var _checkRequired = typeof this.constructor.checkRequired === 'function' ? this.constructor.checkRequired() : Decimal128.checkRequired(); return _checkRequired(value); }; /** * 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 (isBsonType(value, 'Decimal128')) { return value; } return this._castRef(value, doc, init); } var castDecimal128; if (typeof this._castFunction === 'function') { castDecimal128 = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castDecimal128 = this.constructor.cast(); } else { castDecimal128 = Decimal128.cast(); } try { return castDecimal128(value); } catch (error) { throw new CastError('Decimal128', value, this.path, error, this); } }; /*! * ignore */ function handleSingle(val) { return this.cast(val); } Decimal128.prototype.$conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle }); /*! * Module exports. */ module.exports = Decimal128; /***/ }), /***/ 4504: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ var ArrayType = __webpack_require__(94); var CastError = __webpack_require__(1795); var EventEmitter = (__webpack_require__(9620).EventEmitter); var SchemaDocumentArrayOptions = __webpack_require__(887); var SchemaType = __webpack_require__(4289); var SubdocumentPath = __webpack_require__(3617); var discriminator = __webpack_require__(9181); var handleIdOption = __webpack_require__(9691); var handleSpreadDoc = __webpack_require__(719); var utils = __webpack_require__(6872); var getConstructor = __webpack_require__(8413); var arrayAtomicsSymbol = (__webpack_require__(8770).arrayAtomicsSymbol); var arrayPathSymbol = (__webpack_require__(8770).arrayPathSymbol); var documentArrayParent = (__webpack_require__(8770).documentArrayParent); var MongooseDocumentArray; var Subdocument; /** * SubdocsArray SchemaType constructor * * @param {String} key * @param {Schema} schema * @param {Object} options * @param {Object} schemaOptions * @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); } var 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; var fn = this.defaultValue; if (!('defaultValue' in this) || fn !== void 0) { this["default"](function () { var 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; }); } var parentSchemaType = this; this.$embeddedSchemaType = new SchemaType(key + '.$', { required: this && this.schemaOptions && this.schemaOptions.required || false }); this.$embeddedSchemaType.cast = function (value, doc, init) { return parentSchemaType.cast(value, doc, init)[0]; }; this.$embeddedSchemaType.doValidate = function (value, fn, scope, options) { var Constructor = getConstructor(this.caster, value); if (value && !(value instanceof Constructor)) { value = new Constructor(value, scope, null, null, options && options.index != null ? options.index : null); } return SubdocumentPath.prototype.doValidate.call(this, value, fn, scope, options); }; 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 = __webpack_require__(1568)); // compile an embedded document for this schema function EmbeddedDocument(_value, parentArray) { Subdocument.apply(this, arguments); if (parentArray == null || parentArray.getArrayParent() == null) { return; } this.$session(parentArray.getArrayParent().$session()); } schema._preCompile(); var 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 (var i in schema.methods) { EmbeddedDocument.prototype[i] = schema.methods[i]; } // apply statics for (var _i in schema.statics) { EmbeddedDocument[_i] = schema.statics[_i]; } for (var _i2 in EventEmitter.prototype) { EmbeddedDocument[_i2] = EventEmitter.prototype[_i2]; } 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 {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 */ DocumentArrayPath.prototype.discriminator = function (name, schema, options) { if (typeof name === 'function') { name = utils.getFunctionName(name); } options = options || {}; var tiedValue = utils.isPOJO(options) ? options.value : options; var clone = typeof options.clone === 'boolean' ? options.clone : true; if (schema.instanceOfSchema && clone) { schema = schema.clone(); } schema = discriminator(this.casterConstructor, name, schema, tiedValue); var EmbeddedDocument = _createConstructor(schema, null, this.casterConstructor); EmbeddedDocument.baseCasterConstructor = this.casterConstructor; try { Object.defineProperty(EmbeddedDocument, 'name', { value: name }); } catch (error) {// Ignore error, only happens on old versions of node } this.casterConstructor.discriminators[name] = EmbeddedDocument; return this.casterConstructor.discriminators[name]; }; /** * Performs local validations first, then validations on each embedded doc * * @api private */ DocumentArrayPath.prototype.doValidate = function (array, fn, scope, options) { // lazy load MongooseDocumentArray || (MongooseDocumentArray = __webpack_require__(6077)); var _this = this; try { SchemaType.prototype.doValidate.call(this, array, cb, scope); } catch (err) { return fn(err); } function cb(err) { if (err) { return fn(err); } var count = array && array.length; var error; if (!count) { return fn(); } if (options && options.updateValidator) { return fn(); } if (!utils.isMongooseDocumentArray(array)) { array = new MongooseDocumentArray(array, _this.path, scope); } // handle sparse arrays, do not use array.forEach which does not // iterate over sparse elements yet reports array.length including // them :( function callback(err) { if (err != null) { error = err; } --count || fn(error); } for (var i = 0, len = count; i < len; ++i) { // sidestep sparse entries var doc = array[i]; if (doc == null) { --count || fn(error); continue; } // 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)) { var Constructor = getConstructor(_this.casterConstructor, array[i]); doc = array[i] = new Constructor(doc, array, undefined, undefined, i); } if (options != null && options.validateModifiedOnly && !doc.$isModified()) { --count || fn(error); continue; } 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 */ DocumentArrayPath.prototype.doValidateSync = function (array, scope, options) { var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope); if (schemaTypeError != null) { return schemaTypeError; } var count = array && array.length; var resultError = null; if (!count) { return; } // handle sparse arrays, do not use array.forEach which does not // iterate over sparse elements yet reports array.length including // them :( for (var i = 0, len = count; i < len; ++i) { // sidestep sparse entries var doc = array[i]; if (!doc) { continue; } // 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)) { var Constructor = getConstructor(this.casterConstructor, array[i]); doc = array[i] = new Constructor(doc, array, undefined, undefined, i); } if (options != null && options.validateModifiedOnly && !doc.$isModified()) { continue; } var subdocValidateError = doc.validateSync(); if (subdocValidateError && resultError == null) { resultError = subdocValidateError; } } return resultError; }; /*! * ignore */ DocumentArrayPath.prototype.getDefault = function (scope) { var ret = typeof this.defaultValue === 'function' ? this.defaultValue.call(scope) : this.defaultValue; if (ret == null) { return ret; } // lazy load MongooseDocumentArray || (MongooseDocumentArray = __webpack_require__(6077)); if (!Array.isArray(ret)) { ret = [ret]; } ret = new MongooseDocumentArray(ret, this.path, scope); for (var i = 0; i < ret.length; ++i) { var Constructor = getConstructor(this.casterConstructor, ret[i]); var _subdoc = new Constructor({}, ret, undefined, undefined, i); _subdoc.$init(ret[i]); _subdoc.isNew = true; // 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 = {}; ret[i] = _subdoc; } return ret; }; var _toObjectOptions = Object.freeze({ transform: false, virtuals: false }); var initDocumentOptions = Object.freeze({ skipId: true, willInit: true }); /** * 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 = __webpack_require__(6077)); // 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; } var selected; var subdoc; options = options || {}; if (!Array.isArray(value)) { if (!init && !DocumentArrayPath.options.castNonArrays) { throw new CastError('DocumentArray', 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); } // We need to create a new array, otherwise change tracking will // update the old doc (gh-4449) if (!options.skipDocumentArrayCast || utils.isMongooseDocumentArray(value)) { value = new MongooseDocumentArray(value, this.path, doc); } if (prev != null) { value[arrayAtomicsSymbol] = prev[arrayAtomicsSymbol] || {}; } if (options.arrayPathIndex != null) { value[arrayPathSymbol] = this.path + '.' + options.arrayPathIndex; } var rawArray = utils.isMongooseDocumentArray(value) ? value.__array : value; var len = rawArray.length; for (var i = 0; i < len; ++i) { if (!rawArray[i]) { continue; } var Constructor = getConstructor(this.casterConstructor, rawArray[i]); // Check if the document has a different schema (re gh-3701) if (rawArray[i].$__ != null && !(rawArray[i] instanceof Constructor)) { var spreadDoc = handleSpreadDoc(rawArray[i], true); if (rawArray[i] !== spreadDoc) { rawArray[i] = spreadDoc; } else { 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 }); } } if (rawArray[i] instanceof Subdocument) { if (rawArray[i][documentArrayParent] !== doc) { if (init) { var _subdoc2 = new Constructor(null, value, initDocumentOptions, selected, i); rawArray[i] = _subdoc2.$init(rawArray[i]); } else { var _subdoc3 = new Constructor(rawArray[i], value, undefined, undefined, i); rawArray[i] = _subdoc3; } } // 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; } 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 (prev && subdoc && utils.deepEqual(subdoc.toObject(_toObjectOptions), 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) { throw new CastError('embedded', rawArray[i], value[arrayPathSymbol], error, this); } } } } } return value; }; /*! * ignore */ DocumentArrayPath.prototype.clone = function () { var options = Object.assign({}, this.options); var 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; }; /*! * ignore */ DocumentArrayPath.prototype.applyGetters = function (value, scope) { return SchemaType.prototype.applyGetters.call(this, value, scope); }; /*! * 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; } var path = array.path + '.'; var keys = Object.keys(fields); var i = keys.length; var selected = {}; var hasKeys; var key; var sub; while (i--) { key = keys[i]; if (key.startsWith(path)) { sub = key.substring(path.length); if (sub === '$') { continue; } if (sub.startsWith('$.')) { sub = sub.substring(2); } hasKeys || (hasKeys = true); selected[sub] = fields[key]; } } return hasKeys && selected || undefined; } /** * 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 */ DocumentArrayPath.defaultOptions = {}; DocumentArrayPath.set = SchemaType.set; /*! * Module exports. */ module.exports = DocumentArrayPath; /***/ }), /***/ 5251: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /*! * Module exports. */ exports.String = __webpack_require__(6542); exports.Number = __webpack_require__(1751); exports.Boolean = __webpack_require__(6470); exports.DocumentArray = __webpack_require__(4504); exports.Subdocument = __webpack_require__(3617); exports.Array = __webpack_require__(94); exports.Buffer = __webpack_require__(8800); exports.Date = __webpack_require__(6535); exports.ObjectId = __webpack_require__(7116); exports.Mixed = __webpack_require__(3861); exports.Decimal128 = exports.Decimal = __webpack_require__(6621); exports.Map = __webpack_require__(71); // alias exports.Oid = exports.ObjectId; exports.Object = exports.Mixed; exports.Bool = exports.Boolean; exports.ObjectID = exports.ObjectId; /***/ }), /***/ 71: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * ignore */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var MongooseMap = __webpack_require__(3828); var SchemaMapOptions = __webpack_require__(8227); var SchemaType = __webpack_require__(4289); /*! * ignore */ var Map = /*#__PURE__*/function (_SchemaType) { _inherits(Map, _SchemaType); var _super = _createSuper(Map); function Map(key, options) { var _this; _classCallCheck(this, Map); _this = _super.call(this, key, options, 'Map'); _this.$isSchemaMap = true; return _this; } _createClass(Map, [{ key: "set", value: function set(option, value) { return SchemaType.set(option, value); } }, { key: "cast", value: function cast(val, doc, init) { if (val instanceof MongooseMap) { return val; } var path = this.path; if (init) { var map = new MongooseMap({}, path, doc, this.$__schemaType); if (val instanceof __webpack_require__.g.Map) { var _iterator = _createForOfIteratorHelper(val.keys()), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var key = _step.value; var _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); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } else { for (var _i = 0, _Object$keys = Object.keys(val); _i < _Object$keys.length; _i++) { var _key = _Object$keys[_i]; var _val2 = val[_key]; if (_val2 == null) { _val2 = map.$__schemaType._castNullish(_val2); } else { _val2 = map.$__schemaType.cast(_val2, doc, true, null, { path: path + '.' + _key }); } map.$init(_key, _val2); } } return map; } return new MongooseMap(val, path, doc, this.$__schemaType); } }, { key: "clone", value: function clone() { var schematype = _get(_getPrototypeOf(Map.prototype), "clone", this).call(this); if (this.$__schemaType != null) { schematype.$__schemaType = this.$__schemaType.clone(); } return schematype; } }]); return Map; }(SchemaType); /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ Map.schemaName = 'Map'; Map.prototype.OptionsConstructor = SchemaMapOptions; Map.defaultOptions = {}; module.exports = Map; /***/ }), /***/ 3861: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ var SchemaType = __webpack_require__(4289); var symbols = __webpack_require__(8107); var isObject = __webpack_require__(5721); var utils = __webpack_require__(6872); /** * Mixed SchemaType constructor. * * @param {String} path * @param {Object} options * @inherits SchemaType * @api public */ function Mixed(path, options) { if (options && options["default"]) { var 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 {}; }; } } 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; }; /** * Casts contents for queries. * * @param {String} $cond * @param {any} [val] * @api private */ Mixed.prototype.castForQuery = function ($cond, val) { if (arguments.length === 2) { return val; } return $cond; }; /*! * Module exports. */ module.exports = Mixed; /***/ }), /***/ 1751: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module requirements. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var MongooseError = __webpack_require__(4888); var SchemaNumberOptions = __webpack_require__(8491); var SchemaType = __webpack_require__(4289); var castNumber = __webpack_require__(3065); var handleBitwiseOperator = __webpack_require__(4282); var utils = __webpack_require__(6872); var 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; }; /*! * ignore */ SchemaNumber._defaultCaster = function (v) { if (typeof v !== 'number') { throw new Error(); } return v; }; /** * 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 = function (v) { return 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 (_typeof(value) === 'object' && SchemaType._isRef(this, value, doc, true)) { return value != null; } // `require('util').inherits()` does **not** copy static properties, and // plugins like mongoose-float use `inherits()` for pre-ES6. var _checkRequired = typeof this.constructor.checkRequired === 'function' ? this.constructor.checkRequired() : SchemaNumber.checkRequired(); return _checkRequired(value); }; /** * 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) { var 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; }; /** * 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) { var 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 }); } return 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 */ 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)) { var 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 (utils.isPOJO(values)) { values = Object.values(values); } message = message || MongooseError.messages.Number["enum"]; } message = message == null ? MongooseError.messages.Number["enum"] : message; this.enumValidator = function (v) { return v == null || values.indexOf(v) !== -1; }; this.validators.push({ validator: this.enumValidator, message: message, type: 'enum', enumValues: values }); return this; }; /** * 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 (typeof value !== 'number' && SchemaType._isRef(this, value, doc, init)) { if (value == null || utils.isNonBuiltinObject(value)) { return this._castRef(value, doc, init); } } var val = value && typeof value._id !== 'undefined' ? value._id : // documents value; var castNumber; if (typeof this._castFunction === 'function') { castNumber = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castNumber = this.constructor.cast(); } else { castNumber = SchemaNumber.cast(); } try { return castNumber(val); } catch (err) { throw new CastError('Number', val, this.path, err, this); } }; /*! * ignore */ function handleSingle(val) { return this.cast(val); } function handleArray(val) { var _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 }); /** * Casts contents for queries. * * @param {String} $conditional * @param {any} [value] * @api private */ SchemaNumber.prototype.castForQuery = function ($conditional, val) { var 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; }; /*! * Module exports. */ module.exports = SchemaNumber; /***/ }), /***/ 7116: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ var SchemaObjectIdOptions = __webpack_require__(8172); var SchemaType = __webpack_require__(4289); var castObjectId = __webpack_require__(4731); var getConstructorName = __webpack_require__(1981); var oid = __webpack_require__(6079); var isBsonType = __webpack_require__(1563); var utils = __webpack_require__(6872); var CastError = SchemaType.CastError; var Document; /** * ObjectId SchemaType constructor. * * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function ObjectId(key, options) { var isKeyHexStr = typeof key === 'string' && key.length === 24 && /^[a-f0-9]+$/i.test(key); var 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'); } /** * 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); } return this; }; /*! * ignore */ ObjectId._checkRequired = function (v) { return isBsonType(v, 'ObjectID'); }; /*! * 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 */ ObjectId._defaultCaster = function (v) { if (!isBsonType(v, 'ObjectID')) { throw new Error(v + ' is not an instance of ObjectId'); } return v; }; /** * 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. var _checkRequired = typeof this.constructor.checkRequired === 'function' ? this.constructor.checkRequired() : ObjectId.checkRequired(); return _checkRequired(value); }; /** * 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 (!isBsonType(value, 'ObjectID') && SchemaType._isRef(this, value, doc, init)) { // wait! we may need to cast this to a document if ((getConstructorName(value) || '').toLowerCase() === 'objectid') { return new oid(value.toHexString()); } if (value == null || utils.isNonBuiltinObject(value)) { return this._castRef(value, doc, init); } } var castObjectId; if (typeof this._castFunction === 'function') { castObjectId = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castObjectId = this.constructor.cast(); } else { castObjectId = ObjectId.cast(); } try { return castObjectId(value); } catch (error) { throw new CastError('ObjectId', value, this.path, error, this); } }; /*! * ignore */ function handleSingle(val) { return this.cast(val); } ObjectId.prototype.$conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle }); /*! * ignore */ function defaultId() { return new oid(); } defaultId.$runBeforeSetters = true; function resetId(v) { Document || (Document = __webpack_require__(8727)); if (this instanceof Document) { if (v === void 0) { var _v = new oid(); return _v; } } return v; } /*! * Module exports. */ module.exports = ObjectId; /***/ }), /***/ 4282: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; /*! * Module requirements. */ var CastError = __webpack_require__(1795); /*! * ignore */ function handleBitwiseOperator(val) { var _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); } /*! * ignore */ function _castNumber(path, num) { var v = Number(num); if (isNaN(v)) { throw new CastError('number', num, path); } return v; } module.exports = handleBitwiseOperator; /***/ }), /***/ 8702: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var castBoolean = __webpack_require__(6670); /*! * ignore */ module.exports = function (val) { var path = this != null ? this.path : null; return castBoolean(val, path); }; /***/ }), /***/ 5008: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /*! * Module requirements. */ var castArraysOfNumbers = (__webpack_require__(1521)/* .castArraysOfNumbers */ .i); var castToNumber = (__webpack_require__(1521)/* .castToNumber */ .W); /*! * ignore */ exports.cast$geoIntersects = cast$geoIntersects; exports.cast$near = cast$near; exports.cast$within = cast$within; function cast$near(val) { var SchemaArray = __webpack_require__(94); if (Array.isArray(val)) { castArraysOfNumbers(val, this); return val; } _castMinMaxDistance(this, val); if (val && val.$geometry) { return cast$geometry(val, this); } if (!Array.isArray(val)) { throw new TypeError('$near must be either an array or an object ' + 'with a $geometry property'); } 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; } _castMinMaxDistance(self, val); return val; } function cast$within(val) { var _this = this; _castMinMaxDistance(this, val); if (val.$box || val.$polygon) { var type = val.$box ? '$box' : '$polygon'; val[type].forEach(function (arr) { if (!Array.isArray(arr)) { var msg = 'Invalid $within $box argument. ' + 'Expected an array, received ' + arr; throw new TypeError(msg); } arr.forEach(function (v, i) { arr[i] = castToNumber.call(_this, v); }); }); } else if (val.$center || val.$centerSphere) { var _type = val.$center ? '$center' : '$centerSphere'; val[_type].forEach(function (item, i) { if (Array.isArray(item)) { item.forEach(function (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 val; } function cast$geoIntersects(val) { var geo = val.$geometry; if (!geo) { return; } 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); } } /***/ }), /***/ 1521: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /*! * Module requirements. */ var SchemaNumber = __webpack_require__(1751); /*! * @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); } }); } /***/ }), /***/ 6495: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var CastError = __webpack_require__(1795); var castBoolean = __webpack_require__(6670); var castString = __webpack_require__(2417); /*! * 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'); } return val; }; /***/ }), /***/ 3053: /***/ ((module) => { "use strict"; /*! * ignore */ module.exports = function (val) { if (Array.isArray(val)) { if (!val.every(function (v) { return typeof v === 'number' || typeof v === 'string'; })) { throw new Error('$type array values must be strings or numbers'); } return val; } if (typeof val !== 'number' && typeof val !== 'string') { throw new Error('$type parameter must be number, string, or array of numbers and strings'); } return val; }; /***/ }), /***/ 6542: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var SchemaType = __webpack_require__(4289); var MongooseError = __webpack_require__(4888); var SchemaStringOptions = __webpack_require__(3209); var castString = __webpack_require__(2417); var utils = __webpack_require__(6872); var isBsonType = __webpack_require__(1563); var 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; }; /*! * ignore */ SchemaString._defaultCaster = function (v) { if (v != null && typeof v !== 'string') { throw new Error(); } return v; }; /** * 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 = function (v) { return (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; } var values; var errorMessage; 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"]; } var _iterator = _createForOfIteratorHelper(values), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var value = _step.value; if (value !== undefined) { this.enumValues.push(this.cast(value)); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } var 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](https://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) { var _this2 = this; if (arguments.length > 0 && !shouldApply) { return this; } return this.set(function (v) { if (typeof v !== 'string') { v = _this2.cast(v); } if (v) { return v.toLowerCase(); } return v; }); }; /** * Adds an uppercase [setter](https://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) { var _this3 = this; if (arguments.length > 0 && !shouldApply) { return this; } return this.set(function (v) { if (typeof v !== 'string') { v = _this3.cast(v); } if (v) { return v.toUpperCase(); } return v; }); }; /** * Adds a trim [setter](https://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 */ SchemaString.prototype.trim = function (shouldTrim) { var _this4 = this; if (arguments.length > 0 && !shouldTrim) { return this; } return this.set(function (v) { if (typeof v !== 'string') { v = _this4.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) { var 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 }); } 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) { var 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 this; }; 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 var msg = message || MongooseError.messages.String.match; var matchValidator = function matchValidator(v) { if (!regExp) { return false; } // In case RegExp happens to have `/g` flag set, we need to reset the // `lastIndex`, otherwise `match` will intermittently fail. regExp.lastIndex = 0; var ret = v != null && v !== '' ? regExp.test(v) : true; return ret; }; 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 (_typeof(value) === 'object' && SchemaType._isRef(this, value, doc, true)) { return value != null; } // `require('util').inherits()` does **not** copy static properties, and // plugins like mongoose-float use `inherits()` for pre-ES6. var _checkRequired = typeof this.constructor.checkRequired === 'function' ? this.constructor.checkRequired() : SchemaString.checkRequired(); return _checkRequired(value); }; /** * Casts to String * * @api private */ SchemaString.prototype.cast = function (value, doc, init) { if (typeof value !== 'string' && SchemaType._isRef(this, value, doc, init)) { return this._castRef(value, doc, init); } var castString; if (typeof this._castFunction === 'function') { castString = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castString = this.constructor.cast(); } else { castString = SchemaString.cast(); } try { return castString(value); } catch (error) { throw new CastError('string', value, this.path, null, this); } }; /*! * ignore */ function handleSingle(val) { return this.castForQuery(val); } /*! * ignore */ function handleArray(val) { var _this = this; if (!Array.isArray(val)) { return [this.castForQuery(val)]; } return val.map(function (m) { return _this.castForQuery(m); }); } /*! * ignore */ function handleSingleNoSetters(val) { if (val == null) { return this._castNullish(val); } return this.cast(val, this); } var $conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { $all: handleArray, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle, $options: handleSingleNoSetters, $regex: function handle$regex(val) { if (Object.prototype.toString.call(val) === '[object RegExp]') { return val; } return handleSingleNoSetters.call(this, val); }, $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 */ SchemaString.prototype.castForQuery = function ($conditional, val) { var 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]' || isBsonType(val, 'BSONRegExp')) { return val; } return this._castForQuery(val); }; /*! * Module exports. */ module.exports = SchemaString; /***/ }), /***/ 8107: /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.schemaMixedSymbol = Symbol["for"]('mongoose:schema_mixed'); exports.builtInMiddleware = Symbol["for"]('mongoose:built-in-middleware'); /***/ }), /***/ 4289: /***/ ((module, exports, __webpack_require__) => { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; /*! * Module dependencies. */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var MongooseError = __webpack_require__(4888); var SchemaTypeOptions = __webpack_require__(1764); var $exists = __webpack_require__(8702); var $type = __webpack_require__(3053); var handleImmutable = __webpack_require__(8828); var isAsyncFunction = __webpack_require__(8857); var isSimpleValidator = __webpack_require__(9130); var immediate = __webpack_require__(1490); var schemaTypeSymbol = (__webpack_require__(8770).schemaTypeSymbol); var utils = __webpack_require__(6872); var validatorErrorSymbol = (__webpack_require__(8770).validatorErrorSymbol); var documentIsModified = (__webpack_require__(8770).documentIsModified); var populateModelSymbol = (__webpack_require__(8770).populateModelSymbol); var CastError = MongooseError.CastError; var ValidatorError = MongooseError.ValidatorError; var setOptionsForDefaults = { _skipMarkModified: true }; /** * 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(); options = options || {}; var defaultOptions = this.constructor.defaultOptions || {}; var defaultOptionsKeys = Object.keys(defaultOptions); for (var _i = 0, _defaultOptionsKeys = defaultOptionsKeys; _i < _defaultOptionsKeys.length; _i++) { var option = _defaultOptionsKeys[_i]; if (defaultOptions.hasOwnProperty(option) && !options.hasOwnProperty(option)) { options[option] = defaultOptions[option]; } } if (options.select == null) { delete options.select; } var Options = this.OptionsConstructor || SchemaTypeOptions; this.options = new Options(options); this._index = null; if (utils.hasUserDefinedProperty(this.options, 'immutable')) { this.$immutable = this.options.immutable; handleImmutable(this); } var keys = Object.keys(this.options); for (var _i2 = 0, _keys = keys; _i2 < _keys.length; _i2++) { var prop = _keys[_i2]; 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) { var 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; } var val = options[prop]; // Special case so we don't screw up array defaults, see gh-5780 if (prop === 'default') { this["default"](val); continue; } var opts = Array.isArray(val) ? val : [val]; this[prop].apply(this, opts); } } 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. */ SchemaType.prototype.OptionsConstructor = SchemaTypeOptions; /** * The path to this SchemaType in a Schema. * * #### Example: * const schema = new Schema({ name: String }); * schema.path('name').path; // 'name' * * @property path * @api public * @memberOf SchemaType */ SchemaType.prototype.path; /** * The validators that Mongoose should run to validate properties at this SchemaType's path. * * #### Example: * const schema = new Schema({ name: { type: String, required: true } }); * schema.path('name').validators.length; // 1, the `required` validator * * @property validators * @api public * @memberOf SchemaType */ SchemaType.prototype.validators; /** * True if this SchemaType has a required validator. False otherwise. * * #### Example: * const schema = new Schema({ name: { type: String, required: true } }); * schema.path('name').isRequired; // true * * schema.path('name').required(false); * schema.path('name').isRequired; // false * * @property isRequired * @api public * @memberOf SchemaType */ SchemaType.prototype.validators; /*! * ignore */ SchemaType.prototype.splitPath = function () { if (this._presplitPath != null) { return this._presplitPath; } if (this.path == null) { return undefined; } this._presplitPath = this.path.indexOf('.') === -1 ? [this.path] : this.path.split('.'); return this._presplitPath; }; /** * 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 = function caster(v) { return v; }; } this._cast = caster; return this._cast; }; /** * 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 || function (v) { return v; }; } this._castFunction = caster; return this._castFunction; }; /** * 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'); }; /** * 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; }; /** * 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); }; /** * 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; } if (val != null && val.instanceOfSchema) { throw new MongooseError('Cannot set default value of path `' + this.path + '` to a mongoose Schema instance.'); } this.defaultValue = val; return this.defaultValue; } else if (arguments.length > 1) { this.defaultValue = Array.prototype.slice.call(arguments); } return this.defaultValue; }; /** * 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; }; /** * 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.options.hasOwnProperty('index') && bool === false) { return this; } if (this._index == null || this._index === true) { this._index = {}; } else if (typeof this._index === 'string') { this._index = { type: this._index }; } this._index.unique = bool; 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 */ 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'); } if (!this.options.hasOwnProperty('index') && bool === false) { 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 }; } this._index.text = bool; 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 */ 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'); } if (!this.options.hasOwnProperty('index') && bool === false) { return this; } if (this._index == null || typeof this._index === 'boolean') { this._index = {}; } else if (typeof this._index === 'string') { this._index = { type: this._index }; } this._index.sparse = bool; return this; }; /** * 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); 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 */ SchemaType.prototype.transform = function (fn) { this.options.transform = fn; return this; }; /** * Adds a setter to this schematype. * * #### Example: * * ```javascript * 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. * * ```javascript * 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._ * * ```javascript * 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. * * ```javascript * 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 */ SchemaType.prototype.set = function (fn) { if (typeof fn !== 'function') { throw new TypeError('A setter must be a function.'); } this.setters.push(fn); return this; }; /** * 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; }; /** * 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(v) { 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') { var properties; if (typeof message === 'function') { properties = { validator: obj, message: message }; properties.type = type || 'user defined'; } else if (message instanceof Object && !type) { properties = isSimpleValidator(message) ? Object.assign({}, message) : 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 }; } this.validators.push(properties); return this; } var i; var length; var arg; for (i = 0, length = arguments.length; i < length; i++) { arg = arguments[i]; if (!utils.isPOJO(arg)) { var msg = 'Invalid validator. Received (' + _typeof(arg) + ') ' + arg + '. See https://mongoosejs.com/docs/api.html#schematype_SchemaType-validate'; throw new Error(msg); } this.validate(arg.validator, arg); } return this; }; /** * 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) { var 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; } if (_typeof(required) === 'object') { customOptions = required; message = customOptions.message || message; required = required.isRequired; } if (required === false) { this.validators = this.validators.filter(function (v) { return v.validator !== this.requiredValidator; }, this); this.isRequired = false; delete this.originalRequiredValue; return this; } var _this = this; this.isRequired = true; this.requiredValidator = function (v) { var cachedRequired = this && this.$__ && this.$__.cachedRequired; // no validation when this path wasn't selected in the query. if (cachedRequired != null && !this.$__isSelected(_this.path) && !this[documentIsModified](_this.path)) { return true; } // `$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) { var 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; } return _this.checkRequired(v, this); }; this.originalRequiredValue = required; if (typeof required === 'string') { message = required; required = undefined; } var msg = message || MongooseError.messages.general.required; this.validators.unshift(Object.assign({}, customOptions, { validator: this.requiredValidator, message: msg, type: 'required' })); return this; }; /** * 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; }; /** * Gets the default value * * @param {Object} scope the scope which callback are executed * @param {Boolean} init * @api private */ SchemaType.prototype.getDefault = function (scope, init) { var 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; } if (ret !== null && ret !== undefined) { if (_typeof(ret) === 'object' && (!this.options || !this.options.shared)) { ret = utils.clone(ret); } var casted = this.applySetters(ret, scope, init, undefined, setOptionsForDefaults); if (casted && !Array.isArray(casted) && casted.$isSingleNested) { casted.$__parent = scope; } return casted; } return ret; }; /*! * Applies setters without casting * * @api private */ SchemaType.prototype._applySetters = function (value, scope, init, priorVal, options) { var v = value; if (init) { return v; } var setters = this.setters; for (var i = setters.length - 1; i >= 0; i--) { v = setters[i].call(scope, v, priorVal, this, options); } return v; }; /*! * ignore */ 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) { var 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; }; /** * Applies getters to a value * * @param {Object} value * @param {Object} scope * @api private */ SchemaType.prototype.applyGetters = function (value, scope) { var v = value; var getters = this.getters; var len = getters.length; if (len === 0) { return v; } for (var i = 0; i < len; ++i) { v = getters[i].call(scope, v, this); } return v; }; /** * 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; }; /** * 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) { var _this2 = this; var err = false; var path = this.path; // Avoid non-object `validators` var validators = this.validators.filter(function (v) { return _typeof(v) === 'object' && v !== null; }); var count = validators.length; if (!count) { return fn(null); } var _loop = function _loop(i, len) { if (err) { return "break"; } var v = validators[i]; var validator = v.validator; var ok = void 0; var validatorProperties = isSimpleValidator(v) ? Object.assign({}, v) : utils.clone(v); validatorProperties.path = options && options.path ? options.path : path; validatorProperties.value = value; if (validator instanceof RegExp) { validate(validator.test(value), validatorProperties); return "continue"; } if (typeof validator !== 'function') { return "continue"; } if (value === undefined && validator !== _this2.requiredValidator) { validate(true, validatorProperties); return "continue"; } 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; } } 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); } }; for (var i = 0, len = validators.length; i < len; ++i) { var _ret = _loop(i, len); if (_ret === "break") break; if (_ret === "continue") continue; } function validate(ok, validatorProperties) { if (err) { return; } if (ok === undefined || ok) { if (--count <= 0) { immediate(function () { fn(null); }); } } else { var ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; err = new ErrorConstructor(validatorProperties); err[validatorErrorSymbol] = true; immediate(function () { fn(err); }); } } }; function _validate(ok, validatorProperties) { if (ok !== undefined && !ok) { var ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; var err = new ErrorConstructor(validatorProperties); err[validatorErrorSymbol] = true; return err; } } /** * 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 */ SchemaType.prototype.doValidateSync = function (value, scope, options) { var path = this.path; var count = this.validators.length; if (!count) { return null; } var validators = this.validators; if (value === void 0) { if (this.validators.length !== 0 && this.validators[0].type === 'required') { validators = [this.validators[0]]; } else { return null; } } var err = null; var i = 0; var len = validators.length; for (i = 0; i < len; ++i) { var v = validators[i]; if (v === null || _typeof(v) !== 'object') { continue; } var validator = v.validator; var validatorProperties = isSimpleValidator(v) ? Object.assign({}, v) : utils.clone(v); validatorProperties.path = options && options.path ? options.path : path; validatorProperties.value = value; var ok = false; // Skip any explicit async validators. Validators that return a promise // will still run, but won't trigger any errors. if (isAsyncFunction(validator)) { continue; } if (validator instanceof RegExp) { err = _validate(validator.test(value), validatorProperties); continue; } if (typeof validator !== 'function') { continue; } 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') { continue; } err = _validate(ok, validatorProperties); if (err) { break; } } return err; }; /** * 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 var 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 var path = doc.$__fullPath(self.path, true); var owner = doc.ownerDocument(); ref = path != null && 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; } return init; } return false; }; /*! * ignore */ SchemaType.prototype._castRef = function _castRef(value, doc, init) { if (value == null) { return value; } if (value.$__ != null) { value.$__.wasPopulated = value.$__.wasPopulated || true; return value; } // 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); } // Handle the case where user directly sets a populated // path to a plain object; cast to the Model used in // the population query. var path = doc.$__fullPath(this.path, true); var owner = doc.ownerDocument(); var pop = owner.$populated(path, true); var 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 ret; }; /*! * ignore */ function handleSingle(val) { return this.castForQuery(val); } /*! * ignore */ function handleArray(val) { var _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 */ function handle$in(val) { var _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); }); } /*! * ignore */ SchemaType.prototype.$conditionalHandlers = { $all: handleArray, $eq: handleSingle, $in: handle$in, $ne: handleSingle, $nin: handle$in, $exists: $exists, $type: $type }; /*! * Wraps `castForQuery` to handle context */ SchemaType.prototype.castForQueryWrapper = function (params) { this.$$context = params.context; if ('$conditional' in params) { var _ret2 = this.castForQuery(params.$conditional, params.val); this.$$context = null; return _ret2; } if (params.$skipQueryCastForUpdate || params.$applySetters) { var _ret3 = this._castForQuery(params.val); this.$$context = null; return _ret3; } var ret = this.castForQuery(params.val); this.$$context = null; return ret; }; /** * 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) { var 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); }; /*! * Internal switch for runSetters * * @api private */ SchemaType.prototype._castForQuery = function (val) { return this.applySetters(val, this.$$context); }; /** * 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; }; /** * Default check for if this path satisfies the `required` validator. * * @param {any} val * @api private */ SchemaType.prototype.checkRequired = function (val) { return val != null; }; /*! * ignore */ SchemaType.prototype.clone = function () { var options = Object.assign({}, this.options); var 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; }; /*! * Module exports. */ module.exports = exports = SchemaType; exports.CastError = CastError; exports.ValidatorError = ValidatorError; /***/ }), /***/ 489: /***/ ((module, exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ var utils = __webpack_require__(6872); // eslint-disable-line no-unused-vars /*! * StateMachine represents a minimal `interface` for the * constructors it builds via StateMachine.ctor(...). * * @api private */ var 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 () { var states = Array.prototype.slice.call(arguments); var ctor = function ctor() { StateMachine.apply(this, arguments); this.paths = {}; this.states = {}; this.stateNames = states; var i = states.length, state; while (i--) { state = states[i]; this.states[state] = {}; } }; ctor.prototype = new StateMachine(); states.forEach(function (state) { // Changes the `path`'s state to `state`. ctor.prototype[state] = function (path) { this._changeState(path, state); }; }); return ctor; }; /*! * This function is wrapped by the state change functions: * * - `require(path)` * - `modify(path)` * - `init(path)` * * @api private */ StateMachine.prototype._changeState = function _changeState(path, nextState) { var prevBucket = this.states[this.paths[path]]; if (prevBucket) delete prevBucket[path]; this.paths[path] = nextState; this.states[nextState][path] = true; }; /*! * ignore */ StateMachine.prototype.clear = function clear(state) { var keys = Object.keys(this.states[state]); var i = keys.length; var path; while (i--) { path = keys[i]; delete this.states[state][path]; delete this.paths[path]; } }; /*! * ignore */ StateMachine.prototype.clearPath = function clearPath(path) { var state = this.paths[path]; if (!state) { return; } delete this.paths[path]; delete this.states[state][path]; }; /*! * 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 */ StateMachine.prototype.some = function some() { var _this = this; var 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 */ StateMachine.prototype._iter = function _iter(iterMethod) { return function () { var states = Array.prototype.slice.call(arguments); var callback = states.pop(); if (!states.length) states = this.stateNames; var _this = this; var 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); }); }; }; /*! * 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); }; /*! * 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); }; /***/ }), /***/ 1568: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ var EventEmitter = (__webpack_require__(9620).EventEmitter); var Subdocument = __webpack_require__(2591); var utils = __webpack_require__(6872); var documentArrayParent = (__webpack_require__(8770).documentArrayParent); /*! * 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 */ function ArraySubdocument(obj, parentArr, skipId, fields, index) { if (utils.isMongooseDocumentArray(parentArr)) { this.__parentArray = parentArr; this[documentArrayParent] = parentArr.$parent(); } else { this.__parentArray = undefined; this[documentArrayParent] = undefined; } this.$setIndex(index); this.$__parent = this[documentArrayParent]; Subdocument.call(this, obj, fields, this[documentArrayParent], skipId, { isNew: true }); } /*! * 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 (var i in EventEmitter.prototype) { ArraySubdocument[i] = EventEmitter.prototype[i]; } /*! * ignore */ ArraySubdocument.prototype.$setIndex = function (index) { this.__index = index; if (this.$__ != null && this.$__.validationError != null) { var keys = Object.keys(this.$__.validationError.errors); for (var _i = 0, _keys = keys; _i < _keys.length; _i++) { var key = _keys[_i]; this.invalidate(key, this.$__.validationError.errors[key]); } } }; /*! * ignore */ 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")`'); }; /*! * ignore */ ArraySubdocument.prototype.$__removeFromParent = function () { var _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 }); }; /** * 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 */ ArraySubdocument.prototype.$__fullPath = function (path, skipIndex) { if (this.__index == null) { return null; } if (!this.$__.fullPath) { this.ownerDocument(); } if (skipIndex) { return path ? this.$__.fullPath + '.' + path : this.$__.fullPath; } return path ? this.$__.fullPath + '.' + this.__index + '.' + path : this.$__.fullPath + '.' + this.__index; }; /*! * Given a path relative to this document, return the path relative * to the top-level document. */ 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; }; /*! * Returns this sub-documents parent document. */ ArraySubdocument.prototype.$parent = function () { return this[documentArrayParent]; }; /** * Returns this subdocument's parent array. * * #### Example: * * const Test = mongoose.model('Test', new Schema({ * docArr: [{ name: String }] * })); * const doc = new Test({ docArr: [{ name: 'test subdoc' }] }); * * doc.docArr[0].parentArray() === doc.docArr; // true * * @api public * @method parentArray * @returns DocumentArray */ ArraySubdocument.prototype.parentArray = function () { return this.__parentArray; }; /*! * Module exports. */ module.exports = ArraySubdocument; /***/ }), /***/ 6077: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var ArrayMethods = __webpack_require__(8075); var DocumentArrayMethods = __webpack_require__(9261); var Document = __webpack_require__(8727); var arrayAtomicsSymbol = (__webpack_require__(8770).arrayAtomicsSymbol); var arrayAtomicsBackupSymbol = (__webpack_require__(8770).arrayAtomicsBackupSymbol); var arrayParentSymbol = (__webpack_require__(8770).arrayParentSymbol); var arrayPathSymbol = (__webpack_require__(8770).arrayPathSymbol); var arraySchemaSymbol = (__webpack_require__(8770).arraySchemaSymbol); var _basePush = Array.prototype.push; var numberRE = /^\d+$/; /** * 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 https://bit.ly/f6CnZU */ function MongooseDocumentArray(values, path, doc) { var _internals; var __array = []; var internals = (_internals = {}, _defineProperty(_internals, arrayAtomicsSymbol, {}), _defineProperty(_internals, arrayAtomicsBackupSymbol, void 0), _defineProperty(_internals, arrayPathSymbol, path), _defineProperty(_internals, arraySchemaSymbol, void 0), _defineProperty(_internals, arrayParentSymbol, void 0), _internals); if (Array.isArray(values)) { if (values[arrayPathSymbol] === path && values[arrayParentSymbol] === doc) { internals[arrayAtomicsSymbol] = Object.assign({}, values[arrayAtomicsSymbol]); } values.forEach(function (v) { _basePush.call(__array, v); }); } internals[arrayPathSymbol] = path; internals.__array = __array; // 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; } } var proxy = new Proxy(__array, { get: function get(target, prop) { if (prop === 'isMongooseArray' || prop === 'isMongooseArrayProxy' || prop === 'isMongooseDocumentArray' || prop === 'isMongooseDocumentArrayProxy') { return true; } if (internals.hasOwnProperty(prop)) { return internals[prop]; } if (DocumentArrayMethods.hasOwnProperty(prop)) { return DocumentArrayMethods[prop]; } if (ArrayMethods.hasOwnProperty(prop)) { return ArrayMethods[prop]; } return __array[prop]; }, set: function set(target, prop, value) { if (typeof prop === 'string' && numberRE.test(prop)) { DocumentArrayMethods.set.call(proxy, prop, value, false); } else if (internals.hasOwnProperty(prop)) { internals[prop] = value; } else { __array[prop] = value; } return true; } }); return proxy; } /*! * Module exports. */ module.exports = MongooseDocumentArray; /***/ }), /***/ 1255: /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.isMongooseDocumentArray = function (mongooseDocumentArray) { return Array.isArray(mongooseDocumentArray) && mongooseDocumentArray.isMongooseDocumentArray; }; /***/ }), /***/ 9261: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var ArrayMethods = __webpack_require__(8075); var Document = __webpack_require__(8727); var castObjectId = __webpack_require__(4731); var getDiscriminatorByValue = __webpack_require__(7291); var internalToObjectOptions = (__webpack_require__(4962)/* .internalToObjectOptions */ .h); var utils = __webpack_require__(6872); var isBsonType = __webpack_require__(1563); var arrayParentSymbol = (__webpack_require__(8770).arrayParentSymbol); var arrayPathSymbol = (__webpack_require__(8770).arrayPathSymbol); var arraySchemaSymbol = (__webpack_require__(8770).arraySchemaSymbol); var documentArrayParent = (__webpack_require__(8770).documentArrayParent); var methods = { /*! * ignore */ toBSON: function toBSON() { return this.toObject(internalToObjectOptions); }, /*! * ignore */ getArrayParent: function getArrayParent() { return this[arrayParentSymbol]; }, /** * Overrides MongooseArray#cast * * @method _cast * @api private * @receiver MongooseDocumentArray */ _cast: function _cast(value, index) { if (this[arraySchemaSymbol] == null) { return value; } var Constructor = this[arraySchemaSymbol].casterConstructor; var isInstance = Constructor.$isMongooseDocumentArray ? utils.isMongooseDocumentArray(value) : 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; } if (value === undefined || value === null) { return null; } // 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) || isBsonType(value, 'ObjectID') || !utils.isObject(value)) { value = { _id: value }; } 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 { var constructorByValue = getDiscriminatorByValue(Constructor.discriminators, value[Constructor.schema.options.discriminatorKey]); if (constructorByValue) { Constructor = constructorByValue; } } } if (Constructor.$isMongooseDocumentArray) { return Constructor.cast(value, this, undefined, undefined, index); } var 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: function id(_id2) { var casted; var sid; var _id; try { casted = castObjectId(_id2).toString(); } catch (e) { casted = null; } var _iterator = _createForOfIteratorHelper(this), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var val = _step.value; if (!val) { continue; } _id = val.get('_id'); if (_id === null || typeof _id === 'undefined') { continue; } else if (_id instanceof Document) { sid || (sid = String(_id2)); if (sid == _id._id) { return val; } } else if (!isBsonType(_id2, 'ObjectID') && !isBsonType(_id, 'ObjectID')) { if (_id2 == _id || utils.deepEqual(_id2, _id)) { return val; } } else if (casted == _id) { return val; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } 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: function 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: function $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: function push() { var 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: function pull() { var 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: function shift() { var 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: function splice() { var ret = ArrayMethods.splice.apply(this, arguments); _updateParentPopulated(this); return ret; }, /** * Helper for console.log * * @method inspect * @api public * @memberOf MongooseDocumentArray */ inspect: function 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: function create(obj) { var 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 { var constructorByValue = getDiscriminatorByValue(Constructor.discriminators, obj[Constructor.schema.options.discriminatorKey]); if (constructorByValue) { Constructor = constructorByValue; } } } return new Constructor(obj, this); }, /*! * ignore */ notify: function notify(event) { var _this = this; return function notify(val, _arr) { _arr = _arr || _this; var 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 (utils.isMongooseArray(_arr[i])) { notify(val, _arr[i]); } else if (_arr[i]) { _arr[i].emit(event, val); } } }; }, set: function set(i, val, skipModified) { var arr = this.__array; if (skipModified) { arr[i] = val; return this; } var value = methods._cast.call(this, val, i); methods._markModified.call(this, i); arr[i] = value; return this; }, _markModified: function _markModified(elem, embeddedPath) { var parent = this[arrayParentSymbol]; var dirtyPath; if (parent) { dirtyPath = this[arrayPathSymbol]; if (arguments.length) { if (embeddedPath != null) { // an embedded doc bubbled up the change var index = elem.__index; dirtyPath = dirtyPath + '.' + index + '.' + embeddedPath; } else { // directly set an index dirtyPath = dirtyPath + '.' + elem; } } if (dirtyPath != null && dirtyPath.endsWith('.$')) { return this; } parent.markModified(dirtyPath, arguments.length !== 0 ? elem : parent); } return this; } }; module.exports = methods; /*! * 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 _updateParentPopulated(arr) { var parent = arr[arrayParentSymbol]; if (!parent || parent.$__.populated == null) return; var populatedPaths = Object.keys(parent.$__.populated).filter(function (p) { return p.startsWith(arr[arrayPathSymbol] + '.'); }); var _iterator2 = _createForOfIteratorHelper(populatedPaths), _step2; try { var _loop = function _loop() { var path = _step2.value; var remnant = path.slice((arr[arrayPathSymbol] + '.').length); if (!Array.isArray(parent.$__.populated[path].value)) { return "continue"; } parent.$__.populated[path].value = arr.map(function (val) { return val.$populated(remnant); }); }; for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var _ret = _loop(); if (_ret === "continue") continue; } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } /***/ }), /***/ 1362: /***/ ((module, exports, __webpack_require__) => { "use strict"; /*! * Module dependencies. */ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var Document = __webpack_require__(8727); var mongooseArrayMethods = __webpack_require__(8075); var arrayAtomicsSymbol = (__webpack_require__(8770).arrayAtomicsSymbol); var arrayAtomicsBackupSymbol = (__webpack_require__(8770).arrayAtomicsBackupSymbol); var arrayParentSymbol = (__webpack_require__(8770).arrayParentSymbol); var arrayPathSymbol = (__webpack_require__(8770).arrayPathSymbol); var arraySchemaSymbol = (__webpack_require__(8770).arraySchemaSymbol); /** * 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 https://bit.ly/f6CnZU */ var _basePush = Array.prototype.push; var numberRE = /^\d+$/; function MongooseArray(values, path, doc, schematype) { var _internals; var __array; if (Array.isArray(values)) { var 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) { __array = new Array(); } else if (len === 1) { __array = new Array(1); __array[0] = values[0]; } else if (len < 10000) { __array = new Array(); _basePush.apply(__array, values); } else { __array = new Array(); for (var i = 0; i < len; ++i) { _basePush.call(__array, values[i]); } } } else { __array = []; } var internals = (_internals = {}, _defineProperty(_internals, arrayAtomicsSymbol, {}), _defineProperty(_internals, arrayAtomicsBackupSymbol, void 0), _defineProperty(_internals, arrayPathSymbol, path), _defineProperty(_internals, arraySchemaSymbol, schematype), _defineProperty(_internals, arrayParentSymbol, void 0), _defineProperty(_internals, "isMongooseArray", true), _defineProperty(_internals, "isMongooseArrayProxy", true), _defineProperty(_internals, "__array", __array), _internals); if (values && values[arrayAtomicsSymbol] != null) { internals[arrayAtomicsSymbol] = values[arrayAtomicsSymbol]; } // 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 proxy = new Proxy(__array, { get: function get(target, prop) { if (internals.hasOwnProperty(prop)) { return internals[prop]; } if (mongooseArrayMethods.hasOwnProperty(prop)) { return mongooseArrayMethods[prop]; } return __array[prop]; }, set: function set(target, prop, value) { if (typeof prop === 'string' && numberRE.test(prop)) { mongooseArrayMethods.set.call(proxy, prop, value, false); } else if (internals.hasOwnProperty(prop)) { internals[prop] = value; } else { __array[prop] = value; } return true; } }); return proxy; } /*! * Module exports. */ module.exports = exports = MongooseArray; /***/ }), /***/ 7339: /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.isMongooseArray = function (mongooseArray) { return Array.isArray(mongooseArray) && mongooseArray.isMongooseArray; }; /***/ }), /***/ 8075: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var Document = __webpack_require__(8727); var ArraySubdocument = __webpack_require__(1568); var MongooseError = __webpack_require__(5202); var cleanModifiedSubpaths = __webpack_require__(4134); var internalToObjectOptions = (__webpack_require__(4962)/* .internalToObjectOptions */ .h); var utils = __webpack_require__(6872); var isBsonType = __webpack_require__(1563); var arrayAtomicsSymbol = (__webpack_require__(8770).arrayAtomicsSymbol); var arrayParentSymbol = (__webpack_require__(8770).arrayParentSymbol); var arrayPathSymbol = (__webpack_require__(8770).arrayPathSymbol); var arraySchemaSymbol = (__webpack_require__(8770).arraySchemaSymbol); var populateModelSymbol = (__webpack_require__(8770).populateModelSymbol); var slicedSymbol = Symbol('mongoose#Array#sliced'); var _basePush = Array.prototype.push; /*! * ignore */ var 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: function $__getAtomics() { var ret = []; var keys = Object.keys(this[arrayAtomicsSymbol] || {}); var i = keys.length; var opts = Object.assign({}, internalToObjectOptions, { _isNested: true }); if (i === 0) { ret[0] = ['$set', this.toObject(opts)]; return ret; } while (i--) { var op = keys[i]; var 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(); } if (op === '$addToSet') { val = { $each: val }; } ret.push([op, val]); } return ret; }, /*! * ignore */ $atomics: function $atomics() { return this[arrayAtomicsSymbol]; }, /*! * ignore */ $parent: function $parent() { return this[arrayParentSymbol]; }, /*! * ignore */ $path: function $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](https://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 https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop */ $shift: function $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 multiple times on an array before saving sends the same command as calling it once._ * _This update is implemented using the MongoDB [$pop](https://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 https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop * @method $pop * @memberOf MongooseArray */ $pop: function $pop() { this._registerAtomic('$pop', 1); this._markModified(); // only allow popping once if (this._popped) { return; } this._popped = true; return [].pop.call(this); }, /*! * ignore */ $schema: function $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: function _cast(value) { var populated = false; var Model; var parent = this[arrayParentSymbol]; if (parent) { populated = parent.$populated(this[arrayPathSymbol], true); } 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) || isBsonType(value, 'ObjectID') || !utils.isObject(value)) { value = { _id: value }; } // gh-2399 // we should cast model only when it's not a discriminator var 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); } return this[arraySchemaSymbol].caster.applySetters(value, parent, false); }, /** * Internal helper for .map() * * @api private * @return {Number} * @method _mapCast * @memberOf MongooseArray */ _mapCast: function _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: function _markModified(elem) { var parent = this[arrayParentSymbol]; var dirtyPath; if (parent) { dirtyPath = this[arrayPathSymbol]; if (arguments.length) { dirtyPath = dirtyPath + '.' + elem; } if (dirtyPath != null && dirtyPath.endsWith('.$')) { return this; } parent.markModified(dirtyPath, arguments.length !== 0 ? elem : parent); } return this; }, /** * Register an atomic operation with the parent. * * @param {Array} op operation * @param {any} val * @method _registerAtomic * @api private * @memberOf MongooseArray */ _registerAtomic: function _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; } var atomics = this[arrayAtomicsSymbol]; // reset pop/shift after save if (op === '$pop' && !('$pop' in atomics)) { var _this = this; this[arrayParentSymbol].once('save', function () { _this._popped = _this._shifted = null; }); } // 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; } var selector; if (op === '$pullAll' || op === '$addToSet') { atomics[op] || (atomics[op] = []); atomics[op] = atomics[op].concat(val); } else if (op === '$pullDocs') { var 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; } 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: function addToSet() { _checkManualPopulation(this, arguments); var values = [].map.call(arguments, this._mapCast, this); values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]); var added = []; var type = ''; if (values[0] instanceof ArraySubdocument) { type = 'doc'; } else if (values[0] instanceof Date) { type = 'date'; } var rawValues = utils.isMongooseArray(values) ? values.__array : this; var rawArray = utils.isMongooseArray(this) ? this.__array : this; rawValues.forEach(function (v) { var found; var 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); } if (!found) { this._markModified(); rawArray.push(v); this._registerAtomic('$addToSet', v); [].push.call(added, v); } }, this); return added; }, /** * Returns the number of pending atomic operations to send to the db for this array. * * @api private * @return {Number} * @method hasAtomics * @memberOf MongooseArray */ hasAtomics: function hasAtomics() { if (!utils.isPOJO(this[arrayAtomicsSymbol])) { return 0; } return Object.keys(this[arrayAtomicsSymbol]).length; }, /** * Return whether or not the `obj` is included in the array. * * @param {Object} obj the item to check * @param {Number} fromIndex * @return {Boolean} * @api public * @method includes * @memberOf MongooseArray */ includes: function includes(obj, fromIndex) { var 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 * @param {Number} fromIndex * @return {Number} * @api public * @method indexOf * @memberOf MongooseArray */ indexOf: function indexOf(obj, fromIndex) { if (isBsonType(obj, 'ObjectID')) { obj = obj.toString(); } fromIndex = fromIndex == null ? 0 : fromIndex; var len = this.length; for (var i = fromIndex; i < len; ++i) { if (obj == this[i]) { return i; } } return -1; }, /** * Helper for console.log * * @api public * @method inspect * @memberOf MongooseArray */ inspect: function 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: function nonAtomicPush() { var values = [].map.call(arguments, this._mapCast, this); this._markModified(); var ret = [].push.apply(this, values); this._registerAtomic('$set', this); 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 overwriting 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: function pop() { this._markModified(); var ret = [].pop.call(this); this._registerAtomic('$set', this); 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.](/docs/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 https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull * @api public * @method pull * @memberOf MongooseArray */ pull: function pull() { var values = [].map.call(arguments, this._cast, this); var cur = this[arrayParentSymbol].get(this[arrayPathSymbol]); var i = cur.length; var mem; this._markModified(); while (i--) { mem = cur[i]; if (mem instanceof Document) { var 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); } } if (values[0] instanceof ArraySubdocument) { this._registerAtomic('$pullDocs', values.map(function (v) { return v.$__getValue('_id') || v; })); } else { this._registerAtomic('$pullAll', values); } // 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); } 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: function push() { var values = arguments; var atomic = values; var isOverwrite = values[0] != null && utils.hasUserDefinedProperty(values[0], '$each'); var arr = utils.isMongooseArray(this) ? this.__array : this; if (isOverwrite) { atomic = values[0]; values = values[0].$each; } if (this[arraySchemaSymbol] == null) { return _basePush.apply(this, values); } _checkManualPopulation(this, values); var parent = this[arrayParentSymbol]; values = [].map.call(values, this._mapCast, this); values = this[arraySchemaSymbol].applySetters(values, parent, undefined, undefined, { skipDocumentArrayCast: true }); var ret; var atomics = this[arrayAtomicsSymbol]; this._markModified(); if (isOverwrite) { atomic.$each = values; if ((atomics.$push && atomics.$push.$each && atomics.$push.$each.length || 0) !== 0 && atomics.$push.$position != atomic.$position) { throw new MongooseError('Cannot call `Array#push()` multiple times ' + 'with different `$position`'); } if (atomic.$position != null) { [].splice.apply(arr, [atomic.$position, 0].concat(values)); ret = this.length; } else { ret = [].push.apply(arr, values); } } else { if ((atomics.$push && atomics.$push.$each && 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); return ret; }, /** * Alias of [pull](#mongoosearray_MongooseArray-pull) * * @see MongooseArray#pull #types_array_MongooseArray-pull * @see mongodb https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull * @api public * @memberOf MongooseArray * @instance * @method remove */ remove: function 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: function set(i, val, skipModified) { var arr = this.__array; if (skipModified) { arr[i] = val; return this; } var value = methods._cast.call(this, val, i); methods._markModified.call(this, i); arr[i] = value; 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: function shift() { var arr = utils.isMongooseArray(this) ? this.__array : this; this._markModified(); var ret = [].shift.call(arr); this._registerAtomic('$set', this); 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: function sort() { var arr = utils.isMongooseArray(this) ? this.__array : this; var 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: function splice() { var ret; var arr = utils.isMongooseArray(this) ? this.__array : this; _checkManualPopulation(this, Array.prototype.slice.call(arguments, 2)); if (arguments.length) { var vals; if (this[arraySchemaSymbol] == null) { vals = arguments; } else { vals = []; for (var i = 0; i < arguments.length; ++i) { vals[i] = i < 2 ? arguments[i] : this._cast(arguments[i], arguments[0] + (i - 2)); } } ret = [].splice.apply(arr, vals); this._registerAtomic('$set', this); } return ret; }, /*! * ignore */ toBSON: function toBSON() { return this.toObject(internalToObjectOptions); }, /** * Returns a native js Array. * * @param {Object} options * @return {Array} * @api public * @method toObject * @memberOf MongooseArray */ toObject: function toObject(options) { var arr = utils.isMongooseArray(this) ? 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; }); } return [].concat(arr); }, $toObject: function $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: function unshift() { _checkManualPopulation(this, arguments); var values; if (this[arraySchemaSymbol] == null) { values = arguments; } else { values = [].map.call(arguments, this._cast, this); values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]); } var arr = utils.isMongooseArray(this) ? this.__array : this; this._markModified(); [].unshift.apply(arr, values); this._registerAtomic('$set', this); return this.length; } }; /*! * ignore */ function _isAllSubdocs(docs, ref) { if (!ref) { return false; } var _iterator = _createForOfIteratorHelper(docs), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var arg = _step.value; if (arg == null) { return false; } var model = arg.constructor; if (!(arg instanceof Document) || model.modelName !== ref && model.baseModelName !== ref) { return false; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return true; } /*! * ignore */ function _checkManualPopulation(arr, docs) { var ref = arr == null ? null : arr[arraySchemaSymbol] && arr[arraySchemaSymbol].caster && arr[arraySchemaSymbol].caster.options && arr[arraySchemaSymbol].caster.options.ref || null; if (arr.length === 0 && docs.length !== 0) { if (_isAllSubdocs(docs, ref)) { arr[arrayParentSymbol].$populated(arr[arrayPathSymbol], [], _defineProperty({}, populateModelSymbol, docs[0].constructor)); } } } var returnVanillaArrayMethods = ['filter', 'flat', 'flatMap', 'map', 'slice']; var _loop = function _loop() { var method = _returnVanillaArrayMe[_i]; if (Array.prototype[method] == null) { return "continue"; } methods[method] = function () { var _arr = utils.isMongooseArray(this) ? this.__array : this; var arr = [].concat(_arr); return arr[method].apply(arr, arguments); }; }; for (var _i = 0, _returnVanillaArrayMe = returnVanillaArrayMethods; _i < _returnVanillaArrayMe.length; _i++) { var _ret = _loop(); if (_ret === "continue") continue; } module.exports = methods; /***/ }), /***/ 4051: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; /*! * Module dependencies. */ var Binary = (__webpack_require__(9906).get)().Binary; var utils = __webpack_require__(6872); /** * 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 https://bit.ly/f6CnZU */ function MongooseBuffer(value, encode, offset) { var val = value; if (value == null) { val = 0; } var encoding; var path; var doc; if (Array.isArray(encode)) { // internal casting path = encode[0]; doc = encode[1]; } else { encoding = encode; } var 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; // make sure these internal props don't show up in Object.keys() buf[MongooseBuffer.pathSymbol] = path; buf[parentSymbol] = doc; buf._subtype = 0; return buf; } var pathSymbol = Symbol["for"]('mongoose#Buffer#_path'); var parentSymbol = Symbol["for"]('mongoose#Buffer#_parent'); MongooseBuffer.pathSymbol = pathSymbol; /*! * Inherit from Buffer. */ MongooseBuffer.mixin = { /** * Default subtype for the Binary representing this Buffer * * @api private * @property _subtype * @receiver MongooseBuffer */ _subtype: undefined, /** * Marks this buffer as modified. * * @api private * @method _markModified * @receiver MongooseBuffer */ _markModified: function _markModified() { var parent = this[parentSymbol]; if (parent) { parent.markModified(this[MongooseBuffer.pathSymbol]); } return this; }, /** * Writes the buffer. * * @api public * @method write * @receiver MongooseBuffer */ write: function write() { var written = Buffer.prototype.write.apply(this, arguments); if (written > 0) { this._markModified(); } 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 copy(target) { var ret = Buffer.prototype.copy.apply(this, arguments); if (target && target.isMongooseBuffer) { target._markModified(); } return ret; } }; /*! * 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 () { var ret = Buffer.prototype[method].apply(this, arguments); this._markModified(); return ret; }; }); /** * 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 https://bsonspec.org/#/specification * @param {Hex} [subtype] * @return {Binary} * @api public * @method toObject * @receiver MongooseBuffer */ MongooseBuffer.mixin.toObject = function (options) { var subtype = typeof options === 'number' ? options : this._subtype || 0; return new Binary(Buffer.from(this), subtype); }; MongooseBuffer.mixin.$toObject = MongooseBuffer.mixin.toObject; /** * 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); }; /** * 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; } if (this.length !== other.length) { return false; } for (var i = 0; i < this.length; ++i) { if (this[i] !== other[i]) { return false; } } return true; }; /** * 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 https://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; }; /*! * Module exports. */ MongooseBuffer.Binary = Binary; module.exports = MongooseBuffer; /***/ }), /***/ 5003: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /** * ObjectId type constructor * * #### Example * * const id = new mongoose.Types.ObjectId; * * @constructor ObjectId */ module.exports = (__webpack_require__(9906).get)().Decimal128; /***/ }), /***/ 8941: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /*! * Module exports. */ exports.Array = __webpack_require__(1362); exports.Buffer = __webpack_require__(4051); exports.Document = // @deprecate exports.Embedded = __webpack_require__(1568); exports.DocumentArray = __webpack_require__(6077); exports.Decimal128 = __webpack_require__(5003); exports.ObjectId = __webpack_require__(6079); exports.Map = __webpack_require__(3828); exports.Subdocument = __webpack_require__(2591); /***/ }), /***/ 3828: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var Mixed = __webpack_require__(3861); var clone = __webpack_require__(1973); var deepEqual = (__webpack_require__(6872).deepEqual); var getConstructorName = __webpack_require__(1981); var handleSpreadDoc = __webpack_require__(719); var util = __webpack_require__(161); var specialProperties = __webpack_require__(2862); var isBsonType = __webpack_require__(1563); var populateModelSymbol = (__webpack_require__(8770).populateModelSymbol); /*! * ignore */ var MongooseMap = /*#__PURE__*/function (_Map) { _inherits(MongooseMap, _Map); var _super = _createSuper(MongooseMap); function MongooseMap(v, path, doc, schemaType) { var _this; _classCallCheck(this, MongooseMap); if (getConstructorName(v) === 'Object') { v = Object.keys(v).reduce(function (arr, key) { return arr.concat([[key, v[key]]]); }, []); } _this = _super.call(this, v); _this.$__parent = doc != null && doc.$__ != null ? doc : null; _this.$__path = path; _this.$__schemaType = schemaType == null ? new Mixed(path) : schemaType; _this.$__runDeferred(); return _this; } _createClass(MongooseMap, [{ key: "$init", value: function $init(key, value) { checkValidKey(key); _get(_getPrototypeOf(MongooseMap.prototype), "set", this).call(this, key, value); if (value != null && value.$isSingleNested) { value.$basePath = this.$__path + '.' + key; } } }, { key: "$__set", value: function $__set(key, value) { _get(_getPrototypeOf(MongooseMap.prototype), "set", this).call(this, key, value); } }, { key: "get", value: function get(key, options) { if (isBsonType(key, 'ObjectID')) { key = key.toString(); } options = options || {}; if (options.getters === false) { return _get(_getPrototypeOf(MongooseMap.prototype), "get", this).call(this, key); } return this.$__schemaType.applyGetters(_get(_getPrototypeOf(MongooseMap.prototype), "get", this).call(this, key), this.$__parent); } }, { key: "set", value: function set(key, value) { if (isBsonType(key, 'ObjectID')) { key = key.toString(); } checkValidKey(key); value = handleSpreadDoc(value); // 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. if (this.$__schemaType == null) { this.$__deferred = this.$__deferred || []; this.$__deferred.push({ key: key, value: value }); return; } var fullPath = this.$__path + '.' + key; var populated = this.$__parent != null && this.$__parent.$__ ? this.$__parent.$populated(fullPath) || this.$__parent.$populated(this.$__path) : null; var priorVal = this.get(key); if (populated != null) { if (value.$__ == null) { value = new populated.options[populateModelSymbol](value); } value.$__.wasPopulated = { value: populated.value }; } 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; } } _get(_getPrototypeOf(MongooseMap.prototype), "set", this).call(this, key, value); if (value != null && value.$isSingleNested) { value.$basePath = this.$__path + '.' + key; } var parent = this.$__parent; if (parent != null && parent.$__ != null && !deepEqual(value, priorVal)) { parent.markModified(this.$__path + '.' + key); } } }, { key: "clear", value: function clear() { _get(_getPrototypeOf(MongooseMap.prototype), "clear", this).call(this); var parent = this.$__parent; if (parent != null) { parent.markModified(this.$__path); } } }, { key: "delete", value: function _delete(key) { if (isBsonType(key, 'ObjectID')) { key = key.toString(); } this.set(key, undefined); _get(_getPrototypeOf(MongooseMap.prototype), "delete", this).call(this, key); } }, { key: "toBSON", value: function toBSON() { return new Map(this); } }, { key: "toObject", value: function toObject(options) { if (options && options.flattenMaps) { var ret = {}; var keys = this.keys(); var _iterator = _createForOfIteratorHelper(keys), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var key = _step.value; ret[key] = clone(this.get(key), options); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return ret; } return new Map(this); } }, { key: "$toObject", value: function $toObject() { return this.constructor.prototype.toObject.apply(this, arguments); } }, { key: "toJSON", value: function toJSON(options) { if (typeof (options && options.flattenMaps) === 'boolean' ? options.flattenMaps : true) { var ret = {}; var keys = this.keys(); var _iterator2 = _createForOfIteratorHelper(keys), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var key = _step2.value; ret[key] = clone(this.get(key), options); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return ret; } return new Map(this); } }, { key: "inspect", value: function inspect() { return new Map(this); } }, { key: "$__runDeferred", value: function $__runDeferred() { if (!this.$__deferred) { return; } var _iterator3 = _createForOfIteratorHelper(this.$__deferred), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var keyValueObject = _step3.value; this.set(keyValueObject.key, keyValueObject.value); } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } this.$__deferred = null; } }]); return MongooseMap; }( /*#__PURE__*/_wrapNativeSuper(Map)); 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 */ function checkValidKey(key) { var keyType = _typeof(key); if (keyType !== 'string') { throw new TypeError("Mongoose maps only support string keys, got ".concat(keyType)); } if (key.startsWith('$')) { throw new Error("Mongoose maps do not support keys that start with \"$\", got \"".concat(key, "\"")); } if (key.includes('.')) { throw new Error("Mongoose maps do not support keys that contain \".\", got \"".concat(key, "\"")); } if (specialProperties.has(key)) { throw new Error("Mongoose maps do not support reserved key name \"".concat(key, "\"")); } } module.exports = MongooseMap; /***/ }), /***/ 6079: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /** * ObjectId type constructor * * #### Example * * const id = new mongoose.Types.ObjectId; * * @constructor ObjectId */ var ObjectId = (__webpack_require__(9906).get)().ObjectId; var objectIdSymbol = (__webpack_require__(8770).objectIdSymbol); /*! * Getter for convenience with populate, see gh-6115 */ Object.defineProperty(ObjectId.prototype, '_id', { enumerable: false, configurable: true, get: function get() { return this; } }); /*! * Convenience `valueOf()` to allow comparing ObjectIds using double equals re: gh-7299 */ if (!ObjectId.prototype.hasOwnProperty('valueOf')) { ObjectId.prototype.valueOf = function objectIdValueOf() { return this.toString(); }; } ObjectId.prototype[objectIdSymbol] = true; module.exports = ObjectId; /***/ }), /***/ 2591: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Document = __webpack_require__(8727); var immediate = __webpack_require__(1490); var internalToObjectOptions = (__webpack_require__(4962)/* .internalToObjectOptions */ .h); var promiseOrCallback = __webpack_require__(8486); var util = __webpack_require__(161); var utils = __webpack_require__(6872); module.exports = Subdocument; /** * Subdocument constructor. * * @inherits Document * @api private */ function Subdocument(value, fields, parent, skipId, options) { if (parent != null) { // If setting a nested path, should copy isNew from parent re: gh-7048 var 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); delete this.$__.priorDoc; } Subdocument.prototype = Object.create(Document.prototype); Object.defineProperty(Subdocument.prototype, '$isSubdocument', { configurable: false, writable: false, value: true }); Object.defineProperty(Subdocument.prototype, '$isSingleNested', { configurable: false, writable: false, value: true }); /*! * ignore */ Subdocument.prototype.toBSON = function () { return this.toObject(internalToObjectOptions); }; /** * 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) { var _this = this; if (typeof options === 'function') { fn = options; options = {}; } options = options || {}; 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.'); } return promiseOrCallback(fn, function (cb) { _this.$__save(cb); }); }; /*! * 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(); } return path ? this.$__.fullPath + '.' + path : this.$__.fullPath; }; /*! * Given a path relative to this document, return the path relative * to the top-level document. */ Subdocument.prototype.$__pathRelativeToParent = function (p) { if (p == null) { return this.$basePath; } return [this.$basePath, p].join('.'); }; /** * 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) { var _this2 = this; return immediate(function () { return fn(null, _this2); }); }; /*! * ignore */ Subdocument.prototype.$isValid = function (path) { var parent = this.$parent(); var fullPath = this.$__pathRelativeToParent(path); if (parent != null && fullPath != null) { return parent.$isValid(fullPath); } return Document.prototype.$isValid.call(this, path); }; /*! * ignore */ Subdocument.prototype.markModified = function (path) { Document.prototype.markModified.call(this, path); var parent = this.$parent(); var fullPath = this.$__pathRelativeToParent(path); if (parent == null || fullPath == null) { return; } var myPath = this.$__pathRelativeToParent().replace(/\.$/, ''); if (parent.isDirectModified(myPath) || this.isNew) { return; } this.$__parent.markModified(fullPath, this); }; /*! * ignore */ Subdocument.prototype.isModified = function (paths, modifiedPaths) { var _this3 = this; var parent = this.$parent(); if (parent != null) { if (Array.isArray(paths) || typeof paths === 'string') { paths = Array.isArray(paths) ? paths : paths.split(' '); paths = paths.map(function (p) { return _this3.$__pathRelativeToParent(p); }).filter(function (p) { return p != null; }); } else if (!paths) { paths = this.$__pathRelativeToParent(); } return parent.$isModified(paths, modifiedPaths); } 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 */ Subdocument.prototype.$markValid = function (path) { Document.prototype.$markValid.call(this, path); var parent = this.$parent(); var fullPath = this.$__pathRelativeToParent(path); if (parent != null && fullPath != null) { parent.$markValid(fullPath); } }; /*! * ignore */ Subdocument.prototype.invalidate = function (path, err, val) { Document.prototype.invalidate.call(this, path, err, val); var parent = this.$parent(); var 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; } return this.ownerDocument().$__.validationError; }; /*! * ignore */ Subdocument.prototype.$ignore = function (path) { Document.prototype.$ignore.call(this, path); var parent = this.$parent(); var 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; } var parent = this; // eslint-disable-line consistent-this var paths = []; var seenDocs = new Set([parent]); while (true) { if (typeof parent.$__pathRelativeToParent !== 'function') { break; } paths.unshift(parent.$__pathRelativeToParent(void 0, true)); var _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'); } seenDocs.add(parent); } this.$__.fullPath = paths.join('.'); this.$__.ownerDocument = parent; return this.$__.ownerDocument; }; /*! * ignore */ Subdocument.prototype.$__fullPathWithIndexes = function () { var parent = this; // eslint-disable-line consistent-this var paths = []; var seenDocs = new Set([parent]); while (true) { if (typeof parent.$__pathRelativeToParent !== 'function') { break; } paths.unshift(parent.$__pathRelativeToParent(void 0, false)); var _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'); } seenDocs.add(parent); } return paths.join('.'); }; /** * Returns this sub-documents parent document. * * @api public */ Subdocument.prototype.parent = function () { return this.$__parent; }; /** * Returns this sub-documents parent document. * * @api public * @method $parent */ Subdocument.prototype.$parent = Subdocument.prototype.parent; /*! * no-op for hooks */ Subdocument.prototype.$__remove = function (cb) { if (cb == null) { return; } return cb(null, this); }; Subdocument.prototype.$__removeFromParent = function () { this.$__parent.set(this.$basePath, null); }; /** * Null-out this subdoc * * @param {Object} [options] * @param {Function} [callback] optional callback for compatibility with Document.prototype.remove */ 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.$__removeFromParent(); } return this.$__remove(callback); }; /*! * ignore */ 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")`'); }; /** * Helper for console.log * * @api public */ 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 registerRemoveListener(sub) { var owner = sub.ownerDocument(); function emitRemove() { owner.$removeListener('save', emitRemove); owner.$removeListener('remove', emitRemove); sub.emit('remove', sub); sub.constructor.emit('remove', sub); owner = sub = null; } owner.$on('save', emitRemove); owner.$on('remove', emitRemove); } /***/ }), /***/ 6872: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; /*! * Module dependencies. */ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var ms = __webpack_require__(2068); var mpath = __webpack_require__(3564); var ObjectId = __webpack_require__(6079); var PopulateOptions = __webpack_require__(4034); var clone = __webpack_require__(1973); var immediate = __webpack_require__(1490); var isObject = __webpack_require__(5721); var isMongooseArray = __webpack_require__(7339); var isMongooseDocumentArray = __webpack_require__(1255); var isBsonType = __webpack_require__(1563); var getFunctionName = __webpack_require__(6749); var isMongooseObject = __webpack_require__(6584); var promiseOrCallback = __webpack_require__(8486); var schemaMerge = __webpack_require__(4913); var specialProperties = __webpack_require__(2862); var _require = __webpack_require__(3636), trustedSymbol = _require.trustedSymbol; var Document; exports.specialProperties = specialProperties; exports.isMongooseArray = isMongooseArray.isMongooseArray; exports.isMongooseDocumentArray = isMongooseDocumentArray.isMongooseDocumentArray; exports.registerMongooseArray = isMongooseArray.registerMongooseArray; exports.registerMongooseDocumentArray = isMongooseDocumentArray.registerMongooseDocumentArray; /*! * 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; }; /*! * 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; } if (_typeof(a) !== 'object' || _typeof(b) !== 'object') { return a === b; } if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime(); } if (isBsonType(a, 'ObjectID') && isBsonType(b, 'ObjectID') || isBsonType(a, 'Decimal128') && isBsonType(b, 'Decimal128')) { return a.toString() === b.toString(); } if (a instanceof RegExp && b instanceof RegExp) { return a.source === b.source && a.ignoreCase === b.ignoreCase && a.multiline === b.multiline && a.global === b.global && a.dotAll === b.dotAll && a.unicode === b.unicode && a.sticky === b.sticky && a.hasIndices === b.hasIndices; } if (a == null || b == null) { return false; } if (a.prototype !== b.prototype) { return false; } if (a instanceof Map || b instanceof Map) { if (!(a instanceof Map) || !(b instanceof Map)) { return false; } 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); } if (Array.isArray(a) || Array.isArray(b)) { if (!Array.isArray(a) || !Array.isArray(b)) { return false; } var len = a.length; if (len !== b.length) { return false; } for (var 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(); } if (b.$__ != null) { b = b._doc; } else if (isMongooseObject(b)) { b = b.toObject(); } var ka = Object.keys(a); var kb = Object.keys(b); var kaLength = ka.length; // having the same number of owned properties (keys incorporates // hasOwnProperty) if (kaLength !== kb.length) { return false; } // ~~~cheap key test for (var _i = kaLength - 1; _i >= 0; _i--) { if (ka[_i] !== kb[_i]) { return false; } } // equivalent values for every corresponding key, and // ~~~possibly expensive deep test for (var _i2 = 0, _ka = ka; _i2 < _ka.length; _i2++) { var key = _ka[_i2]; if (!deepEqual(a[key], b[key])) { return false; } } return true; }; /*! * Get the last element of an array */ exports.last = function (arr) { if (arr.length > 0) { return arr[arr.length - 1]; } return void 0; }; exports.clone = clone; /*! * ignore */ exports.promiseOrCallback = promiseOrCallback; /*! * ignore */ exports.cloneArrays = function cloneArrays(arr) { if (!Array.isArray(arr)) { return arr; } return arr.map(function (el) { return exports.cloneArrays(el); }); }; /*! * ignore */ exports.omit = function omit(obj, keys) { if (keys == null) { return Object.assign({}, obj); } if (!Array.isArray(keys)) { keys = [keys]; } var ret = Object.assign({}, obj); var _iterator = _createForOfIteratorHelper(keys), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var key = _step.value; delete ret[key]; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return ret; }; /*! * Shallow copies defaults into options. * * @param {Object} defaults * @param {Object} options * @return {Object} the merged object * @api private */ exports.options = function (defaults, options) { var keys = Object.keys(defaults); var i = keys.length; var k; options = options || {}; while (i--) { k = keys[i]; if (!(k in options)) { options[k] = defaults[k]; } } return options; }; /*! * Merges `from` into `to` without overwriting existing properties. * * @param {Object} to * @param {Object} from * @api private */ exports.merge = function merge(to, from, options, path) { options = options || {}; var keys = Object.keys(from); var i = 0; var len = keys.length; var key; if (from[trustedSymbol]) { to[trustedSymbol] = from[trustedSymbol]; } path = path || ''; var 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 { to[key] = from[key].clone(); } continue; } else if (isBsonType(from[key], '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]; } } }; /*! * Applies toObject recursively. * * @param {Document|Array|Object} obj * @return {Object} * @api private */ exports.toObject = function toObject(obj) { Document || (Document = __webpack_require__(8727)); var ret; if (obj == null) { return obj; } if (obj instanceof Document) { return obj.toObject(); } if (Array.isArray(obj)) { ret = []; var _iterator2 = _createForOfIteratorHelper(obj), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var doc = _step2.value; ret.push(toObject(doc)); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return ret; } if (exports.isPOJO(obj)) { ret = {}; if (obj[trustedSymbol]) { ret[trustedSymbol] = obj[trustedSymbol]; } for (var _i3 = 0, _Object$keys = Object.keys(obj); _i3 < _Object$keys.length; _i3++) { var k = _Object$keys[_i3]; if (specialProperties.has(k)) { continue; } ret[k] = toObject(obj[k]); } return ret; } return obj; }; 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; } var 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. */ exports.isNonBuiltinObject = function isNonBuiltinObject(val) { return _typeof(val) === 'object' && !exports.isNativeObject(val) && !exports.isMongooseType(val) && val != null; }; /*! * 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; }; /*! * Determines if `val` is an object that has no own keys */ exports.isEmptyObject = function (val) { return val != null && _typeof(val) === 'object' && Object.keys(val).length === 0; }; /*! * Search if `obj` or any POJOs nested underneath `obj` has a property named * `key` */ exports.hasKey = function hasKey(obj, key) { var props = Object.keys(obj); for (var _i4 = 0, _props = props; _i4 < _props.length; _i4++) { var prop = _props[_i4]; if (prop === key) { return true; } if (exports.isPOJO(obj[prop]) && exports.hasKey(obj[prop], key)) { return true; } } return false; }; /*! * 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; }); } }; }; /*! * Returns true if `v` is an object that can be serialized as a primitive in * MongoDB */ exports.isMongooseType = function (v) { return isBsonType(v, 'ObjectID') || isBsonType(v, 'Decimal128') || v instanceof Buffer; }; 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; } object.expireAfterSeconds = typeof object.expires !== 'string' ? object.expires : Math.round(ms(object.expires) / 1000); delete object.expires; }; /*! * populate helper */ exports.populate = function populate(path, select, model, match, options, subPopulate, justOne, count) { // might have passed an object specifying all arguments var obj = null; if (arguments.length === 1) { if (path instanceof PopulateOptions) { // If reusing old populate docs, avoid reusing `_docs` because that may // lead to bugs and memory leaks. See gh-11641 path._docs = []; path._childDocs = []; return [path]; } if (Array.isArray(path)) { var singles = makeSingles(path); return singles.map(function (o) { return 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 }; } if (typeof obj.path !== 'string') { throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + _typeof(path) + '`'); } 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) { var ret = []; arr.forEach(function (obj) { if (/[\s]/.test(obj.path)) { var paths = obj.path.split(' '); paths.forEach(function (p) { var copy = Object.assign({}, obj); copy.path = p; ret.push(copy); }); } else { ret.push(obj); } }); return ret; } }; function _populateObj(obj) { if (Array.isArray(obj.populate)) { var _ret = []; obj.populate.forEach(function (obj) { if (/[\s]/.test(obj.path)) { var copy = Object.assign({}, obj); var _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); } var ret = []; var paths = obj.path.split(' '); if (obj.options != null) { obj.options = exports.clone(obj.options); } var _iterator3 = _createForOfIteratorHelper(paths), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var path = _step3.value; ret.push(new PopulateOptions(Object.assign({}, obj, { path: path }))); } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return ret; } /*! * Return the value of `obj` at the given `path`. * * @param {String} path * @param {Object} obj */ exports.getValue = function (path, obj, map) { return mpath.get(path, obj, '_doc', map); }; /*! * 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); }; /*! * Returns an array of values from object `o`. * * @param {Object} o * @return {Array} * @private */ exports.object = {}; exports.object.vals = function vals(o) { var keys = Object.keys(o); var i = keys.length; var ret = []; while (i--) { ret.push(o[keys[i]]); } return ret; }; /*! * @see exports.options */ exports.object.shallowCopy = exports.options; /*! * Safer helper for hasOwnProperty checks * * @param {Object} obj * @param {String} prop */ var hop = Object.prototype.hasOwnProperty; exports.object.hasOwnProperty = function (obj, prop) { return hop.call(obj, prop); }; /*! * Determine if `val` is null or undefined * * @return {Boolean} */ exports.isNullOrUndefined = function (val) { return val === null || val === undefined; }; /*! * 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); } } }); return ret; }; /*! * ignore */ var _hasOwnProperty = Object.prototype.hasOwnProperty; exports.hasUserDefinedProperty = function (obj, key) { if (obj == null) { return false; } if (Array.isArray(key)) { var _iterator4 = _createForOfIteratorHelper(key), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var k = _step4.value; if (exports.hasUserDefinedProperty(obj, k)) { return true; } } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } return false; } if (_hasOwnProperty.call(obj, key)) { return true; } if (_typeof(obj) === 'object' && key in obj) { var v = obj[key]; return v !== Object.prototype[key] && v !== Array.prototype[key]; } return false; }; /*! * ignore */ var MAX_ARRAY_INDEX = Math.pow(2, 32) - 1; 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; } return false; }; /*! * 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) { var primitives = new Set(); var ids = new Set(); var ret = []; var _iterator5 = _createForOfIteratorHelper(arr), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var item = _step5.value; if (typeof item === 'number' || typeof item === 'string' || item == null) { if (primitives.has(item)) { continue; } ret.push(item); primitives.add(item); } else if (isBsonType(item, 'ObjectID')) { if (ids.has(item.toString())) { continue; } ret.push(item); ids.add(item.toString()); } else { ret.push(item); } } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } return ret; }; /*! * Determines if two buffers are equal. * * @param {Buffer} a * @param {Object} b */ 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 (var 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 (var 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 */ exports.mergeClone = function (to, fromObj) { if (isMongooseObject(fromObj)) { fromObj = fromObj.toObject({ transform: false, virtuals: false, depopulate: true, getters: false, flattenDecimals: false }); } var keys = Object.keys(fromObj); var len = keys.length; var i = 0; var 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 { var val = fromObj[key]; if (val != null && val.valueOf && !(val instanceof Date)) { val = val.valueOf(); } if (exports.isObject(val)) { var 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 */ exports.each = function (arr, fn) { var _iterator6 = _createForOfIteratorHelper(arr), _step6; try { for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { var item = _step6.value; fn(item); } } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } }; /*! * ignore */ exports.getOption = function (name) { var sources = Array.prototype.slice.call(arguments, 1); var _iterator7 = _createForOfIteratorHelper(sources), _step7; try { for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) { var source = _step7.value; if (source == null) { continue; } if (source[name] != null) { return source[name]; } } } catch (err) { _iterator7.e(err); } finally { _iterator7.f(); } return null; }; /*! * ignore */ exports.noop = function () {}; exports.errorToPOJO = function errorToPOJO(error) { var isError = error instanceof Error; if (!isError) { throw new Error('`error` must be `instanceof Error`.'); } var ret = {}; var _iterator8 = _createForOfIteratorHelper(Object.getOwnPropertyNames(error)), _step8; try { for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) { var properyName = _step8.value; ret[properyName] = error[properyName]; } } catch (err) { _iterator8.e(err); } finally { _iterator8.f(); } return ret; }; /*! * ignore */ exports.warn = function warn(message) { return ({env:{}}).emitWarning(message, { code: 'MONGOOSE' }); }; /***/ }), /***/ 459: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var utils = __webpack_require__(6872); /** * 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`. * @param {string} name * @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; } var path = this.path; var internalProperty = '$' + path; this.getters.push(function () { return this[internalProperty]; }); this.setters.push(function (v) { this[internalProperty] = v; }); }; /*! * ignore */ VirtualType.prototype.clone = function () { var clone = new VirtualType(this.options, this.path); clone.getters = [].concat(this.getters); clone.setters = [].concat(this.setters); return clone; }; /** * 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; }; /** * 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]; } var v = value; var _iterator = _createForOfIteratorHelper(this.getters), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var getter = _step.value; v = getter.call(doc, v, this, doc); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return v; }; /** * 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) { var v = value; var _iterator2 = _createForOfIteratorHelper(this.setters), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var setter = _step2.value; v = setter.call(doc, v, this, doc); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return v; }; /*! * exports */ module.exports = VirtualType; /***/ }), /***/ 7406: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var asn1 = exports; asn1.bignum = __webpack_require__(6781); asn1.define = (__webpack_require__(8721).define); asn1.base = __webpack_require__(6002); asn1.constants = __webpack_require__(4319); asn1.decoders = __webpack_require__(4049); asn1.encoders = __webpack_require__(6860); /***/ }), /***/ 8721: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var encoders = __webpack_require__(6860); var decoders = __webpack_require__(4049); var inherits = __webpack_require__(376); var api = exports; api.define = function define(name, body) { return new Entity(name, body); }; function Entity(name, body) { this.name = name; this.body = body; this.decoders = {}; this.encoders = {}; } Entity.prototype._createNamed = function createNamed(Base) { var name = this.name; function Generated(entity) { this._initNamed(entity, name); } inherits(Generated, Base); Generated.prototype._initNamed = function _initNamed(entity, name) { Base.call(this, entity, name); }; return new Generated(this); }; Entity.prototype._getDecoder = function _getDecoder(enc) { enc = enc || 'der'; // Lazily create decoder if (!this.decoders.hasOwnProperty(enc)) this.decoders[enc] = this._createNamed(decoders[enc]); return this.decoders[enc]; }; Entity.prototype.decode = function decode(data, enc, options) { return this._getDecoder(enc).decode(data, options); }; Entity.prototype._getEncoder = function _getEncoder(enc) { enc = enc || 'der'; // Lazily create encoder if (!this.encoders.hasOwnProperty(enc)) this.encoders[enc] = this._createNamed(encoders[enc]); return this.encoders[enc]; }; Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { return this._getEncoder(enc).encode(data, reporter); }; /***/ }), /***/ 4989: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var inherits = __webpack_require__(376); var Reporter = (__webpack_require__(1269)/* .Reporter */ .b); var Buffer = (__webpack_require__(8723).Buffer); function DecoderBuffer(base, options) { Reporter.call(this, options); if (!Buffer.isBuffer(base)) { this.error('Input not Buffer'); return; } this.base = base; this.offset = 0; this.length = base.length; } inherits(DecoderBuffer, Reporter); exports.C = DecoderBuffer; DecoderBuffer.isDecoderBuffer = function isDecoderBuffer(data) { if (data instanceof DecoderBuffer) { return true; } // Or accept compatible API var isCompatible = _typeof(data) === 'object' && Buffer.isBuffer(data.base) && data.constructor.name === 'DecoderBuffer' && typeof data.offset === 'number' && typeof data.length === 'number' && typeof data.save === 'function' && typeof data.restore === 'function' && typeof data.isEmpty === 'function' && typeof data.readUInt8 === 'function' && typeof data.skip === 'function' && typeof data.raw === 'function'; return isCompatible; }; DecoderBuffer.prototype.save = function save() { return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; }; DecoderBuffer.prototype.restore = function restore(save) { // Return skipped data var res = new DecoderBuffer(this.base); res.offset = save.offset; res.length = this.offset; this.offset = save.offset; Reporter.prototype.restore.call(this, save.reporter); return res; }; DecoderBuffer.prototype.isEmpty = function isEmpty() { return this.offset === this.length; }; DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { if (this.offset + 1 <= this.length) return this.base.readUInt8(this.offset++, true);else return this.error(fail || 'DecoderBuffer overrun'); }; DecoderBuffer.prototype.skip = function skip(bytes, fail) { if (!(this.offset + bytes <= this.length)) return this.error(fail || 'DecoderBuffer overrun'); var res = new DecoderBuffer(this.base); // Share reporter state res._reporterState = this._reporterState; res.offset = this.offset; res.length = this.offset + bytes; this.offset += bytes; return res; }; DecoderBuffer.prototype.raw = function raw(save) { return this.base.slice(save ? save.offset : this.offset, this.length); }; function EncoderBuffer(value, reporter) { if (Array.isArray(value)) { this.length = 0; this.value = value.map(function (item) { if (!EncoderBuffer.isEncoderBuffer(item)) item = new EncoderBuffer(item, reporter); this.length += item.length; return item; }, this); } else if (typeof value === 'number') { if (!(0 <= value && value <= 0xff)) return reporter.error('non-byte EncoderBuffer value'); this.value = value; this.length = 1; } else if (typeof value === 'string') { this.value = value; this.length = Buffer.byteLength(value); } else if (Buffer.isBuffer(value)) { this.value = value; this.length = value.length; } else { return reporter.error('Unsupported type: ' + _typeof(value)); } } exports.R = EncoderBuffer; EncoderBuffer.isEncoderBuffer = function isEncoderBuffer(data) { if (data instanceof EncoderBuffer) { return true; } // Or accept compatible API var isCompatible = _typeof(data) === 'object' && data.constructor.name === 'EncoderBuffer' && typeof data.length === 'number' && typeof data.join === 'function'; return isCompatible; }; EncoderBuffer.prototype.join = function join(out, offset) { if (!out) out = Buffer.alloc(this.length); if (!offset) offset = 0; if (this.length === 0) return out; if (Array.isArray(this.value)) { this.value.forEach(function (item) { item.join(out, offset); offset += item.length; }); } else { if (typeof this.value === 'number') out[offset] = this.value;else if (typeof this.value === 'string') out.write(this.value, offset);else if (Buffer.isBuffer(this.value)) this.value.copy(out, offset); offset += this.length; } return out; }; /***/ }), /***/ 6002: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var base = exports; base.Reporter = (__webpack_require__(1269)/* .Reporter */ .b); base.DecoderBuffer = (__webpack_require__(4989)/* .DecoderBuffer */ .C); base.EncoderBuffer = (__webpack_require__(4989)/* .EncoderBuffer */ .R); base.Node = __webpack_require__(3304); /***/ }), /***/ 3304: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var Reporter = (__webpack_require__(1269)/* .Reporter */ .b); var EncoderBuffer = (__webpack_require__(4989)/* .EncoderBuffer */ .R); var DecoderBuffer = (__webpack_require__(4989)/* .DecoderBuffer */ .C); var assert = __webpack_require__(1130); // Supported tags var tags = ['seq', 'seqof', 'set', 'setof', 'objid', 'bool', 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr']; // Public methods list var methods = ['key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', 'any', 'contains'].concat(tags); // Overrided methods list var overrided = ['_peekTag', '_decodeTag', '_use', '_decodeStr', '_decodeObjid', '_decodeTime', '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', '_encodeNull', '_encodeInt', '_encodeBool']; function Node(enc, parent, name) { var state = {}; this._baseState = state; state.name = name; state.enc = enc; state.parent = parent || null; state.children = null; // State state.tag = null; state.args = null; state.reverseArgs = null; state.choice = null; state.optional = false; state.any = false; state.obj = false; state.use = null; state.useDecoder = null; state.key = null; state['default'] = null; state.explicit = null; state.implicit = null; state.contains = null; // Should create new instance on each method if (!state.parent) { state.children = []; this._wrap(); } } module.exports = Node; var stateProps = ['enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', 'implicit', 'contains']; Node.prototype.clone = function clone() { var state = this._baseState; var cstate = {}; stateProps.forEach(function (prop) { cstate[prop] = state[prop]; }); var res = new this.constructor(cstate.parent); res._baseState = cstate; return res; }; Node.prototype._wrap = function wrap() { var state = this._baseState; methods.forEach(function (method) { this[method] = function _wrappedMethod() { var clone = new this.constructor(this); state.children.push(clone); return clone[method].apply(clone, arguments); }; }, this); }; Node.prototype._init = function init(body) { var state = this._baseState; assert(state.parent === null); body.call(this); // Filter children state.children = state.children.filter(function (child) { return child._baseState.parent === this; }, this); assert.equal(state.children.length, 1, 'Root node can have only one child'); }; Node.prototype._useArgs = function useArgs(args) { var state = this._baseState; // Filter children and args var children = args.filter(function (arg) { return arg instanceof this.constructor; }, this); args = args.filter(function (arg) { return !(arg instanceof this.constructor); }, this); if (children.length !== 0) { assert(state.children === null); state.children = children; // Replace parent to maintain backward link children.forEach(function (child) { child._baseState.parent = this; }, this); } if (args.length !== 0) { assert(state.args === null); state.args = args; state.reverseArgs = args.map(function (arg) { if (_typeof(arg) !== 'object' || arg.constructor !== Object) return arg; var res = {}; Object.keys(arg).forEach(function (key) { if (key == (key | 0)) key |= 0; var value = arg[key]; res[value] = key; }); return res; }); } }; // // Overrided methods // overrided.forEach(function (method) { Node.prototype[method] = function _overrided() { var state = this._baseState; throw new Error(method + ' not implemented for encoding: ' + state.enc); }; }); // // Public methods // tags.forEach(function (tag) { Node.prototype[tag] = function _tagMethod() { var state = this._baseState; var args = Array.prototype.slice.call(arguments); assert(state.tag === null); state.tag = tag; this._useArgs(args); return this; }; }); Node.prototype.use = function use(item) { assert(item); var state = this._baseState; assert(state.use === null); state.use = item; return this; }; Node.prototype.optional = function optional() { var state = this._baseState; state.optional = true; return this; }; Node.prototype.def = function def(val) { var state = this._baseState; assert(state['default'] === null); state['default'] = val; state.optional = true; return this; }; Node.prototype.explicit = function explicit(num) { var state = this._baseState; assert(state.explicit === null && state.implicit === null); state.explicit = num; return this; }; Node.prototype.implicit = function implicit(num) { var state = this._baseState; assert(state.explicit === null && state.implicit === null); state.implicit = num; return this; }; Node.prototype.obj = function obj() { var state = this._baseState; var args = Array.prototype.slice.call(arguments); state.obj = true; if (args.length !== 0) this._useArgs(args); return this; }; Node.prototype.key = function key(newKey) { var state = this._baseState; assert(state.key === null); state.key = newKey; return this; }; Node.prototype.any = function any() { var state = this._baseState; state.any = true; return this; }; Node.prototype.choice = function choice(obj) { var state = this._baseState; assert(state.choice === null); state.choice = obj; this._useArgs(Object.keys(obj).map(function (key) { return obj[key]; })); return this; }; Node.prototype.contains = function contains(item) { var state = this._baseState; assert(state.use === null); state.contains = item; return this; }; // // Decoding // Node.prototype._decode = function decode(input, options) { var state = this._baseState; // Decode root node if (state.parent === null) return input.wrapResult(state.children[0]._decode(input, options)); var result = state['default']; var present = true; var prevKey = null; if (state.key !== null) prevKey = input.enterKey(state.key); // Check if tag is there if (state.optional) { var tag = null; if (state.explicit !== null) tag = state.explicit;else if (state.implicit !== null) tag = state.implicit;else if (state.tag !== null) tag = state.tag; if (tag === null && !state.any) { // Trial and Error var save = input.save(); try { if (state.choice === null) this._decodeGeneric(state.tag, input, options);else this._decodeChoice(input, options); present = true; } catch (e) { present = false; } input.restore(save); } else { present = this._peekTag(input, tag, state.any); if (input.isError(present)) return present; } } // Push object on stack var prevObj; if (state.obj && present) prevObj = input.enterObject(); if (present) { // Unwrap explicit values if (state.explicit !== null) { var explicit = this._decodeTag(input, state.explicit); if (input.isError(explicit)) return explicit; input = explicit; } var start = input.offset; // Unwrap implicit and normal values if (state.use === null && state.choice === null) { var _save; if (state.any) _save = input.save(); var body = this._decodeTag(input, state.implicit !== null ? state.implicit : state.tag, state.any); if (input.isError(body)) return body; if (state.any) result = input.raw(_save);else input = body; } if (options && options.track && state.tag !== null) options.track(input.path(), start, input.length, 'tagged'); if (options && options.track && state.tag !== null) options.track(input.path(), input.offset, input.length, 'content'); // Select proper method for tag if (state.any) {// no-op } else if (state.choice === null) { result = this._decodeGeneric(state.tag, input, options); } else { result = this._decodeChoice(input, options); } if (input.isError(result)) return result; // Decode children if (!state.any && state.choice === null && state.children !== null) { state.children.forEach(function decodeChildren(child) { // NOTE: We are ignoring errors here, to let parser continue with other // parts of encoded data child._decode(input, options); }); } // Decode contained/encoded by schema, only in bit or octet strings if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { var data = new DecoderBuffer(result); result = this._getUse(state.contains, input._reporterState.obj)._decode(data, options); } } // Pop object if (state.obj && present) result = input.leaveObject(prevObj); // Set key if (state.key !== null && (result !== null || present === true)) input.leaveKey(prevKey, state.key, result);else if (prevKey !== null) input.exitKey(prevKey); return result; }; Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { var state = this._baseState; if (tag === 'seq' || tag === 'set') return null; if (tag === 'seqof' || tag === 'setof') return this._decodeList(input, tag, state.args[0], options);else if (/str$/.test(tag)) return this._decodeStr(input, tag, options);else if (tag === 'objid' && state.args) return this._decodeObjid(input, state.args[0], state.args[1], options);else if (tag === 'objid') return this._decodeObjid(input, null, null, options);else if (tag === 'gentime' || tag === 'utctime') return this._decodeTime(input, tag, options);else if (tag === 'null_') return this._decodeNull(input, options);else if (tag === 'bool') return this._decodeBool(input, options);else if (tag === 'objDesc') return this._decodeStr(input, tag, options);else if (tag === 'int' || tag === 'enum') return this._decodeInt(input, state.args && state.args[0], options); if (state.use !== null) { return this._getUse(state.use, input._reporterState.obj)._decode(input, options); } else { return input.error('unknown tag: ' + tag); } }; Node.prototype._getUse = function _getUse(entity, obj) { var state = this._baseState; // Create altered use decoder if implicit is set state.useDecoder = this._use(entity, obj); assert(state.useDecoder._baseState.parent === null); state.useDecoder = state.useDecoder._baseState.children[0]; if (state.implicit !== state.useDecoder._baseState.implicit) { state.useDecoder = state.useDecoder.clone(); state.useDecoder._baseState.implicit = state.implicit; } return state.useDecoder; }; Node.prototype._decodeChoice = function decodeChoice(input, options) { var state = this._baseState; var result = null; var match = false; Object.keys(state.choice).some(function (key) { var save = input.save(); var node = state.choice[key]; try { var value = node._decode(input, options); if (input.isError(value)) return false; result = { type: key, value: value }; match = true; } catch (e) { input.restore(save); return false; } return true; }, this); if (!match) return input.error('Choice not matched'); return result; }; // // Encoding // Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { return new EncoderBuffer(data, this.reporter); }; Node.prototype._encode = function encode(data, reporter, parent) { var state = this._baseState; if (state['default'] !== null && state['default'] === data) return; var result = this._encodeValue(data, reporter, parent); if (result === undefined) return; if (this._skipDefault(result, reporter, parent)) return; return result; }; Node.prototype._encodeValue = function encode(data, reporter, parent) { var state = this._baseState; // Decode root node if (state.parent === null) return state.children[0]._encode(data, reporter || new Reporter()); var result = null; // Set reporter to share it with a child class this.reporter = reporter; // Check if data is there if (state.optional && data === undefined) { if (state['default'] !== null) data = state['default'];else return; } // Encode children first var content = null; var primitive = false; if (state.any) { // Anything that was given is translated to buffer result = this._createEncoderBuffer(data); } else if (state.choice) { result = this._encodeChoice(data, reporter); } else if (state.contains) { content = this._getUse(state.contains, parent)._encode(data, reporter); primitive = true; } else if (state.children) { content = state.children.map(function (child) { if (child._baseState.tag === 'null_') return child._encode(null, reporter, data); if (child._baseState.key === null) return reporter.error('Child should have a key'); var prevKey = reporter.enterKey(child._baseState.key); if (_typeof(data) !== 'object') return reporter.error('Child expected, but input is not object'); var res = child._encode(data[child._baseState.key], reporter, data); reporter.leaveKey(prevKey); return res; }, this).filter(function (child) { return child; }); content = this._createEncoderBuffer(content); } else { if (state.tag === 'seqof' || state.tag === 'setof') { // TODO(indutny): this should be thrown on DSL level if (!(state.args && state.args.length === 1)) return reporter.error('Too many args for : ' + state.tag); if (!Array.isArray(data)) return reporter.error('seqof/setof, but data is not Array'); var child = this.clone(); child._baseState.implicit = null; content = this._createEncoderBuffer(data.map(function (item) { var state = this._baseState; return this._getUse(state.args[0], data)._encode(item, reporter); }, child)); } else if (state.use !== null) { result = this._getUse(state.use, parent)._encode(data, reporter); } else { content = this._encodePrimitive(state.tag, data); primitive = true; } } // Encode data itself if (!state.any && state.choice === null) { var tag = state.implicit !== null ? state.implicit : state.tag; var cls = state.implicit === null ? 'universal' : 'context'; if (tag === null) { if (state.use === null) reporter.error('Tag could be omitted only for .use()'); } else { if (state.use === null) result = this._encodeComposite(tag, primitive, cls, content); } } // Wrap in explicit if (state.explicit !== null) result = this._encodeComposite(state.explicit, false, 'context', result); return result; }; Node.prototype._encodeChoice = function encodeChoice(data, reporter) { var state = this._baseState; var node = state.choice[data.type]; if (!node) { assert(false, data.type + ' not found in ' + JSON.stringify(Object.keys(state.choice))); } return node._encode(data.value, reporter); }; Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { var state = this._baseState; if (/str$/.test(tag)) return this._encodeStr(data, tag);else if (tag === 'objid' && state.args) return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);else if (tag === 'objid') return this._encodeObjid(data, null, null);else if (tag === 'gentime' || tag === 'utctime') return this._encodeTime(data, tag);else if (tag === 'null_') return this._encodeNull();else if (tag === 'int' || tag === 'enum') return this._encodeInt(data, state.args && state.reverseArgs[0]);else if (tag === 'bool') return this._encodeBool(data);else if (tag === 'objDesc') return this._encodeStr(data, tag);else throw new Error('Unsupported tag: ' + tag); }; Node.prototype._isNumstr = function isNumstr(str) { return /^[0-9 ]*$/.test(str); }; Node.prototype._isPrintstr = function isPrintstr(str) { return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str); }; /***/ }), /***/ 1269: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var inherits = __webpack_require__(376); function Reporter(options) { this._reporterState = { obj: null, path: [], options: options || {}, errors: [] }; } exports.b = Reporter; Reporter.prototype.isError = function isError(obj) { return obj instanceof ReporterError; }; Reporter.prototype.save = function save() { var state = this._reporterState; return { obj: state.obj, pathLen: state.path.length }; }; Reporter.prototype.restore = function restore(data) { var state = this._reporterState; state.obj = data.obj; state.path = state.path.slice(0, data.pathLen); }; Reporter.prototype.enterKey = function enterKey(key) { return this._reporterState.path.push(key); }; Reporter.prototype.exitKey = function exitKey(index) { var state = this._reporterState; state.path = state.path.slice(0, index - 1); }; Reporter.prototype.leaveKey = function leaveKey(index, key, value) { var state = this._reporterState; this.exitKey(index); if (state.obj !== null) state.obj[key] = value; }; Reporter.prototype.path = function path() { return this._reporterState.path.join('/'); }; Reporter.prototype.enterObject = function enterObject() { var state = this._reporterState; var prev = state.obj; state.obj = {}; return prev; }; Reporter.prototype.leaveObject = function leaveObject(prev) { var state = this._reporterState; var now = state.obj; state.obj = prev; return now; }; Reporter.prototype.error = function error(msg) { var err; var state = this._reporterState; var inherited = msg instanceof ReporterError; if (inherited) { err = msg; } else { err = new ReporterError(state.path.map(function (elem) { return '[' + JSON.stringify(elem) + ']'; }).join(''), msg.message || msg, msg.stack); } if (!state.options.partial) throw err; if (!inherited) state.errors.push(err); return err; }; Reporter.prototype.wrapResult = function wrapResult(result) { var state = this._reporterState; if (!state.options.partial) return result; return { result: this.isError(result) ? null : result, errors: state.errors }; }; function ReporterError(path, msg) { this.path = path; this.rethrow(msg); } inherits(ReporterError, Error); ReporterError.prototype.rethrow = function rethrow(msg) { this.message = msg + ' at: ' + (this.path || '(shallow)'); if (Error.captureStackTrace) Error.captureStackTrace(this, ReporterError); if (!this.stack) { try { // IE only adds stack when thrown throw new Error(this.message); } catch (e) { this.stack = e.stack; } } return this; }; /***/ }), /***/ 2007: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Helper function reverse(map) { var res = {}; Object.keys(map).forEach(function (key) { // Convert key to integer if it is stringified if ((key | 0) == key) key = key | 0; var value = map[key]; res[value] = key; }); return res; } exports.tagClass = { 0: 'universal', 1: 'application', 2: 'context', 3: 'private' }; exports.tagClassByName = reverse(exports.tagClass); exports.tag = { 0x00: 'end', 0x01: 'bool', 0x02: 'int', 0x03: 'bitstr', 0x04: 'octstr', 0x05: 'null_', 0x06: 'objid', 0x07: 'objDesc', 0x08: 'external', 0x09: 'real', 0x0a: 'enum', 0x0b: 'embed', 0x0c: 'utf8str', 0x0d: 'relativeOid', 0x10: 'seq', 0x11: 'set', 0x12: 'numstr', 0x13: 'printstr', 0x14: 't61str', 0x15: 'videostr', 0x16: 'ia5str', 0x17: 'utctime', 0x18: 'gentime', 0x19: 'graphstr', 0x1a: 'iso646str', 0x1b: 'genstr', 0x1c: 'unistr', 0x1d: 'charstr', 0x1e: 'bmpstr' }; exports.tagByName = reverse(exports.tag); /***/ }), /***/ 4319: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var constants = exports; // Helper constants._reverse = function reverse(map) { var res = {}; Object.keys(map).forEach(function (key) { // Convert key to integer if it is stringified if ((key | 0) == key) key = key | 0; var value = map[key]; res[value] = key; }); return res; }; constants.der = __webpack_require__(2007); /***/ }), /***/ 4201: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var inherits = __webpack_require__(376); var bignum = __webpack_require__(6781); var DecoderBuffer = (__webpack_require__(4989)/* .DecoderBuffer */ .C); var Node = __webpack_require__(3304); // Import DER constants var der = __webpack_require__(2007); function DERDecoder(entity) { this.enc = 'der'; this.name = entity.name; this.entity = entity; // Construct base tree this.tree = new DERNode(); this.tree._init(entity.body); } module.exports = DERDecoder; DERDecoder.prototype.decode = function decode(data, options) { if (!DecoderBuffer.isDecoderBuffer(data)) { data = new DecoderBuffer(data, options); } return this.tree._decode(data, options); }; // Tree methods function DERNode(parent) { Node.call(this, 'der', parent); } inherits(DERNode, Node); DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { if (buffer.isEmpty()) return false; var state = buffer.save(); var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); if (buffer.isError(decodedTag)) return decodedTag; buffer.restore(state); return decodedTag.tag === tag || decodedTag.tagStr === tag || decodedTag.tagStr + 'of' === tag || any; }; DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { var decodedTag = derDecodeTag(buffer, 'Failed to decode tag of "' + tag + '"'); if (buffer.isError(decodedTag)) return decodedTag; var len = derDecodeLen(buffer, decodedTag.primitive, 'Failed to get length of "' + tag + '"'); // Failure if (buffer.isError(len)) return len; if (!any && decodedTag.tag !== tag && decodedTag.tagStr !== tag && decodedTag.tagStr + 'of' !== tag) { return buffer.error('Failed to match tag: "' + tag + '"'); } if (decodedTag.primitive || len !== null) return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); // Indefinite length... find END tag var state = buffer.save(); var res = this._skipUntilEnd(buffer, 'Failed to skip indefinite length body: "' + this.tag + '"'); if (buffer.isError(res)) return res; len = buffer.offset - state.offset; buffer.restore(state); return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); }; DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { for (;;) { var tag = derDecodeTag(buffer, fail); if (buffer.isError(tag)) return tag; var len = derDecodeLen(buffer, tag.primitive, fail); if (buffer.isError(len)) return len; var res = void 0; if (tag.primitive || len !== null) res = buffer.skip(len);else res = this._skipUntilEnd(buffer, fail); // Failure if (buffer.isError(res)) return res; if (tag.tagStr === 'end') break; } }; DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, options) { var result = []; while (!buffer.isEmpty()) { var possibleEnd = this._peekTag(buffer, 'end'); if (buffer.isError(possibleEnd)) return possibleEnd; var res = decoder.decode(buffer, 'der', options); if (buffer.isError(res) && possibleEnd) break; result.push(res); } return result; }; DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { if (tag === 'bitstr') { var unused = buffer.readUInt8(); if (buffer.isError(unused)) return unused; return { unused: unused, data: buffer.raw() }; } else if (tag === 'bmpstr') { var raw = buffer.raw(); if (raw.length % 2 === 1) return buffer.error('Decoding of string type: bmpstr length mismatch'); var str = ''; for (var i = 0; i < raw.length / 2; i++) { str += String.fromCharCode(raw.readUInt16BE(i * 2)); } return str; } else if (tag === 'numstr') { var numstr = buffer.raw().toString('ascii'); if (!this._isNumstr(numstr)) { return buffer.error('Decoding of string type: ' + 'numstr unsupported characters'); } return numstr; } else if (tag === 'octstr') { return buffer.raw(); } else if (tag === 'objDesc') { return buffer.raw(); } else if (tag === 'printstr') { var printstr = buffer.raw().toString('ascii'); if (!this._isPrintstr(printstr)) { return buffer.error('Decoding of string type: ' + 'printstr unsupported characters'); } return printstr; } else if (/str$/.test(tag)) { return buffer.raw().toString(); } else { return buffer.error('Decoding of string type: ' + tag + ' unsupported'); } }; DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { var result; var identifiers = []; var ident = 0; var subident = 0; while (!buffer.isEmpty()) { subident = buffer.readUInt8(); ident <<= 7; ident |= subident & 0x7f; if ((subident & 0x80) === 0) { identifiers.push(ident); ident = 0; } } if (subident & 0x80) identifiers.push(ident); var first = identifiers[0] / 40 | 0; var second = identifiers[0] % 40; if (relative) result = identifiers;else result = [first, second].concat(identifiers.slice(1)); if (values) { var tmp = values[result.join(' ')]; if (tmp === undefined) tmp = values[result.join('.')]; if (tmp !== undefined) result = tmp; } return result; }; DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { var str = buffer.raw().toString(); var year; var mon; var day; var hour; var min; var sec; if (tag === 'gentime') { year = str.slice(0, 4) | 0; mon = str.slice(4, 6) | 0; day = str.slice(6, 8) | 0; hour = str.slice(8, 10) | 0; min = str.slice(10, 12) | 0; sec = str.slice(12, 14) | 0; } else if (tag === 'utctime') { year = str.slice(0, 2) | 0; mon = str.slice(2, 4) | 0; day = str.slice(4, 6) | 0; hour = str.slice(6, 8) | 0; min = str.slice(8, 10) | 0; sec = str.slice(10, 12) | 0; if (year < 70) year = 2000 + year;else year = 1900 + year; } else { return buffer.error('Decoding ' + tag + ' time is not supported yet'); } return Date.UTC(year, mon - 1, day, hour, min, sec, 0); }; DERNode.prototype._decodeNull = function decodeNull() { return null; }; DERNode.prototype._decodeBool = function decodeBool(buffer) { var res = buffer.readUInt8(); if (buffer.isError(res)) return res;else return res !== 0; }; DERNode.prototype._decodeInt = function decodeInt(buffer, values) { // Bigint, return as it is (assume big endian) var raw = buffer.raw(); var res = new bignum(raw); if (values) res = values[res.toString(10)] || res; return res; }; DERNode.prototype._use = function use(entity, obj) { if (typeof entity === 'function') entity = entity(obj); return entity._getDecoder('der').tree; }; // Utility methods function derDecodeTag(buf, fail) { var tag = buf.readUInt8(fail); if (buf.isError(tag)) return tag; var cls = der.tagClass[tag >> 6]; var primitive = (tag & 0x20) === 0; // Multi-octet tag - load if ((tag & 0x1f) === 0x1f) { var oct = tag; tag = 0; while ((oct & 0x80) === 0x80) { oct = buf.readUInt8(fail); if (buf.isError(oct)) return oct; tag <<= 7; tag |= oct & 0x7f; } } else { tag &= 0x1f; } var tagStr = der.tag[tag]; return { cls: cls, primitive: primitive, tag: tag, tagStr: tagStr }; } function derDecodeLen(buf, primitive, fail) { var len = buf.readUInt8(fail); if (buf.isError(len)) return len; // Indefinite form if (!primitive && len === 0x80) return null; // Definite form if ((len & 0x80) === 0) { // Short form return len; } // Long form var num = len & 0x7f; if (num > 4) return buf.error('length octect is too long'); len = 0; for (var i = 0; i < num; i++) { len <<= 8; var j = buf.readUInt8(fail); if (buf.isError(j)) return j; len |= j; } return len; } /***/ }), /***/ 4049: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var decoders = exports; decoders.der = __webpack_require__(4201); decoders.pem = __webpack_require__(618); /***/ }), /***/ 618: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var inherits = __webpack_require__(376); var Buffer = (__webpack_require__(8723).Buffer); var DERDecoder = __webpack_require__(4201); function PEMDecoder(entity) { DERDecoder.call(this, entity); this.enc = 'pem'; } inherits(PEMDecoder, DERDecoder); module.exports = PEMDecoder; PEMDecoder.prototype.decode = function decode(data, options) { var lines = data.toString().split(/[\r\n]+/g); var label = options.label.toUpperCase(); var re = /^-----(BEGIN|END) ([^-]+)-----$/; var start = -1; var end = -1; for (var i = 0; i < lines.length; i++) { var match = lines[i].match(re); if (match === null) continue; if (match[2] !== label) continue; if (start === -1) { if (match[1] !== 'BEGIN') break; start = i; } else { if (match[1] !== 'END') break; end = i; break; } } if (start === -1 || end === -1) throw new Error('PEM section not found for: ' + label); var base64 = lines.slice(start + 1, end).join(''); // Remove excessive symbols base64.replace(/[^a-z0-9+/=]+/gi, ''); var input = Buffer.from(base64, 'base64'); return DERDecoder.prototype.decode.call(this, input, options); }; /***/ }), /***/ 1889: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var inherits = __webpack_require__(376); var Buffer = (__webpack_require__(8723).Buffer); var Node = __webpack_require__(3304); // Import DER constants var der = __webpack_require__(2007); function DEREncoder(entity) { this.enc = 'der'; this.name = entity.name; this.entity = entity; // Construct base tree this.tree = new DERNode(); this.tree._init(entity.body); } module.exports = DEREncoder; DEREncoder.prototype.encode = function encode(data, reporter) { return this.tree._encode(data, reporter).join(); }; // Tree methods function DERNode(parent) { Node.call(this, 'der', parent); } inherits(DERNode, Node); DERNode.prototype._encodeComposite = function encodeComposite(tag, primitive, cls, content) { var encodedTag = encodeTag(tag, primitive, cls, this.reporter); // Short form if (content.length < 0x80) { var _header = Buffer.alloc(2); _header[0] = encodedTag; _header[1] = content.length; return this._createEncoderBuffer([_header, content]); } // Long form // Count octets required to store length var lenOctets = 1; for (var i = content.length; i >= 0x100; i >>= 8) { lenOctets++; } var header = Buffer.alloc(1 + 1 + lenOctets); header[0] = encodedTag; header[1] = 0x80 | lenOctets; for (var _i = 1 + lenOctets, j = content.length; j > 0; _i--, j >>= 8) { header[_i] = j & 0xff; } return this._createEncoderBuffer([header, content]); }; DERNode.prototype._encodeStr = function encodeStr(str, tag) { if (tag === 'bitstr') { return this._createEncoderBuffer([str.unused | 0, str.data]); } else if (tag === 'bmpstr') { var buf = Buffer.alloc(str.length * 2); for (var i = 0; i < str.length; i++) { buf.writeUInt16BE(str.charCodeAt(i), i * 2); } return this._createEncoderBuffer(buf); } else if (tag === 'numstr') { if (!this._isNumstr(str)) { return this.reporter.error('Encoding of string type: numstr supports ' + 'only digits and space'); } return this._createEncoderBuffer(str); } else if (tag === 'printstr') { if (!this._isPrintstr(str)) { return this.reporter.error('Encoding of string type: printstr supports ' + 'only latin upper and lower case letters, ' + 'digits, space, apostrophe, left and rigth ' + 'parenthesis, plus sign, comma, hyphen, ' + 'dot, slash, colon, equal sign, ' + 'question mark'); } return this._createEncoderBuffer(str); } else if (/str$/.test(tag)) { return this._createEncoderBuffer(str); } else if (tag === 'objDesc') { return this._createEncoderBuffer(str); } else { return this.reporter.error('Encoding of string type: ' + tag + ' unsupported'); } }; DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { if (typeof id === 'string') { if (!values) return this.reporter.error('string objid given, but no values map found'); if (!values.hasOwnProperty(id)) return this.reporter.error('objid not found in values map'); id = values[id].split(/[\s.]+/g); for (var i = 0; i < id.length; i++) { id[i] |= 0; } } else if (Array.isArray(id)) { id = id.slice(); for (var _i2 = 0; _i2 < id.length; _i2++) { id[_i2] |= 0; } } if (!Array.isArray(id)) { return this.reporter.error('objid() should be either array or string, ' + 'got: ' + JSON.stringify(id)); } if (!relative) { if (id[1] >= 40) return this.reporter.error('Second objid identifier OOB'); id.splice(0, 2, id[0] * 40 + id[1]); } // Count number of octets var size = 0; for (var _i3 = 0; _i3 < id.length; _i3++) { var ident = id[_i3]; for (size++; ident >= 0x80; ident >>= 7) { size++; } } var objid = Buffer.alloc(size); var offset = objid.length - 1; for (var _i4 = id.length - 1; _i4 >= 0; _i4--) { var _ident = id[_i4]; objid[offset--] = _ident & 0x7f; while ((_ident >>= 7) > 0) { objid[offset--] = 0x80 | _ident & 0x7f; } } return this._createEncoderBuffer(objid); }; function two(num) { if (num < 10) return '0' + num;else return num; } DERNode.prototype._encodeTime = function encodeTime(time, tag) { var str; var date = new Date(time); if (tag === 'gentime') { str = [two(date.getUTCFullYear()), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z'].join(''); } else if (tag === 'utctime') { str = [two(date.getUTCFullYear() % 100), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z'].join(''); } else { this.reporter.error('Encoding ' + tag + ' time is not supported yet'); } return this._encodeStr(str, 'octstr'); }; DERNode.prototype._encodeNull = function encodeNull() { return this._createEncoderBuffer(''); }; DERNode.prototype._encodeInt = function encodeInt(num, values) { if (typeof num === 'string') { if (!values) return this.reporter.error('String int or enum given, but no values map'); if (!values.hasOwnProperty(num)) { return this.reporter.error('Values map doesn\'t contain: ' + JSON.stringify(num)); } num = values[num]; } // Bignum, assume big endian if (typeof num !== 'number' && !Buffer.isBuffer(num)) { var numArray = num.toArray(); if (!num.sign && numArray[0] & 0x80) { numArray.unshift(0); } num = Buffer.from(numArray); } if (Buffer.isBuffer(num)) { var _size = num.length; if (num.length === 0) _size++; var _out = Buffer.alloc(_size); num.copy(_out); if (num.length === 0) _out[0] = 0; return this._createEncoderBuffer(_out); } if (num < 0x80) return this._createEncoderBuffer(num); if (num < 0x100) return this._createEncoderBuffer([0, num]); var size = 1; for (var i = num; i >= 0x100; i >>= 8) { size++; } var out = new Array(size); for (var _i5 = out.length - 1; _i5 >= 0; _i5--) { out[_i5] = num & 0xff; num >>= 8; } if (out[0] & 0x80) { out.unshift(0); } return this._createEncoderBuffer(Buffer.from(out)); }; DERNode.prototype._encodeBool = function encodeBool(value) { return this._createEncoderBuffer(value ? 0xff : 0); }; DERNode.prototype._use = function use(entity, obj) { if (typeof entity === 'function') entity = entity(obj); return entity._getEncoder('der').tree; }; DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { var state = this._baseState; var i; if (state['default'] === null) return false; var data = dataBuffer.join(); if (state.defaultBuffer === undefined) state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); if (data.length !== state.defaultBuffer.length) return false; for (i = 0; i < data.length; i++) { if (data[i] !== state.defaultBuffer[i]) return false; } return true; }; // Utility methods function encodeTag(tag, primitive, cls, reporter) { var res; if (tag === 'seqof') tag = 'seq';else if (tag === 'setof') tag = 'set'; if (der.tagByName.hasOwnProperty(tag)) res = der.tagByName[tag];else if (typeof tag === 'number' && (tag | 0) === tag) res = tag;else return reporter.error('Unknown tag: ' + tag); if (res >= 0x1f) return reporter.error('Multi-octet tag encoding unsupported'); if (!primitive) res |= 0x20; res |= der.tagClassByName[cls || 'universal'] << 6; return res; } /***/ }), /***/ 6860: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var encoders = exports; encoders.der = __webpack_require__(1889); encoders.pem = __webpack_require__(1610); /***/ }), /***/ 1610: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var inherits = __webpack_require__(376); var DEREncoder = __webpack_require__(1889); function PEMEncoder(entity) { DEREncoder.call(this, entity); this.enc = 'pem'; } inherits(PEMEncoder, DEREncoder); module.exports = PEMEncoder; PEMEncoder.prototype.encode = function encode(data, options) { var buf = DEREncoder.prototype.encode.call(this, data); var p = buf.toString('base64'); var out = ['-----BEGIN ' + options.label + '-----']; for (var i = 0; i < p.length; i += 64) { out.push(p.slice(i, i + 64)); } out.push('-----END ' + options.label + '-----'); return out.join('\n'); }; /***/ }), /***/ 9373: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Currently in sync with Node.js lib/assert.js // https://github.com/nodejs/node/commit/2a51ae424a513ec9a6aa3466baa0cc1d55dd4f3b // Originally from narwhal.js (http://narwhaljs.org) // Copyright (c) 2009 Thomas Robinson <280north.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the 'Software'), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. function _typeof2(obj) { "@babel/helpers - typeof"; return _typeof2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof2(obj); } function _typeof(obj) { if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") { _typeof = function _typeof(obj) { return _typeof2(obj); }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj); }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _require = __webpack_require__(9978), _require$codes = _require.codes, ERR_AMBIGUOUS_ARGUMENT = _require$codes.ERR_AMBIGUOUS_ARGUMENT, ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE = _require$codes.ERR_INVALID_ARG_VALUE, ERR_INVALID_RETURN_VALUE = _require$codes.ERR_INVALID_RETURN_VALUE, ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; var AssertionError = __webpack_require__(1935); var _require2 = __webpack_require__(161), inspect = _require2.inspect; var _require$types = (__webpack_require__(161).types), isPromise = _require$types.isPromise, isRegExp = _require$types.isRegExp; var objectAssign = Object.assign ? Object.assign : (__webpack_require__(8028).assign); var objectIs = Object.is ? Object.is : __webpack_require__(4710); var errorCache = new Map(); var isDeepEqual; var isDeepStrictEqual; var parseExpressionAt; var findNodeAround; var decoder; function lazyLoadComparison() { var comparison = __webpack_require__(9015); isDeepEqual = comparison.isDeepEqual; isDeepStrictEqual = comparison.isDeepStrictEqual; } // Escape control characters but not \n and \t to keep the line breaks and // indentation intact. // eslint-disable-next-line no-control-regex var escapeSequencesRegExp = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g; var meta = (/* unused pure expression or super */ null && (["\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", "\\u0006", "\\u0007", '\\b', '', '', "\\u000b", '\\f', '', "\\u000e", "\\u000f", "\\u0010", "\\u0011", "\\u0012", "\\u0013", "\\u0014", "\\u0015", "\\u0016", "\\u0017", "\\u0018", "\\u0019", "\\u001a", "\\u001b", "\\u001c", "\\u001d", "\\u001e", "\\u001f"])); var escapeFn = function escapeFn(str) { return meta[str.charCodeAt(0)]; }; var warned = false; // The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. var assert = module.exports = ok; var NO_EXCEPTION_SENTINEL = {}; // All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for // display purposes. function innerFail(obj) { if (obj.message instanceof Error) throw obj.message; throw new AssertionError(obj); } function fail(actual, expected, message, operator, stackStartFn) { var argsLen = arguments.length; var internalMessage; if (argsLen === 0) { internalMessage = 'Failed'; } else if (argsLen === 1) { message = actual; actual = undefined; } else { if (warned === false) { warned = true; var warn = ({env:{}}).emitWarning ? ({env:{}}).emitWarning : console.warn.bind(console); warn('assert.fail() with more than one argument is deprecated. ' + 'Please use assert.strictEqual() instead or only pass a message.', 'DeprecationWarning', 'DEP0094'); } if (argsLen === 2) operator = '!='; } if (message instanceof Error) throw message; var errArgs = { actual: actual, expected: expected, operator: operator === undefined ? 'fail' : operator, stackStartFn: stackStartFn || fail }; if (message !== undefined) { errArgs.message = message; } var err = new AssertionError(errArgs); if (internalMessage) { err.message = internalMessage; err.generatedMessage = true; } throw err; } assert.fail = fail; // The AssertionError is defined in internal/error. assert.AssertionError = AssertionError; function innerOk(fn, argLen, value, message) { if (!value) { var generatedMessage = false; if (argLen === 0) { generatedMessage = true; message = 'No value argument passed to `assert.ok()`'; } else if (message instanceof Error) { throw message; } var err = new AssertionError({ actual: value, expected: true, message: message, operator: '==', stackStartFn: fn }); err.generatedMessage = generatedMessage; throw err; } } // Pure assertion tests whether a value is truthy, as determined // by !!value. function ok() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } innerOk.apply(void 0, [ok, args.length].concat(args)); } assert.ok = ok; // The equality assertion tests shallow, coercive equality with ==. /* eslint-disable no-restricted-properties */ assert.equal = function equal(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } // eslint-disable-next-line eqeqeq if (actual != expected) { innerFail({ actual: actual, expected: expected, message: message, operator: '==', stackStartFn: equal }); } }; // The non-equality assertion tests for whether two objects are not // equal with !=. assert.notEqual = function notEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } // eslint-disable-next-line eqeqeq if (actual == expected) { innerFail({ actual: actual, expected: expected, message: message, operator: '!=', stackStartFn: notEqual }); } }; // The equivalence assertion tests a deep equality relation. assert.deepEqual = function deepEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } if (isDeepEqual === undefined) lazyLoadComparison(); if (!isDeepEqual(actual, expected)) { innerFail({ actual: actual, expected: expected, message: message, operator: 'deepEqual', stackStartFn: deepEqual }); } }; // The non-equivalence assertion tests for any deep inequality. assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } if (isDeepEqual === undefined) lazyLoadComparison(); if (isDeepEqual(actual, expected)) { innerFail({ actual: actual, expected: expected, message: message, operator: 'notDeepEqual', stackStartFn: notDeepEqual }); } }; /* eslint-enable */ assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } if (isDeepEqual === undefined) lazyLoadComparison(); if (!isDeepStrictEqual(actual, expected)) { innerFail({ actual: actual, expected: expected, message: message, operator: 'deepStrictEqual', stackStartFn: deepStrictEqual }); } }; assert.notDeepStrictEqual = notDeepStrictEqual; function notDeepStrictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } if (isDeepEqual === undefined) lazyLoadComparison(); if (isDeepStrictEqual(actual, expected)) { innerFail({ actual: actual, expected: expected, message: message, operator: 'notDeepStrictEqual', stackStartFn: notDeepStrictEqual }); } } assert.strictEqual = function strictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } if (!objectIs(actual, expected)) { innerFail({ actual: actual, expected: expected, message: message, operator: 'strictEqual', stackStartFn: strictEqual }); } }; assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS('actual', 'expected'); } if (objectIs(actual, expected)) { innerFail({ actual: actual, expected: expected, message: message, operator: 'notStrictEqual', stackStartFn: notStrictEqual }); } }; var Comparison = function Comparison(obj, keys, actual) { var _this = this; _classCallCheck(this, Comparison); keys.forEach(function (key) { if (key in obj) { if (actual !== undefined && typeof actual[key] === 'string' && isRegExp(obj[key]) && obj[key].test(actual[key])) { _this[key] = actual[key]; } else { _this[key] = obj[key]; } } }); }; function compareExceptionKey(actual, expected, key, message, keys, fn) { if (!(key in actual) || !isDeepStrictEqual(actual[key], expected[key])) { if (!message) { // Create placeholder objects to create a nice output. var a = new Comparison(actual, keys); var b = new Comparison(expected, keys, actual); var err = new AssertionError({ actual: a, expected: b, operator: 'deepStrictEqual', stackStartFn: fn }); err.actual = actual; err.expected = expected; err.operator = fn.name; throw err; } innerFail({ actual: actual, expected: expected, message: message, operator: fn.name, stackStartFn: fn }); } } function expectedException(actual, expected, msg, fn) { if (typeof expected !== 'function') { if (isRegExp(expected)) return expected.test(actual); // assert.doesNotThrow does not accept objects. if (arguments.length === 2) { throw new ERR_INVALID_ARG_TYPE('expected', ['Function', 'RegExp'], expected); } // Handle primitives properly. if (_typeof(actual) !== 'object' || actual === null) { var err = new AssertionError({ actual: actual, expected: expected, message: msg, operator: 'deepStrictEqual', stackStartFn: fn }); err.operator = fn.name; throw err; } var keys = Object.keys(expected); // Special handle errors to make sure the name and the message are compared // as well. if (expected instanceof Error) { keys.push('name', 'message'); } else if (keys.length === 0) { throw new ERR_INVALID_ARG_VALUE('error', expected, 'may not be an empty object'); } if (isDeepEqual === undefined) lazyLoadComparison(); keys.forEach(function (key) { if (typeof actual[key] === 'string' && isRegExp(expected[key]) && expected[key].test(actual[key])) { return; } compareExceptionKey(actual, expected, key, msg, keys, fn); }); return true; } // Guard instanceof against arrow functions as they don't have a prototype. if (expected.prototype !== undefined && actual instanceof expected) { return true; } if (Error.isPrototypeOf(expected)) { return false; } return expected.call({}, actual) === true; } function getActual(fn) { if (typeof fn !== 'function') { throw new ERR_INVALID_ARG_TYPE('fn', 'Function', fn); } try { fn(); } catch (e) { return e; } return NO_EXCEPTION_SENTINEL; } function checkIsPromise(obj) { // Accept native ES6 promises and promises that are implemented in a similar // way. Do not accept thenables that use a function as `obj` and that have no // `catch` handler. // TODO: thenables are checked up until they have the correct methods, // but according to documentation, the `then` method should receive // the `fulfill` and `reject` arguments as well or it may be never resolved. return isPromise(obj) || obj !== null && _typeof(obj) === 'object' && typeof obj.then === 'function' && typeof obj["catch"] === 'function'; } function waitForActual(promiseFn) { return Promise.resolve().then(function () { var resultPromise; if (typeof promiseFn === 'function') { // Return a rejected promise if `promiseFn` throws synchronously. resultPromise = promiseFn(); // Fail in case no promise is returned. if (!checkIsPromise(resultPromise)) { throw new ERR_INVALID_RETURN_VALUE('instance of Promise', 'promiseFn', resultPromise); } } else if (checkIsPromise(promiseFn)) { resultPromise = promiseFn; } else { throw new ERR_INVALID_ARG_TYPE('promiseFn', ['Function', 'Promise'], promiseFn); } return Promise.resolve().then(function () { return resultPromise; }).then(function () { return NO_EXCEPTION_SENTINEL; })["catch"](function (e) { return e; }); }); } function expectsError(stackStartFn, actual, error, message) { if (typeof error === 'string') { if (arguments.length === 4) { throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error); } if (_typeof(actual) === 'object' && actual !== null) { if (actual.message === error) { throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error message \"".concat(actual.message, "\" is identical to the message.")); } } else if (actual === error) { throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error \"".concat(actual, "\" is identical to the message.")); } message = error; error = undefined; } else if (error != null && _typeof(error) !== 'object' && typeof error !== 'function') { throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error); } if (actual === NO_EXCEPTION_SENTINEL) { var details = ''; if (error && error.name) { details += " (".concat(error.name, ")"); } details += message ? ": ".concat(message) : '.'; var fnType = stackStartFn.name === 'rejects' ? 'rejection' : 'exception'; innerFail({ actual: undefined, expected: error, operator: stackStartFn.name, message: "Missing expected ".concat(fnType).concat(details), stackStartFn: stackStartFn }); } if (error && !expectedException(actual, error, message, stackStartFn)) { throw actual; } } function expectsNoError(stackStartFn, actual, error, message) { if (actual === NO_EXCEPTION_SENTINEL) return; if (typeof error === 'string') { message = error; error = undefined; } if (!error || expectedException(actual, error)) { var details = message ? ": ".concat(message) : '.'; var fnType = stackStartFn.name === 'doesNotReject' ? 'rejection' : 'exception'; innerFail({ actual: actual, expected: error, operator: stackStartFn.name, message: "Got unwanted ".concat(fnType).concat(details, "\n") + "Actual message: \"".concat(actual && actual.message, "\""), stackStartFn: stackStartFn }); } throw actual; } assert["throws"] = function _throws(promiseFn) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } expectsError.apply(void 0, [_throws, getActual(promiseFn)].concat(args)); }; assert.rejects = function rejects(promiseFn) { for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } return waitForActual(promiseFn).then(function (result) { return expectsError.apply(void 0, [rejects, result].concat(args)); }); }; assert.doesNotThrow = function doesNotThrow(fn) { for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { args[_key4 - 1] = arguments[_key4]; } expectsNoError.apply(void 0, [doesNotThrow, getActual(fn)].concat(args)); }; assert.doesNotReject = function doesNotReject(fn) { for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { args[_key5 - 1] = arguments[_key5]; } return waitForActual(fn).then(function (result) { return expectsNoError.apply(void 0, [doesNotReject, result].concat(args)); }); }; assert.ifError = function ifError(err) { if (err !== null && err !== undefined) { var message = 'ifError got unwanted exception: '; if (_typeof(err) === 'object' && typeof err.message === 'string') { if (err.message.length === 0 && err.constructor) { message += err.constructor.name; } else { message += err.message; } } else { message += inspect(err); } var newErr = new AssertionError({ actual: err, expected: null, operator: 'ifError', message: message, stackStartFn: ifError }); // Make sure we actually have a stack trace! var origStack = err.stack; if (typeof origStack === 'string') { // This will remove any duplicated frames from the error frames taken // from within `ifError` and add the original error frames to the newly // created ones. var tmp2 = origStack.split('\n'); tmp2.shift(); // Filter all frames existing in err.stack. var tmp1 = newErr.stack.split('\n'); for (var i = 0; i < tmp2.length; i++) { // Find the first occurrence of the frame. var pos = tmp1.indexOf(tmp2[i]); if (pos !== -1) { // Only keep new frames. tmp1 = tmp1.slice(0, pos); break; } } newErr.stack = "".concat(tmp1.join('\n'), "\n").concat(tmp2.join('\n')); } throw newErr; } }; // Expose a strict only variant of assert function strict() { for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } innerOk.apply(void 0, [strict, args.length].concat(args)); } assert.strict = objectAssign(strict, assert, { equal: assert.strictEqual, deepEqual: assert.deepStrictEqual, notEqual: assert.notStrictEqual, notDeepEqual: assert.notDeepStrictEqual }); assert.strict.strict = assert.strict; /***/ }), /***/ 1935: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Currently in sync with Node.js lib/internal/assert/assertion_error.js // https://github.com/nodejs/node/commit/0817840f775032169ddd70c85ac059f18ffcc81c function _typeof2(obj) { "@babel/helpers - typeof"; return _typeof2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof2(obj); } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _typeof(obj) { if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") { _typeof = function _typeof(obj) { return _typeof2(obj); }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj); }; } return _typeof(obj); } var _require = __webpack_require__(161), inspect = _require.inspect; var _require2 = __webpack_require__(9978), ERR_INVALID_ARG_TYPE = _require2.codes.ERR_INVALID_ARG_TYPE; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith function endsWith(str, search, this_len) { if (this_len === undefined || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat function repeat(str, count) { count = Math.floor(count); if (str.length == 0 || count == 0) return ''; var maxCount = str.length * count; count = Math.floor(Math.log(count) / Math.log(2)); while (count) { str += str; count--; } str += str.substring(0, maxCount - str.length); return str; } var blue = ''; var green = ''; var red = ''; var white = ''; var kReadableOperator = { deepStrictEqual: 'Expected values to be strictly deep-equal:', strictEqual: 'Expected values to be strictly equal:', strictEqualObject: 'Expected "actual" to be reference-equal to "expected":', deepEqual: 'Expected values to be loosely deep-equal:', equal: 'Expected values to be loosely equal:', notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:', notStrictEqual: 'Expected "actual" to be strictly unequal to:', notStrictEqualObject: 'Expected "actual" not to be reference-equal to "expected":', notDeepEqual: 'Expected "actual" not to be loosely deep-equal to:', notEqual: 'Expected "actual" to be loosely unequal to:', notIdentical: 'Values identical but not reference-equal:' }; // Comparing short primitives should just show === / !== instead of using the // diff. var kMaxShortLength = 10; function copyError(source) { var keys = Object.keys(source); var target = Object.create(Object.getPrototypeOf(source)); keys.forEach(function (key) { target[key] = source[key]; }); Object.defineProperty(target, 'message', { value: source.message }); return target; } function inspectValue(val) { // The util.inspect default values could be changed. This makes sure the // error messages contain the necessary information nevertheless. return inspect(val, { compact: false, customInspect: false, depth: 1000, maxArrayLength: Infinity, // Assert compares only enumerable properties (with a few exceptions). showHidden: false, // Having a long line as error is better than wrapping the line for // comparison for now. // TODO(BridgeAR): `breakLength` should be limited as soon as soon as we // have meta information about the inspected properties (i.e., know where // in what line the property starts and ends). breakLength: Infinity, // Assert does not detect proxies currently. showProxy: false, sorted: true, // Inspect getters as we also check them when comparing entries. getters: true }); } function createErrDiff(actual, expected, operator) { var other = ''; var res = ''; var lastPos = 0; var end = ''; var skipped = false; var actualInspected = inspectValue(actual); var actualLines = actualInspected.split('\n'); var expectedLines = inspectValue(expected).split('\n'); var i = 0; var indicator = ''; // In case both values are objects explicitly mark them as not reference equal // for the `strictEqual` operator. if (operator === 'strictEqual' && _typeof(actual) === 'object' && _typeof(expected) === 'object' && actual !== null && expected !== null) { operator = 'strictEqualObject'; } // If "actual" and "expected" fit on a single line and they are not strictly // equal, check further special handling. if (actualLines.length === 1 && expectedLines.length === 1 && actualLines[0] !== expectedLines[0]) { var inputLength = actualLines[0].length + expectedLines[0].length; // If the character length of "actual" and "expected" together is less than // kMaxShortLength and if neither is an object and at least one of them is // not `zero`, use the strict equal comparison to visualize the output. if (inputLength <= kMaxShortLength) { if ((_typeof(actual) !== 'object' || actual === null) && (_typeof(expected) !== 'object' || expected === null) && (actual !== 0 || expected !== 0)) { // -0 === +0 return "".concat(kReadableOperator[operator], "\n\n") + "".concat(actualLines[0], " !== ").concat(expectedLines[0], "\n"); } } else if (operator !== 'strictEqualObject') { // If the stderr is a tty and the input length is lower than the current // columns per line, add a mismatch indicator below the output. If it is // not a tty, use a default value of 80 characters. var maxLength = ({env:{}}).stderr && ({env:{}}).stderr.isTTY ? ({env:{}}).stderr.columns : 80; if (inputLength < maxLength) { while (actualLines[0][i] === expectedLines[0][i]) { i++; } // Ignore the first characters. if (i > 2) { // Add position indicator for the first mismatch in case it is a // single line and the input length is less than the column length. indicator = "\n ".concat(repeat(' ', i), "^"); i = 0; } } } } // Remove all ending lines that match (this optimizes the output for // readability by reducing the number of total changed lines). var a = actualLines[actualLines.length - 1]; var b = expectedLines[expectedLines.length - 1]; while (a === b) { if (i++ < 2) { end = "\n ".concat(a).concat(end); } else { other = a; } actualLines.pop(); expectedLines.pop(); if (actualLines.length === 0 || expectedLines.length === 0) break; a = actualLines[actualLines.length - 1]; b = expectedLines[expectedLines.length - 1]; } var maxLines = Math.max(actualLines.length, expectedLines.length); // Strict equal with identical objects that are not identical by reference. // E.g., assert.deepStrictEqual({ a: Symbol() }, { a: Symbol() }) if (maxLines === 0) { // We have to get the result again. The lines were all removed before. var _actualLines = actualInspected.split('\n'); // Only remove lines in case it makes sense to collapse those. // TODO: Accept env to always show the full error. if (_actualLines.length > 30) { _actualLines[26] = "".concat(blue, "...").concat(white); while (_actualLines.length > 27) { _actualLines.pop(); } } return "".concat(kReadableOperator.notIdentical, "\n\n").concat(_actualLines.join('\n'), "\n"); } if (i > 3) { end = "\n".concat(blue, "...").concat(white).concat(end); skipped = true; } if (other !== '') { end = "\n ".concat(other).concat(end); other = ''; } var printedLines = 0; var msg = kReadableOperator[operator] + "\n".concat(green, "+ actual").concat(white, " ").concat(red, "- expected").concat(white); var skippedMsg = " ".concat(blue, "...").concat(white, " Lines skipped"); for (i = 0; i < maxLines; i++) { // Only extra expected lines exist var cur = i - lastPos; if (actualLines.length < i + 1) { // If the last diverging line is more than one line above and the // current line is at least line three, add some of the former lines and // also add dots to indicate skipped entries. if (cur > 1 && i > 2) { if (cur > 4) { res += "\n".concat(blue, "...").concat(white); skipped = true; } else if (cur > 3) { res += "\n ".concat(expectedLines[i - 2]); printedLines++; } res += "\n ".concat(expectedLines[i - 1]); printedLines++; } // Mark the current line as the last diverging one. lastPos = i; // Add the expected line to the cache. other += "\n".concat(red, "-").concat(white, " ").concat(expectedLines[i]); printedLines++; // Only extra actual lines exist } else if (expectedLines.length < i + 1) { // If the last diverging line is more than one line above and the // current line is at least line three, add some of the former lines and // also add dots to indicate skipped entries. if (cur > 1 && i > 2) { if (cur > 4) { res += "\n".concat(blue, "...").concat(white); skipped = true; } else if (cur > 3) { res += "\n ".concat(actualLines[i - 2]); printedLines++; } res += "\n ".concat(actualLines[i - 1]); printedLines++; } // Mark the current line as the last diverging one. lastPos = i; // Add the actual line to the result. res += "\n".concat(green, "+").concat(white, " ").concat(actualLines[i]); printedLines++; // Lines diverge } else { var expectedLine = expectedLines[i]; var actualLine = actualLines[i]; // If the lines diverge, specifically check for lines that only diverge by // a trailing comma. In that case it is actually identical and we should // mark it as such. var divergingLines = actualLine !== expectedLine && (!endsWith(actualLine, ',') || actualLine.slice(0, -1) !== expectedLine); // If the expected line has a trailing comma but is otherwise identical, // add a comma at the end of the actual line. Otherwise the output could // look weird as in: // // [ // 1 // No comma at the end! // + 2 // ] // if (divergingLines && endsWith(expectedLine, ',') && expectedLine.slice(0, -1) === actualLine) { divergingLines = false; actualLine += ','; } if (divergingLines) { // If the last diverging line is more than one line above and the // current line is at least line three, add some of the former lines and // also add dots to indicate skipped entries. if (cur > 1 && i > 2) { if (cur > 4) { res += "\n".concat(blue, "...").concat(white); skipped = true; } else if (cur > 3) { res += "\n ".concat(actualLines[i - 2]); printedLines++; } res += "\n ".concat(actualLines[i - 1]); printedLines++; } // Mark the current line as the last diverging one. lastPos = i; // Add the actual line to the result and cache the expected diverging // line so consecutive diverging lines show up as +++--- and not +-+-+-. res += "\n".concat(green, "+").concat(white, " ").concat(actualLine); other += "\n".concat(red, "-").concat(white, " ").concat(expectedLine); printedLines += 2; // Lines are identical } else { // Add all cached information to the result before adding other things // and reset the cache. res += other; other = ''; // If the last diverging line is exactly one line above or if it is the // very first line, add the line to the result. if (cur === 1 || i === 0) { res += "\n ".concat(actualLine); printedLines++; } } } // Inspected object to big (Show ~20 rows max) if (printedLines > 20 && i < maxLines - 2) { return "".concat(msg).concat(skippedMsg, "\n").concat(res, "\n").concat(blue, "...").concat(white).concat(other, "\n") + "".concat(blue, "...").concat(white); } } return "".concat(msg).concat(skipped ? skippedMsg : '', "\n").concat(res).concat(other).concat(end).concat(indicator); } var AssertionError = /*#__PURE__*/function (_Error) { _inherits(AssertionError, _Error); function AssertionError(options) { var _this; _classCallCheck(this, AssertionError); if (_typeof(options) !== 'object' || options === null) { throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); } var message = options.message, operator = options.operator, stackStartFn = options.stackStartFn; var actual = options.actual, expected = options.expected; var limit = Error.stackTraceLimit; Error.stackTraceLimit = 0; if (message != null) { _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, String(message))); } else { if (({env:{}}).stderr && ({env:{}}).stderr.isTTY) { // Reset on each call to make sure we handle dynamically set environment // variables correct. if (({env:{}}).stderr && ({env:{}}).stderr.getColorDepth && ({env:{}}).stderr.getColorDepth() !== 1) { blue = "\x1B[34m"; green = "\x1B[32m"; white = "\x1B[39m"; red = "\x1B[31m"; } else { blue = ''; green = ''; white = ''; red = ''; } } // Prevent the error stack from being visible by duplicating the error // in a very close way to the original in case both sides are actually // instances of Error. if (_typeof(actual) === 'object' && actual !== null && _typeof(expected) === 'object' && expected !== null && 'stack' in actual && actual instanceof Error && 'stack' in expected && expected instanceof Error) { actual = copyError(actual); expected = copyError(expected); } if (operator === 'deepStrictEqual' || operator === 'strictEqual') { _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, createErrDiff(actual, expected, operator))); } else if (operator === 'notDeepStrictEqual' || operator === 'notStrictEqual') { // In case the objects are equal but the operator requires unequal, show // the first object and say A equals B var base = kReadableOperator[operator]; var res = inspectValue(actual).split('\n'); // In case "actual" is an object, it should not be reference equal. if (operator === 'notStrictEqual' && _typeof(actual) === 'object' && actual !== null) { base = kReadableOperator.notStrictEqualObject; } // Only remove lines in case it makes sense to collapse those. // TODO: Accept env to always show the full error. if (res.length > 30) { res[26] = "".concat(blue, "...").concat(white); while (res.length > 27) { res.pop(); } } // Only print a single input. if (res.length === 1) { _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, "".concat(base, " ").concat(res[0]))); } else { _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, "".concat(base, "\n\n").concat(res.join('\n'), "\n"))); } } else { var _res = inspectValue(actual); var other = ''; var knownOperators = kReadableOperator[operator]; if (operator === 'notDeepEqual' || operator === 'notEqual') { _res = "".concat(kReadableOperator[operator], "\n\n").concat(_res); if (_res.length > 1024) { _res = "".concat(_res.slice(0, 1021), "..."); } } else { other = "".concat(inspectValue(expected)); if (_res.length > 512) { _res = "".concat(_res.slice(0, 509), "..."); } if (other.length > 512) { other = "".concat(other.slice(0, 509), "..."); } if (operator === 'deepEqual' || operator === 'equal') { _res = "".concat(knownOperators, "\n\n").concat(_res, "\n\nshould equal\n\n"); } else { other = " ".concat(operator, " ").concat(other); } } _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, "".concat(_res).concat(other))); } } Error.stackTraceLimit = limit; _this.generatedMessage = !message; Object.defineProperty(_assertThisInitialized(_this), 'name', { value: 'AssertionError [ERR_ASSERTION]', enumerable: false, writable: true, configurable: true }); _this.code = 'ERR_ASSERTION'; _this.actual = actual; _this.expected = expected; _this.operator = operator; if (Error.captureStackTrace) { // eslint-disable-next-line no-restricted-syntax Error.captureStackTrace(_assertThisInitialized(_this), stackStartFn); } // Create error message including the error code in the name. _this.stack; // Reset the name. _this.name = 'AssertionError'; return _possibleConstructorReturn(_this); } _createClass(AssertionError, [{ key: "toString", value: function toString() { return "".concat(this.name, " [").concat(this.code, "]: ").concat(this.message); } }, { key: inspect.custom, value: function value(recurseTimes, ctx) { // This limits the `actual` and `expected` property default inspection to // the minimum depth. Otherwise those values would be too verbose compared // to the actual error message which contains a combined view of these two // input values. return inspect(this, _objectSpread({}, ctx, { customInspect: false, depth: 0 })); } }]); return AssertionError; }(_wrapNativeSuper(Error)); module.exports = AssertionError; /***/ }), /***/ 9978: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Currently in sync with Node.js lib/internal/errors.js // https://github.com/nodejs/node/commit/3b044962c48fe313905877a96b5d0894a5404f6f /* eslint node-core/documented-errors: "error" */ /* eslint node-core/alphabetize-errors: "error" */ /* eslint node-core/prefer-util-format-errors: "error" */ // The whole point behind this internal module is to allow Node.js to no // longer be forced to treat every error message change as a semver-major // change. The NodeError classes here all expose a `code` property whose // value statically and permanently identifies the error. While the error // message may change, the code should not. function _typeof2(obj) { "@babel/helpers - typeof"; return _typeof2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof2(obj); } function _typeof(obj) { if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") { _typeof = function _typeof(obj) { return _typeof2(obj); }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj); }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var codes = {}; // Lazy loaded var assert; var util; function createErrorType(code, message, Base) { if (!Base) { Base = Error; } function getMessage(arg1, arg2, arg3) { if (typeof message === 'string') { return message; } else { return message(arg1, arg2, arg3); } } var NodeError = /*#__PURE__*/function (_Base) { _inherits(NodeError, _Base); function NodeError(arg1, arg2, arg3) { var _this; _classCallCheck(this, NodeError); _this = _possibleConstructorReturn(this, _getPrototypeOf(NodeError).call(this, getMessage(arg1, arg2, arg3))); _this.code = code; return _this; } return NodeError; }(Base); codes[code] = NodeError; } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js function oneOf(expected, thing) { if (Array.isArray(expected)) { var len = expected.length; expected = expected.map(function (i) { return String(i); }); if (len > 2) { return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; } else if (len === 2) { return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); } else { return "of ".concat(thing, " ").concat(expected[0]); } } else { return "of ".concat(thing, " ").concat(String(expected)); } } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith function startsWith(str, search, pos) { return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith function endsWith(str, search, this_len) { if (this_len === undefined || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes function includes(str, search, start) { if (typeof start !== 'number') { start = 0; } if (start + search.length > str.length) { return false; } else { return str.indexOf(search, start) !== -1; } } createErrorType('ERR_AMBIGUOUS_ARGUMENT', 'The "%s" argument is ambiguous. %s', TypeError); createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { if (assert === undefined) assert = __webpack_require__(9373); assert(typeof name === 'string', "'name' must be a string"); // determiner: 'must be' or 'must not be' var determiner; if (typeof expected === 'string' && startsWith(expected, 'not ')) { determiner = 'must not be'; expected = expected.replace(/^not /, ''); } else { determiner = 'must be'; } var msg; if (endsWith(name, ' argument')) { // For cases like 'first argument' msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); } else { var type = includes(name, '.') ? 'property' : 'argument'; msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); } // TODO(BridgeAR): Improve the output by showing `null` and similar. msg += ". Received type ".concat(_typeof(actual)); return msg; }, TypeError); createErrorType('ERR_INVALID_ARG_VALUE', function (name, value) { var reason = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'is invalid'; if (util === undefined) util = __webpack_require__(161); var inspected = util.inspect(value); if (inspected.length > 128) { inspected = "".concat(inspected.slice(0, 128), "..."); } return "The argument '".concat(name, "' ").concat(reason, ". Received ").concat(inspected); }, TypeError, RangeError); createErrorType('ERR_INVALID_RETURN_VALUE', function (input, name, value) { var type; if (value && value.constructor && value.constructor.name) { type = "instance of ".concat(value.constructor.name); } else { type = "type ".concat(_typeof(value)); } return "Expected ".concat(input, " to be returned from the \"").concat(name, "\"") + " function but got ".concat(type, "."); }, TypeError); createErrorType('ERR_MISSING_ARGS', function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (assert === undefined) assert = __webpack_require__(9373); assert(args.length > 0, 'At least one arg needs to be specified'); var msg = 'The '; var len = args.length; args = args.map(function (a) { return "\"".concat(a, "\""); }); switch (len) { case 1: msg += "".concat(args[0], " argument"); break; case 2: msg += "".concat(args[0], " and ").concat(args[1], " arguments"); break; default: msg += args.slice(0, len - 1).join(', '); msg += ", and ".concat(args[len - 1], " arguments"); break; } return "".concat(msg, " must be specified"); }, TypeError); module.exports.codes = codes; /***/ }), /***/ 9015: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Currently in sync with Node.js lib/internal/util/comparisons.js // https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 function _typeof2(obj) { "@babel/helpers - typeof"; return _typeof2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof2(obj); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _typeof(obj) { if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") { _typeof = function _typeof(obj) { return _typeof2(obj); }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj); }; } return _typeof(obj); } var regexFlagsSupported = /a/g.flags !== undefined; var arrayFromSet = function arrayFromSet(set) { var array = []; set.forEach(function (value) { return array.push(value); }); return array; }; var arrayFromMap = function arrayFromMap(map) { var array = []; map.forEach(function (value, key) { return array.push([key, value]); }); return array; }; var objectIs = Object.is ? Object.is : __webpack_require__(4710); var objectGetOwnPropertySymbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols : function () { return []; }; var numberIsNaN = Number.isNaN ? Number.isNaN : __webpack_require__(2191); function uncurryThis(f) { return f.call.bind(f); } var hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty); var propertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable); var objectToString = uncurryThis(Object.prototype.toString); var _require$types = (__webpack_require__(161).types), isAnyArrayBuffer = _require$types.isAnyArrayBuffer, isArrayBufferView = _require$types.isArrayBufferView, isDate = _require$types.isDate, isMap = _require$types.isMap, isRegExp = _require$types.isRegExp, isSet = _require$types.isSet, isNativeError = _require$types.isNativeError, isBoxedPrimitive = _require$types.isBoxedPrimitive, isNumberObject = _require$types.isNumberObject, isStringObject = _require$types.isStringObject, isBooleanObject = _require$types.isBooleanObject, isBigIntObject = _require$types.isBigIntObject, isSymbolObject = _require$types.isSymbolObject, isFloat32Array = _require$types.isFloat32Array, isFloat64Array = _require$types.isFloat64Array; function isNonIndex(key) { if (key.length === 0 || key.length > 10) return true; for (var i = 0; i < key.length; i++) { var code = key.charCodeAt(i); if (code < 48 || code > 57) return true; } // The maximum size for an array is 2 ** 32 -1. return key.length === 10 && key >= Math.pow(2, 32); } function getOwnNonIndexProperties(value) { return Object.keys(value).filter(isNonIndex).concat(objectGetOwnPropertySymbols(value).filter(Object.prototype.propertyIsEnumerable.bind(value))); } // Taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js // original notice: /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ function compare(a, b) { if (a === b) { return 0; } var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } } if (x < y) { return -1; } if (y < x) { return 1; } return 0; } var ONLY_ENUMERABLE = undefined; var kStrict = true; var kLoose = false; var kNoIterator = 0; var kIsArray = 1; var kIsSet = 2; var kIsMap = 3; // Check if they have the same source and flags function areSimilarRegExps(a, b) { return regexFlagsSupported ? a.source === b.source && a.flags === b.flags : RegExp.prototype.toString.call(a) === RegExp.prototype.toString.call(b); } function areSimilarFloatArrays(a, b) { if (a.byteLength !== b.byteLength) { return false; } for (var offset = 0; offset < a.byteLength; offset++) { if (a[offset] !== b[offset]) { return false; } } return true; } function areSimilarTypedArrays(a, b) { if (a.byteLength !== b.byteLength) { return false; } return compare(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)) === 0; } function areEqualArrayBuffers(buf1, buf2) { return buf1.byteLength === buf2.byteLength && compare(new Uint8Array(buf1), new Uint8Array(buf2)) === 0; } function isEqualBoxedPrimitive(val1, val2) { if (isNumberObject(val1)) { return isNumberObject(val2) && objectIs(Number.prototype.valueOf.call(val1), Number.prototype.valueOf.call(val2)); } if (isStringObject(val1)) { return isStringObject(val2) && String.prototype.valueOf.call(val1) === String.prototype.valueOf.call(val2); } if (isBooleanObject(val1)) { return isBooleanObject(val2) && Boolean.prototype.valueOf.call(val1) === Boolean.prototype.valueOf.call(val2); } if (isBigIntObject(val1)) { return isBigIntObject(val2) && BigInt.prototype.valueOf.call(val1) === BigInt.prototype.valueOf.call(val2); } return isSymbolObject(val2) && Symbol.prototype.valueOf.call(val1) === Symbol.prototype.valueOf.call(val2); } // Notes: Type tags are historical [[Class]] properties that can be set by // FunctionTemplate::SetClassName() in C++ or Symbol.toStringTag in JS // and retrieved using Object.prototype.toString.call(obj) in JS // See https://tc39.github.io/ecma262/#sec-object.prototype.tostring // for a list of tags pre-defined in the spec. // There are some unspecified tags in the wild too (e.g. typed array tags). // Since tags can be altered, they only serve fast failures // // Typed arrays and buffers are checked by comparing the content in their // underlying ArrayBuffer. This optimization requires that it's // reasonable to interpret their underlying memory in the same way, // which is checked by comparing their type tags. // (e.g. a Uint8Array and a Uint16Array with the same memory content // could still be different because they will be interpreted differently). // // For strict comparison, objects should have // a) The same built-in type tags // b) The same prototypes. function innerDeepEqual(val1, val2, strict, memos) { // All identical values are equivalent, as determined by ===. if (val1 === val2) { if (val1 !== 0) return true; return strict ? objectIs(val1, val2) : true; } // Check more closely if val1 and val2 are equal. if (strict) { if (_typeof(val1) !== 'object') { return typeof val1 === 'number' && numberIsNaN(val1) && numberIsNaN(val2); } if (_typeof(val2) !== 'object' || val1 === null || val2 === null) { return false; } if (Object.getPrototypeOf(val1) !== Object.getPrototypeOf(val2)) { return false; } } else { if (val1 === null || _typeof(val1) !== 'object') { if (val2 === null || _typeof(val2) !== 'object') { // eslint-disable-next-line eqeqeq return val1 == val2; } return false; } if (val2 === null || _typeof(val2) !== 'object') { return false; } } var val1Tag = objectToString(val1); var val2Tag = objectToString(val2); if (val1Tag !== val2Tag) { return false; } if (Array.isArray(val1)) { // Check for sparse arrays and general fast path if (val1.length !== val2.length) { return false; } var keys1 = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE); var keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE); if (keys1.length !== keys2.length) { return false; } return keyCheck(val1, val2, strict, memos, kIsArray, keys1); } // [browserify] This triggers on certain types in IE (Map/Set) so we don't // wan't to early return out of the rest of the checks. However we can check // if the second value is one of these values and the first isn't. if (val1Tag === '[object Object]') { // return keyCheck(val1, val2, strict, memos, kNoIterator); if (!isMap(val1) && isMap(val2) || !isSet(val1) && isSet(val2)) { return false; } } if (isDate(val1)) { if (!isDate(val2) || Date.prototype.getTime.call(val1) !== Date.prototype.getTime.call(val2)) { return false; } } else if (isRegExp(val1)) { if (!isRegExp(val2) || !areSimilarRegExps(val1, val2)) { return false; } } else if (isNativeError(val1) || val1 instanceof Error) { // Do not compare the stack as it might differ even though the error itself // is otherwise identical. if (val1.message !== val2.message || val1.name !== val2.name) { return false; } } else if (isArrayBufferView(val1)) { if (!strict && (isFloat32Array(val1) || isFloat64Array(val1))) { if (!areSimilarFloatArrays(val1, val2)) { return false; } } else if (!areSimilarTypedArrays(val1, val2)) { return false; } // Buffer.compare returns true, so val1.length === val2.length. If they both // only contain numeric keys, we don't need to exam further than checking // the symbols. var _keys = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE); var _keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE); if (_keys.length !== _keys2.length) { return false; } return keyCheck(val1, val2, strict, memos, kNoIterator, _keys); } else if (isSet(val1)) { if (!isSet(val2) || val1.size !== val2.size) { return false; } return keyCheck(val1, val2, strict, memos, kIsSet); } else if (isMap(val1)) { if (!isMap(val2) || val1.size !== val2.size) { return false; } return keyCheck(val1, val2, strict, memos, kIsMap); } else if (isAnyArrayBuffer(val1)) { if (!areEqualArrayBuffers(val1, val2)) { return false; } } else if (isBoxedPrimitive(val1) && !isEqualBoxedPrimitive(val1, val2)) { return false; } return keyCheck(val1, val2, strict, memos, kNoIterator); } function getEnumerables(val, keys) { return keys.filter(function (k) { return propertyIsEnumerable(val, k); }); } function keyCheck(val1, val2, strict, memos, iterationType, aKeys) { // For all remaining Object pairs, including Array, objects and Maps, // equivalence is determined by having: // a) The same number of owned enumerable properties // b) The same set of keys/indexes (although not necessarily the same order) // c) Equivalent values for every corresponding key/index // d) For Sets and Maps, equal contents // Note: this accounts for both named and indexed properties on Arrays. if (arguments.length === 5) { aKeys = Object.keys(val1); var bKeys = Object.keys(val2); // The pair must have the same number of owned properties. if (aKeys.length !== bKeys.length) { return false; } } // Cheap key test var i = 0; for (; i < aKeys.length; i++) { if (!hasOwnProperty(val2, aKeys[i])) { return false; } } if (strict && arguments.length === 5) { var symbolKeysA = objectGetOwnPropertySymbols(val1); if (symbolKeysA.length !== 0) { var count = 0; for (i = 0; i < symbolKeysA.length; i++) { var key = symbolKeysA[i]; if (propertyIsEnumerable(val1, key)) { if (!propertyIsEnumerable(val2, key)) { return false; } aKeys.push(key); count++; } else if (propertyIsEnumerable(val2, key)) { return false; } } var symbolKeysB = objectGetOwnPropertySymbols(val2); if (symbolKeysA.length !== symbolKeysB.length && getEnumerables(val2, symbolKeysB).length !== count) { return false; } } else { var _symbolKeysB = objectGetOwnPropertySymbols(val2); if (_symbolKeysB.length !== 0 && getEnumerables(val2, _symbolKeysB).length !== 0) { return false; } } } if (aKeys.length === 0 && (iterationType === kNoIterator || iterationType === kIsArray && val1.length === 0 || val1.size === 0)) { return true; } // Use memos to handle cycles. if (memos === undefined) { memos = { val1: new Map(), val2: new Map(), position: 0 }; } else { // We prevent up to two map.has(x) calls by directly retrieving the value // and checking for undefined. The map can only contain numbers, so it is // safe to check for undefined only. var val2MemoA = memos.val1.get(val1); if (val2MemoA !== undefined) { var val2MemoB = memos.val2.get(val2); if (val2MemoB !== undefined) { return val2MemoA === val2MemoB; } } memos.position++; } memos.val1.set(val1, memos.position); memos.val2.set(val2, memos.position); var areEq = objEquiv(val1, val2, strict, aKeys, memos, iterationType); memos.val1["delete"](val1); memos.val2["delete"](val2); return areEq; } function setHasEqualElement(set, val1, strict, memo) { // Go looking. var setValues = arrayFromSet(set); for (var i = 0; i < setValues.length; i++) { var val2 = setValues[i]; if (innerDeepEqual(val1, val2, strict, memo)) { // Remove the matching element to make sure we do not check that again. set["delete"](val2); return true; } } return false; } // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using // Sadly it is not possible to detect corresponding values properly in case the // type is a string, number, bigint or boolean. The reason is that those values // can match lots of different string values (e.g., 1n == '+00001'). function findLooseMatchingPrimitives(prim) { switch (_typeof(prim)) { case 'undefined': return null; case 'object': // Only pass in null as object! return undefined; case 'symbol': return false; case 'string': prim = +prim; // Loose equal entries exist only if the string is possible to convert to // a regular number and not NaN. // Fall through case 'number': if (numberIsNaN(prim)) { return false; } } return true; } function setMightHaveLoosePrim(a, b, prim) { var altValue = findLooseMatchingPrimitives(prim); if (altValue != null) return altValue; return b.has(altValue) && !a.has(altValue); } function mapMightHaveLoosePrim(a, b, prim, item, memo) { var altValue = findLooseMatchingPrimitives(prim); if (altValue != null) { return altValue; } var curB = b.get(altValue); if (curB === undefined && !b.has(altValue) || !innerDeepEqual(item, curB, false, memo)) { return false; } return !a.has(altValue) && innerDeepEqual(item, curB, false, memo); } function setEquiv(a, b, strict, memo) { // This is a lazily initiated Set of entries which have to be compared // pairwise. var set = null; var aValues = arrayFromSet(a); for (var i = 0; i < aValues.length; i++) { var val = aValues[i]; // Note: Checking for the objects first improves the performance for object // heavy sets but it is a minor slow down for primitives. As they are fast // to check this improves the worst case scenario instead. if (_typeof(val) === 'object' && val !== null) { if (set === null) { set = new Set(); } // If the specified value doesn't exist in the second set its an not null // object (or non strict only: a not matching primitive) we'll need to go // hunting for something thats deep-(strict-)equal to it. To make this // O(n log n) complexity we have to copy these values in a new set first. set.add(val); } else if (!b.has(val)) { if (strict) return false; // Fast path to detect missing string, symbol, undefined and null values. if (!setMightHaveLoosePrim(a, b, val)) { return false; } if (set === null) { set = new Set(); } set.add(val); } } if (set !== null) { var bValues = arrayFromSet(b); for (var _i = 0; _i < bValues.length; _i++) { var _val = bValues[_i]; // We have to check if a primitive value is already // matching and only if it's not, go hunting for it. if (_typeof(_val) === 'object' && _val !== null) { if (!setHasEqualElement(set, _val, strict, memo)) return false; } else if (!strict && !a.has(_val) && !setHasEqualElement(set, _val, strict, memo)) { return false; } } return set.size === 0; } return true; } function mapHasEqualEntry(set, map, key1, item1, strict, memo) { // To be able to handle cases like: // Map([[{}, 'a'], [{}, 'b']]) vs Map([[{}, 'b'], [{}, 'a']]) // ... we need to consider *all* matching keys, not just the first we find. var setValues = arrayFromSet(set); for (var i = 0; i < setValues.length; i++) { var key2 = setValues[i]; if (innerDeepEqual(key1, key2, strict, memo) && innerDeepEqual(item1, map.get(key2), strict, memo)) { set["delete"](key2); return true; } } return false; } function mapEquiv(a, b, strict, memo) { var set = null; var aEntries = arrayFromMap(a); for (var i = 0; i < aEntries.length; i++) { var _aEntries$i = _slicedToArray(aEntries[i], 2), key = _aEntries$i[0], item1 = _aEntries$i[1]; if (_typeof(key) === 'object' && key !== null) { if (set === null) { set = new Set(); } set.add(key); } else { // By directly retrieving the value we prevent another b.has(key) check in // almost all possible cases. var item2 = b.get(key); if (item2 === undefined && !b.has(key) || !innerDeepEqual(item1, item2, strict, memo)) { if (strict) return false; // Fast path to detect missing string, symbol, undefined and null // keys. if (!mapMightHaveLoosePrim(a, b, key, item1, memo)) return false; if (set === null) { set = new Set(); } set.add(key); } } } if (set !== null) { var bEntries = arrayFromMap(b); for (var _i2 = 0; _i2 < bEntries.length; _i2++) { var _bEntries$_i = _slicedToArray(bEntries[_i2], 2), key = _bEntries$_i[0], item = _bEntries$_i[1]; if (_typeof(key) === 'object' && key !== null) { if (!mapHasEqualEntry(set, a, key, item, strict, memo)) return false; } else if (!strict && (!a.has(key) || !innerDeepEqual(a.get(key), item, false, memo)) && !mapHasEqualEntry(set, a, key, item, false, memo)) { return false; } } return set.size === 0; } return true; } function objEquiv(a, b, strict, keys, memos, iterationType) { // Sets and maps don't have their entries accessible via normal object // properties. var i = 0; if (iterationType === kIsSet) { if (!setEquiv(a, b, strict, memos)) { return false; } } else if (iterationType === kIsMap) { if (!mapEquiv(a, b, strict, memos)) { return false; } } else if (iterationType === kIsArray) { for (; i < a.length; i++) { if (hasOwnProperty(a, i)) { if (!hasOwnProperty(b, i) || !innerDeepEqual(a[i], b[i], strict, memos)) { return false; } } else if (hasOwnProperty(b, i)) { return false; } else { // Array is sparse. var keysA = Object.keys(a); for (; i < keysA.length; i++) { var key = keysA[i]; if (!hasOwnProperty(b, key) || !innerDeepEqual(a[key], b[key], strict, memos)) { return false; } } if (keysA.length !== Object.keys(b).length) { return false; } return true; } } } // The pair must have equivalent values for every corresponding key. // Possibly expensive deep test: for (i = 0; i < keys.length; i++) { var _key = keys[i]; if (!innerDeepEqual(a[_key], b[_key], strict, memos)) { return false; } } return true; } function isDeepEqual(val1, val2) { return innerDeepEqual(val1, val2, kLoose); } function isDeepStrictEqual(val1, val2) { return innerDeepEqual(val1, val2, kStrict); } module.exports = { isDeepEqual: isDeepEqual, isDeepStrictEqual: isDeepStrictEqual }; /***/ }), /***/ 7943: /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.byteLength = byteLength; exports.toByteArray = toByteArray; exports.fromByteArray = fromByteArray; var lookup = []; var revLookup = []; var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i]; revLookup[code.charCodeAt(i)] = i; } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62; revLookup['_'.charCodeAt(0)] = 63; function getLens(b64) { var len = b64.length; if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4'); } // Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen = b64.indexOf('='); if (validLen === -1) validLen = len; var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; return [validLen, placeHoldersLen]; } // base64 is 4/3 + up to two characters of the original data function byteLength(b64) { var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; } function _byteLength(b64, validLen, placeHoldersLen) { return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; } function toByteArray(b64) { var tmp; var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); var curByte = 0; // if there are placeholders, only get up to the last complete 4 chars var len = placeHoldersLen > 0 ? validLen - 4 : validLen; var i; for (i = 0; i < len; i += 4) { tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; arr[curByte++] = tmp >> 16 & 0xFF; arr[curByte++] = tmp >> 8 & 0xFF; arr[curByte++] = tmp & 0xFF; } if (placeHoldersLen === 2) { tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; arr[curByte++] = tmp & 0xFF; } if (placeHoldersLen === 1) { tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; arr[curByte++] = tmp >> 8 & 0xFF; arr[curByte++] = tmp & 0xFF; } return arr; } function tripletToBase64(num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; } function encodeChunk(uint8, start, end) { var tmp; var output = []; for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF); output.push(tripletToBase64(tmp)); } return output.join(''); } function fromByteArray(uint8) { var tmp; var len = uint8.length; var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes var parts = []; var maxChunkLength = 16383; // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1]; parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '=='); } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1]; parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + '='); } return parts.join(''); } /***/ }), /***/ 6781: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /* module decorator */ module = __webpack_require__.nmd(module); function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } (function (module, exports) { 'use strict'; // Utils function assert(val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } // Could use `inherits` module, but don't want to move from single file // architecture yet. function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function TempCtor() {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } // BN function BN(number, base, endian) { if (BN.isBN(number)) { return number; } this.negative = 0; this.words = null; this.length = 0; // Reduction context this.red = null; if (number !== null) { if (base === 'le' || base === 'be') { endian = base; base = 10; } this._init(number || 0, base || 10, endian || 'be'); } } if (_typeof(module) === 'object') { module.exports = BN; } else { exports.BN = BN; } BN.BN = BN; BN.wordSize = 26; var Buffer; try { if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { Buffer = window.Buffer; } else { Buffer = (__webpack_require__(6601).Buffer); } } catch (e) {} BN.isBN = function isBN(num) { if (num instanceof BN) { return true; } return num !== null && _typeof(num) === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; BN.max = function max(left, right) { if (left.cmp(right) > 0) return left; return right; }; BN.min = function min(left, right) { if (left.cmp(right) < 0) return left; return right; }; BN.prototype._init = function init(number, base, endian) { if (typeof number === 'number') { return this._initNumber(number, base, endian); } if (_typeof(number) === 'object') { return this._initArray(number, base, endian); } if (base === 'hex') { base = 16; } assert(base === (base | 0) && base >= 2 && base <= 36); number = number.toString().replace(/\s+/g, ''); var start = 0; if (number[0] === '-') { start++; this.negative = 1; } if (start < number.length) { if (base === 16) { this._parseHex(number, start, endian); } else { this._parseBase(number, base, start); if (endian === 'le') { this._initArray(this.toArray(), base, endian); } } } }; BN.prototype._initNumber = function _initNumber(number, base, endian) { if (number < 0) { this.negative = 1; number = -number; } if (number < 0x4000000) { this.words = [number & 0x3ffffff]; this.length = 1; } else if (number < 0x10000000000000) { this.words = [number & 0x3ffffff, number / 0x4000000 & 0x3ffffff]; this.length = 2; } else { assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) this.words = [number & 0x3ffffff, number / 0x4000000 & 0x3ffffff, 1]; this.length = 3; } if (endian !== 'le') return; // Reverse the bytes this._initArray(this.toArray(), base, endian); }; BN.prototype._initArray = function _initArray(number, base, endian) { // Perhaps a Uint8Array assert(typeof number.length === 'number'); if (number.length <= 0) { this.words = [0]; this.length = 1; return this; } this.length = Math.ceil(number.length / 3); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; var off = 0; if (endian === 'be') { for (i = number.length - 1, j = 0; i >= 0; i -= 3) { w = number[i] | number[i - 1] << 8 | number[i - 2] << 16; this.words[j] |= w << off & 0x3ffffff; this.words[j + 1] = w >>> 26 - off & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } else if (endian === 'le') { for (i = 0, j = 0; i < number.length; i += 3) { w = number[i] | number[i + 1] << 8 | number[i + 2] << 16; this.words[j] |= w << off & 0x3ffffff; this.words[j + 1] = w >>> 26 - off & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } return this._strip(); }; function parseHex4Bits(string, index) { var c = string.charCodeAt(index); // '0' - '9' if (c >= 48 && c <= 57) { return c - 48; // 'A' - 'F' } else if (c >= 65 && c <= 70) { return c - 55; // 'a' - 'f' } else if (c >= 97 && c <= 102) { return c - 87; } else { assert(false, 'Invalid character in ' + string); } } function parseHexByte(string, lowerBound, index) { var r = parseHex4Bits(string, index); if (index - 1 >= lowerBound) { r |= parseHex4Bits(string, index - 1) << 4; } return r; } BN.prototype._parseHex = function _parseHex(number, start, endian) { // Create possibly bigger array to ensure that it fits the number this.length = Math.ceil((number.length - start) / 6); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } // 24-bits chunks var off = 0; var j = 0; var w; if (endian === 'be') { for (i = number.length - 1; i >= start; i -= 2) { w = parseHexByte(number, start, i) << off; this.words[j] |= w & 0x3ffffff; if (off >= 18) { off -= 18; j += 1; this.words[j] |= w >>> 26; } else { off += 8; } } } else { var parseLength = number.length - start; for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { w = parseHexByte(number, start, i) << off; this.words[j] |= w & 0x3ffffff; if (off >= 18) { off -= 18; j += 1; this.words[j] |= w >>> 26; } else { off += 8; } } } this._strip(); }; function parseBase(str, start, end, mul) { var r = 0; var b = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r *= mul; // 'a' if (c >= 49) { b = c - 49 + 0xa; // 'A' } else if (c >= 17) { b = c - 17 + 0xa; // '0' - '9' } else { b = c; } assert(c >= 0 && b < mul, 'Invalid character'); r += b; } return r; } BN.prototype._parseBase = function _parseBase(number, base, start) { // Initialize as zero this.words = [0]; this.length = 1; // Find length of limb in base for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { limbLen++; } limbLen--; limbPow = limbPow / base | 0; var total = number.length - start; var mod = total % limbLen; var end = Math.min(total, total - mod) + start; var word = 0; for (var i = start; i < end; i += limbLen) { word = parseBase(number, i, i + limbLen, base); this.imuln(limbPow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } if (mod !== 0) { var pow = 1; word = parseBase(number, i, number.length, base); for (i = 0; i < mod; i++) { pow *= base; } this.imuln(pow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } this._strip(); }; BN.prototype.copy = function copy(dest) { dest.words = new Array(this.length); for (var i = 0; i < this.length; i++) { dest.words[i] = this.words[i]; } dest.length = this.length; dest.negative = this.negative; dest.red = this.red; }; function move(dest, src) { dest.words = src.words; dest.length = src.length; dest.negative = src.negative; dest.red = src.red; } BN.prototype._move = function _move(dest) { move(dest, this); }; BN.prototype.clone = function clone() { var r = new BN(null); this.copy(r); return r; }; BN.prototype._expand = function _expand(size) { while (this.length < size) { this.words[this.length++] = 0; } return this; }; // Remove leading `0` from `this` BN.prototype._strip = function strip() { while (this.length > 1 && this.words[this.length - 1] === 0) { this.length--; } return this._normSign(); }; BN.prototype._normSign = function _normSign() { // -0 = 0 if (this.length === 1 && this.words[0] === 0) { this.negative = 0; } return this; }; // Check Symbol.for because not everywhere where Symbol defined // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility if (typeof Symbol !== 'undefined' && typeof Symbol["for"] === 'function') { try { BN.prototype[Symbol["for"]('nodejs.util.inspect.custom')] = inspect; } catch (e) { BN.prototype.inspect = inspect; } } else { BN.prototype.inspect = inspect; } function inspect() { return (this.red ? ''; } /* var zeros = []; var groupSizes = []; var groupBases = []; var s = ''; var i = -1; while (++i < BN.wordSize) { zeros[i] = s; s += '0'; } groupSizes[0] = 0; groupSizes[1] = 0; groupBases[0] = 0; groupBases[1] = 0; var base = 2 - 1; while (++base < 36 + 1) { var groupSize = 0; var groupBase = 1; while (groupBase < (1 << BN.wordSize) / base) { groupBase *= base; groupSize += 1; } groupSizes[base] = groupSize; groupBases[base] = groupBase; } */ var zeros = ['', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000']; var groupSizes = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]; var groupBases = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; BN.prototype.toString = function toString(base, padding) { base = base || 10; padding = padding | 0 || 1; var out; if (base === 16 || base === 'hex') { out = ''; var off = 0; var carry = 0; for (var i = 0; i < this.length; i++) { var w = this.words[i]; var word = ((w << off | carry) & 0xffffff).toString(16); carry = w >>> 24 - off & 0xffffff; off += 2; if (off >= 26) { off -= 26; i--; } if (carry !== 0 || i !== this.length - 1) { out = zeros[6 - word.length] + word + out; } else { out = word + out; } } if (carry !== 0) { out = carry.toString(16) + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } if (base === (base | 0) && base >= 2 && base <= 36) { // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); var groupSize = groupSizes[base]; // var groupBase = Math.pow(base, groupSize); var groupBase = groupBases[base]; out = ''; var c = this.clone(); c.negative = 0; while (!c.isZero()) { var r = c.modrn(groupBase).toString(base); c = c.idivn(groupBase); if (!c.isZero()) { out = zeros[groupSize - r.length] + r + out; } else { out = r + out; } } if (this.isZero()) { out = '0' + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } assert(false, 'Base should be between 2 and 36'); }; BN.prototype.toNumber = function toNumber() { var ret = this.words[0]; if (this.length === 2) { ret += this.words[1] * 0x4000000; } else if (this.length === 3 && this.words[2] === 0x01) { // NOTE: at this stage it is known that the top bit is set ret += 0x10000000000000 + this.words[1] * 0x4000000; } else if (this.length > 2) { assert(false, 'Number can only safely store up to 53 bits'); } return this.negative !== 0 ? -ret : ret; }; BN.prototype.toJSON = function toJSON() { return this.toString(16, 2); }; if (Buffer) { BN.prototype.toBuffer = function toBuffer(endian, length) { return this.toArrayLike(Buffer, endian, length); }; } BN.prototype.toArray = function toArray(endian, length) { return this.toArrayLike(Array, endian, length); }; var allocate = function allocate(ArrayType, size) { if (ArrayType.allocUnsafe) { return ArrayType.allocUnsafe(size); } return new ArrayType(size); }; BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) { this._strip(); var byteLength = this.byteLength(); var reqLength = length || Math.max(1, byteLength); assert(byteLength <= reqLength, 'byte array longer than desired length'); assert(reqLength > 0, 'Requested array length <= 0'); var res = allocate(ArrayType, reqLength); var postfix = endian === 'le' ? 'LE' : 'BE'; this['_toArrayLike' + postfix](res, byteLength); return res; }; BN.prototype._toArrayLikeLE = function _toArrayLikeLE(res, byteLength) { var position = 0; var carry = 0; for (var i = 0, shift = 0; i < this.length; i++) { var word = this.words[i] << shift | carry; res[position++] = word & 0xff; if (position < res.length) { res[position++] = word >> 8 & 0xff; } if (position < res.length) { res[position++] = word >> 16 & 0xff; } if (shift === 6) { if (position < res.length) { res[position++] = word >> 24 & 0xff; } carry = 0; shift = 0; } else { carry = word >>> 24; shift += 2; } } if (position < res.length) { res[position++] = carry; while (position < res.length) { res[position++] = 0; } } }; BN.prototype._toArrayLikeBE = function _toArrayLikeBE(res, byteLength) { var position = res.length - 1; var carry = 0; for (var i = 0, shift = 0; i < this.length; i++) { var word = this.words[i] << shift | carry; res[position--] = word & 0xff; if (position >= 0) { res[position--] = word >> 8 & 0xff; } if (position >= 0) { res[position--] = word >> 16 & 0xff; } if (shift === 6) { if (position >= 0) { res[position--] = word >> 24 & 0xff; } carry = 0; shift = 0; } else { carry = word >>> 24; shift += 2; } } if (position >= 0) { res[position--] = carry; while (position >= 0) { res[position--] = 0; } } }; if (Math.clz32) { BN.prototype._countBits = function _countBits(w) { return 32 - Math.clz32(w); }; } else { BN.prototype._countBits = function _countBits(w) { var t = w; var r = 0; if (t >= 0x1000) { r += 13; t >>>= 13; } if (t >= 0x40) { r += 7; t >>>= 7; } if (t >= 0x8) { r += 4; t >>>= 4; } if (t >= 0x02) { r += 2; t >>>= 2; } return r + t; }; } BN.prototype._zeroBits = function _zeroBits(w) { // Short-cut if (w === 0) return 26; var t = w; var r = 0; if ((t & 0x1fff) === 0) { r += 13; t >>>= 13; } if ((t & 0x7f) === 0) { r += 7; t >>>= 7; } if ((t & 0xf) === 0) { r += 4; t >>>= 4; } if ((t & 0x3) === 0) { r += 2; t >>>= 2; } if ((t & 0x1) === 0) { r++; } return r; }; // Return number of used bits in a BN BN.prototype.bitLength = function bitLength() { var w = this.words[this.length - 1]; var hi = this._countBits(w); return (this.length - 1) * 26 + hi; }; function toBitArray(num) { var w = new Array(num.bitLength()); for (var bit = 0; bit < w.length; bit++) { var off = bit / 26 | 0; var wbit = bit % 26; w[bit] = num.words[off] >>> wbit & 0x01; } return w; } // Number of trailing zero bits BN.prototype.zeroBits = function zeroBits() { if (this.isZero()) return 0; var r = 0; for (var i = 0; i < this.length; i++) { var b = this._zeroBits(this.words[i]); r += b; if (b !== 26) break; } return r; }; BN.prototype.byteLength = function byteLength() { return Math.ceil(this.bitLength() / 8); }; BN.prototype.toTwos = function toTwos(width) { if (this.negative !== 0) { return this.abs().inotn(width).iaddn(1); } return this.clone(); }; BN.prototype.fromTwos = function fromTwos(width) { if (this.testn(width - 1)) { return this.notn(width).iaddn(1).ineg(); } return this.clone(); }; BN.prototype.isNeg = function isNeg() { return this.negative !== 0; }; // Return negative clone of `this` BN.prototype.neg = function neg() { return this.clone().ineg(); }; BN.prototype.ineg = function ineg() { if (!this.isZero()) { this.negative ^= 1; } return this; }; // Or `num` with `this` in-place BN.prototype.iuor = function iuor(num) { while (this.length < num.length) { this.words[this.length++] = 0; } for (var i = 0; i < num.length; i++) { this.words[i] = this.words[i] | num.words[i]; } return this._strip(); }; BN.prototype.ior = function ior(num) { assert((this.negative | num.negative) === 0); return this.iuor(num); }; // Or `num` with `this` BN.prototype.or = function or(num) { if (this.length > num.length) return this.clone().ior(num); return num.clone().ior(this); }; BN.prototype.uor = function uor(num) { if (this.length > num.length) return this.clone().iuor(num); return num.clone().iuor(this); }; // And `num` with `this` in-place BN.prototype.iuand = function iuand(num) { // b = min-length(num, this) var b; if (this.length > num.length) { b = num; } else { b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = this.words[i] & num.words[i]; } this.length = b.length; return this._strip(); }; BN.prototype.iand = function iand(num) { assert((this.negative | num.negative) === 0); return this.iuand(num); }; // And `num` with `this` BN.prototype.and = function and(num) { if (this.length > num.length) return this.clone().iand(num); return num.clone().iand(this); }; BN.prototype.uand = function uand(num) { if (this.length > num.length) return this.clone().iuand(num); return num.clone().iuand(this); }; // Xor `num` with `this` in-place BN.prototype.iuxor = function iuxor(num) { // a.length > b.length var a; var b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = a.words[i] ^ b.words[i]; } if (this !== a) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = a.length; return this._strip(); }; BN.prototype.ixor = function ixor(num) { assert((this.negative | num.negative) === 0); return this.iuxor(num); }; // Xor `num` with `this` BN.prototype.xor = function xor(num) { if (this.length > num.length) return this.clone().ixor(num); return num.clone().ixor(this); }; BN.prototype.uxor = function uxor(num) { if (this.length > num.length) return this.clone().iuxor(num); return num.clone().iuxor(this); }; // Not ``this`` with ``width`` bitwidth BN.prototype.inotn = function inotn(width) { assert(typeof width === 'number' && width >= 0); var bytesNeeded = Math.ceil(width / 26) | 0; var bitsLeft = width % 26; // Extend the buffer with leading zeroes this._expand(bytesNeeded); if (bitsLeft > 0) { bytesNeeded--; } // Handle complete words for (var i = 0; i < bytesNeeded; i++) { this.words[i] = ~this.words[i] & 0x3ffffff; } // Handle the residue if (bitsLeft > 0) { this.words[i] = ~this.words[i] & 0x3ffffff >> 26 - bitsLeft; } // And remove leading zeroes return this._strip(); }; BN.prototype.notn = function notn(width) { return this.clone().inotn(width); }; // Set `bit` of `this` BN.prototype.setn = function setn(bit, val) { assert(typeof bit === 'number' && bit >= 0); var off = bit / 26 | 0; var wbit = bit % 26; this._expand(off + 1); if (val) { this.words[off] = this.words[off] | 1 << wbit; } else { this.words[off] = this.words[off] & ~(1 << wbit); } return this._strip(); }; // Add `num` to `this` in-place BN.prototype.iadd = function iadd(num) { var r; // negative + positive if (this.negative !== 0 && num.negative === 0) { this.negative = 0; r = this.isub(num); this.negative ^= 1; return this._normSign(); // positive + negative } else if (this.negative === 0 && num.negative !== 0) { num.negative = 0; r = this.isub(num); num.negative = 1; return r._normSign(); } // a.length > b.length var a, b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) + (b.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } this.length = a.length; if (carry !== 0) { this.words[this.length] = carry; this.length++; // Copy the rest of the words } else if (a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } return this; }; // Add `num` to `this` BN.prototype.add = function add(num) { var res; if (num.negative !== 0 && this.negative === 0) { num.negative = 0; res = this.sub(num); num.negative ^= 1; return res; } else if (num.negative === 0 && this.negative !== 0) { this.negative = 0; res = num.sub(this); this.negative = 1; return res; } if (this.length > num.length) return this.clone().iadd(num); return num.clone().iadd(this); }; // Subtract `num` from `this` in-place BN.prototype.isub = function isub(num) { // this - (-num) = this + num if (num.negative !== 0) { num.negative = 0; var r = this.iadd(num); num.negative = 1; return r._normSign(); // -this - num = -(this + num) } else if (this.negative !== 0) { this.negative = 0; this.iadd(num); this.negative = 1; return this._normSign(); } // At this point both numbers are positive var cmp = this.cmp(num); // Optimization - zeroify if (cmp === 0) { this.negative = 0; this.length = 1; this.words[0] = 0; return this; } // a > b var a, b; if (cmp > 0) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) - (b.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } // Copy rest of the words if (carry === 0 && i < a.length && a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = Math.max(this.length, i); if (a !== this) { this.negative = 1; } return this._strip(); }; // Subtract `num` from `this` BN.prototype.sub = function sub(num) { return this.clone().isub(num); }; function smallMulTo(self, num, out) { out.negative = num.negative ^ self.negative; var len = self.length + num.length | 0; out.length = len; len = len - 1 | 0; // Peel one iteration (compiler can't do it, because of code complexity) var a = self.words[0] | 0; var b = num.words[0] | 0; var r = a * b; var lo = r & 0x3ffffff; var carry = r / 0x4000000 | 0; out.words[0] = lo; for (var k = 1; k < len; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = carry >>> 26; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = k - j | 0; a = self.words[i] | 0; b = num.words[j] | 0; r = a * b + rword; ncarry += r / 0x4000000 | 0; rword = r & 0x3ffffff; } out.words[k] = rword | 0; carry = ncarry | 0; } if (carry !== 0) { out.words[k] = carry | 0; } else { out.length--; } return out._strip(); } // TODO(indutny): it may be reasonable to omit it for users who don't need // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit // multiplication (like elliptic secp256k1). var comb10MulTo = function comb10MulTo(self, num, out) { var a = self.words; var b = num.words; var o = out.words; var c = 0; var lo; var mid; var hi; var a0 = a[0] | 0; var al0 = a0 & 0x1fff; var ah0 = a0 >>> 13; var a1 = a[1] | 0; var al1 = a1 & 0x1fff; var ah1 = a1 >>> 13; var a2 = a[2] | 0; var al2 = a2 & 0x1fff; var ah2 = a2 >>> 13; var a3 = a[3] | 0; var al3 = a3 & 0x1fff; var ah3 = a3 >>> 13; var a4 = a[4] | 0; var al4 = a4 & 0x1fff; var ah4 = a4 >>> 13; var a5 = a[5] | 0; var al5 = a5 & 0x1fff; var ah5 = a5 >>> 13; var a6 = a[6] | 0; var al6 = a6 & 0x1fff; var ah6 = a6 >>> 13; var a7 = a[7] | 0; var al7 = a7 & 0x1fff; var ah7 = a7 >>> 13; var a8 = a[8] | 0; var al8 = a8 & 0x1fff; var ah8 = a8 >>> 13; var a9 = a[9] | 0; var al9 = a9 & 0x1fff; var ah9 = a9 >>> 13; var b0 = b[0] | 0; var bl0 = b0 & 0x1fff; var bh0 = b0 >>> 13; var b1 = b[1] | 0; var bl1 = b1 & 0x1fff; var bh1 = b1 >>> 13; var b2 = b[2] | 0; var bl2 = b2 & 0x1fff; var bh2 = b2 >>> 13; var b3 = b[3] | 0; var bl3 = b3 & 0x1fff; var bh3 = b3 >>> 13; var b4 = b[4] | 0; var bl4 = b4 & 0x1fff; var bh4 = b4 >>> 13; var b5 = b[5] | 0; var bl5 = b5 & 0x1fff; var bh5 = b5 >>> 13; var b6 = b[6] | 0; var bl6 = b6 & 0x1fff; var bh6 = b6 >>> 13; var b7 = b[7] | 0; var bl7 = b7 & 0x1fff; var bh7 = b7 >>> 13; var b8 = b[8] | 0; var bl8 = b8 & 0x1fff; var bh8 = b8 >>> 13; var b9 = b[9] | 0; var bl9 = b9 & 0x1fff; var bh9 = b9 >>> 13; out.negative = self.negative ^ num.negative; out.length = 19; /* k = 0 */ lo = Math.imul(al0, bl0); mid = Math.imul(al0, bh0); mid = mid + Math.imul(ah0, bl0) | 0; hi = Math.imul(ah0, bh0); var w0 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0; w0 &= 0x3ffffff; /* k = 1 */ lo = Math.imul(al1, bl0); mid = Math.imul(al1, bh0); mid = mid + Math.imul(ah1, bl0) | 0; hi = Math.imul(ah1, bh0); lo = lo + Math.imul(al0, bl1) | 0; mid = mid + Math.imul(al0, bh1) | 0; mid = mid + Math.imul(ah0, bl1) | 0; hi = hi + Math.imul(ah0, bh1) | 0; var w1 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0; w1 &= 0x3ffffff; /* k = 2 */ lo = Math.imul(al2, bl0); mid = Math.imul(al2, bh0); mid = mid + Math.imul(ah2, bl0) | 0; hi = Math.imul(ah2, bh0); lo = lo + Math.imul(al1, bl1) | 0; mid = mid + Math.imul(al1, bh1) | 0; mid = mid + Math.imul(ah1, bl1) | 0; hi = hi + Math.imul(ah1, bh1) | 0; lo = lo + Math.imul(al0, bl2) | 0; mid = mid + Math.imul(al0, bh2) | 0; mid = mid + Math.imul(ah0, bl2) | 0; hi = hi + Math.imul(ah0, bh2) | 0; var w2 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0; w2 &= 0x3ffffff; /* k = 3 */ lo = Math.imul(al3, bl0); mid = Math.imul(al3, bh0); mid = mid + Math.imul(ah3, bl0) | 0; hi = Math.imul(ah3, bh0); lo = lo + Math.imul(al2, bl1) | 0; mid = mid + Math.imul(al2, bh1) | 0; mid = mid + Math.imul(ah2, bl1) | 0; hi = hi + Math.imul(ah2, bh1) | 0; lo = lo + Math.imul(al1, bl2) | 0; mid = mid + Math.imul(al1, bh2) | 0; mid = mid + Math.imul(ah1, bl2) | 0; hi = hi + Math.imul(ah1, bh2) | 0; lo = lo + Math.imul(al0, bl3) | 0; mid = mid + Math.imul(al0, bh3) | 0; mid = mid + Math.imul(ah0, bl3) | 0; hi = hi + Math.imul(ah0, bh3) | 0; var w3 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0; w3 &= 0x3ffffff; /* k = 4 */ lo = Math.imul(al4, bl0); mid = Math.imul(al4, bh0); mid = mid + Math.imul(ah4, bl0) | 0; hi = Math.imul(ah4, bh0); lo = lo + Math.imul(al3, bl1) | 0; mid = mid + Math.imul(al3, bh1) | 0; mid = mid + Math.imul(ah3, bl1) | 0; hi = hi + Math.imul(ah3, bh1) | 0; lo = lo + Math.imul(al2, bl2) | 0; mid = mid + Math.imul(al2, bh2) | 0; mid = mid + Math.imul(ah2, bl2) | 0; hi = hi + Math.imul(ah2, bh2) | 0; lo = lo + Math.imul(al1, bl3) | 0; mid = mid + Math.imul(al1, bh3) | 0; mid = mid + Math.imul(ah1, bl3) | 0; hi = hi + Math.imul(ah1, bh3) | 0; lo = lo + Math.imul(al0, bl4) | 0; mid = mid + Math.imul(al0, bh4) | 0; mid = mid + Math.imul(ah0, bl4) | 0; hi = hi + Math.imul(ah0, bh4) | 0; var w4 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0; w4 &= 0x3ffffff; /* k = 5 */ lo = Math.imul(al5, bl0); mid = Math.imul(al5, bh0); mid = mid + Math.imul(ah5, bl0) | 0; hi = Math.imul(ah5, bh0); lo = lo + Math.imul(al4, bl1) | 0; mid = mid + Math.imul(al4, bh1) | 0; mid = mid + Math.imul(ah4, bl1) | 0; hi = hi + Math.imul(ah4, bh1) | 0; lo = lo + Math.imul(al3, bl2) | 0; mid = mid + Math.imul(al3, bh2) | 0; mid = mid + Math.imul(ah3, bl2) | 0; hi = hi + Math.imul(ah3, bh2) | 0; lo = lo + Math.imul(al2, bl3) | 0; mid = mid + Math.imul(al2, bh3) | 0; mid = mid + Math.imul(ah2, bl3) | 0; hi = hi + Math.imul(ah2, bh3) | 0; lo = lo + Math.imul(al1, bl4) | 0; mid = mid + Math.imul(al1, bh4) | 0; mid = mid + Math.imul(ah1, bl4) | 0; hi = hi + Math.imul(ah1, bh4) | 0; lo = lo + Math.imul(al0, bl5) | 0; mid = mid + Math.imul(al0, bh5) | 0; mid = mid + Math.imul(ah0, bl5) | 0; hi = hi + Math.imul(ah0, bh5) | 0; var w5 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0; w5 &= 0x3ffffff; /* k = 6 */ lo = Math.imul(al6, bl0); mid = Math.imul(al6, bh0); mid = mid + Math.imul(ah6, bl0) | 0; hi = Math.imul(ah6, bh0); lo = lo + Math.imul(al5, bl1) | 0; mid = mid + Math.imul(al5, bh1) | 0; mid = mid + Math.imul(ah5, bl1) | 0; hi = hi + Math.imul(ah5, bh1) | 0; lo = lo + Math.imul(al4, bl2) | 0; mid = mid + Math.imul(al4, bh2) | 0; mid = mid + Math.imul(ah4, bl2) | 0; hi = hi + Math.imul(ah4, bh2) | 0; lo = lo + Math.imul(al3, bl3) | 0; mid = mid + Math.imul(al3, bh3) | 0; mid = mid + Math.imul(ah3, bl3) | 0; hi = hi + Math.imul(ah3, bh3) | 0; lo = lo + Math.imul(al2, bl4) | 0; mid = mid + Math.imul(al2, bh4) | 0; mid = mid + Math.imul(ah2, bl4) | 0; hi = hi + Math.imul(ah2, bh4) | 0; lo = lo + Math.imul(al1, bl5) | 0; mid = mid + Math.imul(al1, bh5) | 0; mid = mid + Math.imul(ah1, bl5) | 0; hi = hi + Math.imul(ah1, bh5) | 0; lo = lo + Math.imul(al0, bl6) | 0; mid = mid + Math.imul(al0, bh6) | 0; mid = mid + Math.imul(ah0, bl6) | 0; hi = hi + Math.imul(ah0, bh6) | 0; var w6 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0; w6 &= 0x3ffffff; /* k = 7 */ lo = Math.imul(al7, bl0); mid = Math.imul(al7, bh0); mid = mid + Math.imul(ah7, bl0) | 0; hi = Math.imul(ah7, bh0); lo = lo + Math.imul(al6, bl1) | 0; mid = mid + Math.imul(al6, bh1) | 0; mid = mid + Math.imul(ah6, bl1) | 0; hi = hi + Math.imul(ah6, bh1) | 0; lo = lo + Math.imul(al5, bl2) | 0; mid = mid + Math.imul(al5, bh2) | 0; mid = mid + Math.imul(ah5, bl2) | 0; hi = hi + Math.imul(ah5, bh2) | 0; lo = lo + Math.imul(al4, bl3) | 0; mid = mid + Math.imul(al4, bh3) | 0; mid = mid + Math.imul(ah4, bl3) | 0; hi = hi + Math.imul(ah4, bh3) | 0; lo = lo + Math.imul(al3, bl4) | 0; mid = mid + Math.imul(al3, bh4) | 0; mid = mid + Math.imul(ah3, bl4) | 0; hi = hi + Math.imul(ah3, bh4) | 0; lo = lo + Math.imul(al2, bl5) | 0; mid = mid + Math.imul(al2, bh5) | 0; mid = mid + Math.imul(ah2, bl5) | 0; hi = hi + Math.imul(ah2, bh5) | 0; lo = lo + Math.imul(al1, bl6) | 0; mid = mid + Math.imul(al1, bh6) | 0; mid = mid + Math.imul(ah1, bl6) | 0; hi = hi + Math.imul(ah1, bh6) | 0; lo = lo + Math.imul(al0, bl7) | 0; mid = mid + Math.imul(al0, bh7) | 0; mid = mid + Math.imul(ah0, bl7) | 0; hi = hi + Math.imul(ah0, bh7) | 0; var w7 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0; w7 &= 0x3ffffff; /* k = 8 */ lo = Math.imul(al8, bl0); mid = Math.imul(al8, bh0); mid = mid + Math.imul(ah8, bl0) | 0; hi = Math.imul(ah8, bh0); lo = lo + Math.imul(al7, bl1) | 0; mid = mid + Math.imul(al7, bh1) | 0; mid = mid + Math.imul(ah7, bl1) | 0; hi = hi + Math.imul(ah7, bh1) | 0; lo = lo + Math.imul(al6, bl2) | 0; mid = mid + Math.imul(al6, bh2) | 0; mid = mid + Math.imul(ah6, bl2) | 0; hi = hi + Math.imul(ah6, bh2) | 0; lo = lo + Math.imul(al5, bl3) | 0; mid = mid + Math.imul(al5, bh3) | 0; mid = mid + Math.imul(ah5, bl3) | 0; hi = hi + Math.imul(ah5, bh3) | 0; lo = lo + Math.imul(al4, bl4) | 0; mid = mid + Math.imul(al4, bh4) | 0; mid = mid + Math.imul(ah4, bl4) | 0; hi = hi + Math.imul(ah4, bh4) | 0; lo = lo + Math.imul(al3, bl5) | 0; mid = mid + Math.imul(al3, bh5) | 0; mid = mid + Math.imul(ah3, bl5) | 0; hi = hi + Math.imul(ah3, bh5) | 0; lo = lo + Math.imul(al2, bl6) | 0; mid = mid + Math.imul(al2, bh6) | 0; mid = mid + Math.imul(ah2, bl6) | 0; hi = hi + Math.imul(ah2, bh6) | 0; lo = lo + Math.imul(al1, bl7) | 0; mid = mid + Math.imul(al1, bh7) | 0; mid = mid + Math.imul(ah1, bl7) | 0; hi = hi + Math.imul(ah1, bh7) | 0; lo = lo + Math.imul(al0, bl8) | 0; mid = mid + Math.imul(al0, bh8) | 0; mid = mid + Math.imul(ah0, bl8) | 0; hi = hi + Math.imul(ah0, bh8) | 0; var w8 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0; w8 &= 0x3ffffff; /* k = 9 */ lo = Math.imul(al9, bl0); mid = Math.imul(al9, bh0); mid = mid + Math.imul(ah9, bl0) | 0; hi = Math.imul(ah9, bh0); lo = lo + Math.imul(al8, bl1) | 0; mid = mid + Math.imul(al8, bh1) | 0; mid = mid + Math.imul(ah8, bl1) | 0; hi = hi + Math.imul(ah8, bh1) | 0; lo = lo + Math.imul(al7, bl2) | 0; mid = mid + Math.imul(al7, bh2) | 0; mid = mid + Math.imul(ah7, bl2) | 0; hi = hi + Math.imul(ah7, bh2) | 0; lo = lo + Math.imul(al6, bl3) | 0; mid = mid + Math.imul(al6, bh3) | 0; mid = mid + Math.imul(ah6, bl3) | 0; hi = hi + Math.imul(ah6, bh3) | 0; lo = lo + Math.imul(al5, bl4) | 0; mid = mid + Math.imul(al5, bh4) | 0; mid = mid + Math.imul(ah5, bl4) | 0; hi = hi + Math.imul(ah5, bh4) | 0; lo = lo + Math.imul(al4, bl5) | 0; mid = mid + Math.imul(al4, bh5) | 0; mid = mid + Math.imul(ah4, bl5) | 0; hi = hi + Math.imul(ah4, bh5) | 0; lo = lo + Math.imul(al3, bl6) | 0; mid = mid + Math.imul(al3, bh6) | 0; mid = mid + Math.imul(ah3, bl6) | 0; hi = hi + Math.imul(ah3, bh6) | 0; lo = lo + Math.imul(al2, bl7) | 0; mid = mid + Math.imul(al2, bh7) | 0; mid = mid + Math.imul(ah2, bl7) | 0; hi = hi + Math.imul(ah2, bh7) | 0; lo = lo + Math.imul(al1, bl8) | 0; mid = mid + Math.imul(al1, bh8) | 0; mid = mid + Math.imul(ah1, bl8) | 0; hi = hi + Math.imul(ah1, bh8) | 0; lo = lo + Math.imul(al0, bl9) | 0; mid = mid + Math.imul(al0, bh9) | 0; mid = mid + Math.imul(ah0, bl9) | 0; hi = hi + Math.imul(ah0, bh9) | 0; var w9 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0; w9 &= 0x3ffffff; /* k = 10 */ lo = Math.imul(al9, bl1); mid = Math.imul(al9, bh1); mid = mid + Math.imul(ah9, bl1) | 0; hi = Math.imul(ah9, bh1); lo = lo + Math.imul(al8, bl2) | 0; mid = mid + Math.imul(al8, bh2) | 0; mid = mid + Math.imul(ah8, bl2) | 0; hi = hi + Math.imul(ah8, bh2) | 0; lo = lo + Math.imul(al7, bl3) | 0; mid = mid + Math.imul(al7, bh3) | 0; mid = mid + Math.imul(ah7, bl3) | 0; hi = hi + Math.imul(ah7, bh3) | 0; lo = lo + Math.imul(al6, bl4) | 0; mid = mid + Math.imul(al6, bh4) | 0; mid = mid + Math.imul(ah6, bl4) | 0; hi = hi + Math.imul(ah6, bh4) | 0; lo = lo + Math.imul(al5, bl5) | 0; mid = mid + Math.imul(al5, bh5) | 0; mid = mid + Math.imul(ah5, bl5) | 0; hi = hi + Math.imul(ah5, bh5) | 0; lo = lo + Math.imul(al4, bl6) | 0; mid = mid + Math.imul(al4, bh6) | 0; mid = mid + Math.imul(ah4, bl6) | 0; hi = hi + Math.imul(ah4, bh6) | 0; lo = lo + Math.imul(al3, bl7) | 0; mid = mid + Math.imul(al3, bh7) | 0; mid = mid + Math.imul(ah3, bl7) | 0; hi = hi + Math.imul(ah3, bh7) | 0; lo = lo + Math.imul(al2, bl8) | 0; mid = mid + Math.imul(al2, bh8) | 0; mid = mid + Math.imul(ah2, bl8) | 0; hi = hi + Math.imul(ah2, bh8) | 0; lo = lo + Math.imul(al1, bl9) | 0; mid = mid + Math.imul(al1, bh9) | 0; mid = mid + Math.imul(ah1, bl9) | 0; hi = hi + Math.imul(ah1, bh9) | 0; var w10 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0; w10 &= 0x3ffffff; /* k = 11 */ lo = Math.imul(al9, bl2); mid = Math.imul(al9, bh2); mid = mid + Math.imul(ah9, bl2) | 0; hi = Math.imul(ah9, bh2); lo = lo + Math.imul(al8, bl3) | 0; mid = mid + Math.imul(al8, bh3) | 0; mid = mid + Math.imul(ah8, bl3) | 0; hi = hi + Math.imul(ah8, bh3) | 0; lo = lo + Math.imul(al7, bl4) | 0; mid = mid + Math.imul(al7, bh4) | 0; mid = mid + Math.imul(ah7, bl4) | 0; hi = hi + Math.imul(ah7, bh4) | 0; lo = lo + Math.imul(al6, bl5) | 0; mid = mid + Math.imul(al6, bh5) | 0; mid = mid + Math.imul(ah6, bl5) | 0; hi = hi + Math.imul(ah6, bh5) | 0; lo = lo + Math.imul(al5, bl6) | 0; mid = mid + Math.imul(al5, bh6) | 0; mid = mid + Math.imul(ah5, bl6) | 0; hi = hi + Math.imul(ah5, bh6) | 0; lo = lo + Math.imul(al4, bl7) | 0; mid = mid + Math.imul(al4, bh7) | 0; mid = mid + Math.imul(ah4, bl7) | 0; hi = hi + Math.imul(ah4, bh7) | 0; lo = lo + Math.imul(al3, bl8) | 0; mid = mid + Math.imul(al3, bh8) | 0; mid = mid + Math.imul(ah3, bl8) | 0; hi = hi + Math.imul(ah3, bh8) | 0; lo = lo + Math.imul(al2, bl9) | 0; mid = mid + Math.imul(al2, bh9) | 0; mid = mid + Math.imul(ah2, bl9) | 0; hi = hi + Math.imul(ah2, bh9) | 0; var w11 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0; w11 &= 0x3ffffff; /* k = 12 */ lo = Math.imul(al9, bl3); mid = Math.imul(al9, bh3); mid = mid + Math.imul(ah9, bl3) | 0; hi = Math.imul(ah9, bh3); lo = lo + Math.imul(al8, bl4) | 0; mid = mid + Math.imul(al8, bh4) | 0; mid = mid + Math.imul(ah8, bl4) | 0; hi = hi + Math.imul(ah8, bh4) | 0; lo = lo + Math.imul(al7, bl5) | 0; mid = mid + Math.imul(al7, bh5) | 0; mid = mid + Math.imul(ah7, bl5) | 0; hi = hi + Math.imul(ah7, bh5) | 0; lo = lo + Math.imul(al6, bl6) | 0; mid = mid + Math.imul(al6, bh6) | 0; mid = mid + Math.imul(ah6, bl6) | 0; hi = hi + Math.imul(ah6, bh6) | 0; lo = lo + Math.imul(al5, bl7) | 0; mid = mid + Math.imul(al5, bh7) | 0; mid = mid + Math.imul(ah5, bl7) | 0; hi = hi + Math.imul(ah5, bh7) | 0; lo = lo + Math.imul(al4, bl8) | 0; mid = mid + Math.imul(al4, bh8) | 0; mid = mid + Math.imul(ah4, bl8) | 0; hi = hi + Math.imul(ah4, bh8) | 0; lo = lo + Math.imul(al3, bl9) | 0; mid = mid + Math.imul(al3, bh9) | 0; mid = mid + Math.imul(ah3, bl9) | 0; hi = hi + Math.imul(ah3, bh9) | 0; var w12 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0; w12 &= 0x3ffffff; /* k = 13 */ lo = Math.imul(al9, bl4); mid = Math.imul(al9, bh4); mid = mid + Math.imul(ah9, bl4) | 0; hi = Math.imul(ah9, bh4); lo = lo + Math.imul(al8, bl5) | 0; mid = mid + Math.imul(al8, bh5) | 0; mid = mid + Math.imul(ah8, bl5) | 0; hi = hi + Math.imul(ah8, bh5) | 0; lo = lo + Math.imul(al7, bl6) | 0; mid = mid + Math.imul(al7, bh6) | 0; mid = mid + Math.imul(ah7, bl6) | 0; hi = hi + Math.imul(ah7, bh6) | 0; lo = lo + Math.imul(al6, bl7) | 0; mid = mid + Math.imul(al6, bh7) | 0; mid = mid + Math.imul(ah6, bl7) | 0; hi = hi + Math.imul(ah6, bh7) | 0; lo = lo + Math.imul(al5, bl8) | 0; mid = mid + Math.imul(al5, bh8) | 0; mid = mid + Math.imul(ah5, bl8) | 0; hi = hi + Math.imul(ah5, bh8) | 0; lo = lo + Math.imul(al4, bl9) | 0; mid = mid + Math.imul(al4, bh9) | 0; mid = mid + Math.imul(ah4, bl9) | 0; hi = hi + Math.imul(ah4, bh9) | 0; var w13 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0; w13 &= 0x3ffffff; /* k = 14 */ lo = Math.imul(al9, bl5); mid = Math.imul(al9, bh5); mid = mid + Math.imul(ah9, bl5) | 0; hi = Math.imul(ah9, bh5); lo = lo + Math.imul(al8, bl6) | 0; mid = mid + Math.imul(al8, bh6) | 0; mid = mid + Math.imul(ah8, bl6) | 0; hi = hi + Math.imul(ah8, bh6) | 0; lo = lo + Math.imul(al7, bl7) | 0; mid = mid + Math.imul(al7, bh7) | 0; mid = mid + Math.imul(ah7, bl7) | 0; hi = hi + Math.imul(ah7, bh7) | 0; lo = lo + Math.imul(al6, bl8) | 0; mid = mid + Math.imul(al6, bh8) | 0; mid = mid + Math.imul(ah6, bl8) | 0; hi = hi + Math.imul(ah6, bh8) | 0; lo = lo + Math.imul(al5, bl9) | 0; mid = mid + Math.imul(al5, bh9) | 0; mid = mid + Math.imul(ah5, bl9) | 0; hi = hi + Math.imul(ah5, bh9) | 0; var w14 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0; w14 &= 0x3ffffff; /* k = 15 */ lo = Math.imul(al9, bl6); mid = Math.imul(al9, bh6); mid = mid + Math.imul(ah9, bl6) | 0; hi = Math.imul(ah9, bh6); lo = lo + Math.imul(al8, bl7) | 0; mid = mid + Math.imul(al8, bh7) | 0; mid = mid + Math.imul(ah8, bl7) | 0; hi = hi + Math.imul(ah8, bh7) | 0; lo = lo + Math.imul(al7, bl8) | 0; mid = mid + Math.imul(al7, bh8) | 0; mid = mid + Math.imul(ah7, bl8) | 0; hi = hi + Math.imul(ah7, bh8) | 0; lo = lo + Math.imul(al6, bl9) | 0; mid = mid + Math.imul(al6, bh9) | 0; mid = mid + Math.imul(ah6, bl9) | 0; hi = hi + Math.imul(ah6, bh9) | 0; var w15 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0; w15 &= 0x3ffffff; /* k = 16 */ lo = Math.imul(al9, bl7); mid = Math.imul(al9, bh7); mid = mid + Math.imul(ah9, bl7) | 0; hi = Math.imul(ah9, bh7); lo = lo + Math.imul(al8, bl8) | 0; mid = mid + Math.imul(al8, bh8) | 0; mid = mid + Math.imul(ah8, bl8) | 0; hi = hi + Math.imul(ah8, bh8) | 0; lo = lo + Math.imul(al7, bl9) | 0; mid = mid + Math.imul(al7, bh9) | 0; mid = mid + Math.imul(ah7, bl9) | 0; hi = hi + Math.imul(ah7, bh9) | 0; var w16 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0; w16 &= 0x3ffffff; /* k = 17 */ lo = Math.imul(al9, bl8); mid = Math.imul(al9, bh8); mid = mid + Math.imul(ah9, bl8) | 0; hi = Math.imul(ah9, bh8); lo = lo + Math.imul(al8, bl9) | 0; mid = mid + Math.imul(al8, bh9) | 0; mid = mid + Math.imul(ah8, bl9) | 0; hi = hi + Math.imul(ah8, bh9) | 0; var w17 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0; w17 &= 0x3ffffff; /* k = 18 */ lo = Math.imul(al9, bl9); mid = Math.imul(al9, bh9); mid = mid + Math.imul(ah9, bl9) | 0; hi = Math.imul(ah9, bh9); var w18 = (c + lo | 0) + ((mid & 0x1fff) << 13) | 0; c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0; w18 &= 0x3ffffff; o[0] = w0; o[1] = w1; o[2] = w2; o[3] = w3; o[4] = w4; o[5] = w5; o[6] = w6; o[7] = w7; o[8] = w8; o[9] = w9; o[10] = w10; o[11] = w11; o[12] = w12; o[13] = w13; o[14] = w14; o[15] = w15; o[16] = w16; o[17] = w17; o[18] = w18; if (c !== 0) { o[19] = c; out.length++; } return out; }; // Polyfill comb if (!Math.imul) { comb10MulTo = smallMulTo; } function bigMulTo(self, num, out) { out.negative = num.negative ^ self.negative; out.length = self.length + num.length; var carry = 0; var hncarry = 0; for (var k = 0; k < out.length - 1; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = hncarry; hncarry = 0; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = k - j; var a = self.words[i] | 0; var b = num.words[j] | 0; var r = a * b; var lo = r & 0x3ffffff; ncarry = ncarry + (r / 0x4000000 | 0) | 0; lo = lo + rword | 0; rword = lo & 0x3ffffff; ncarry = ncarry + (lo >>> 26) | 0; hncarry += ncarry >>> 26; ncarry &= 0x3ffffff; } out.words[k] = rword; carry = ncarry; ncarry = hncarry; } if (carry !== 0) { out.words[k] = carry; } else { out.length--; } return out._strip(); } function jumboMulTo(self, num, out) { // Temporary disable, see https://github.com/indutny/bn.js/issues/211 // var fftm = new FFTM(); // return fftm.mulp(self, num, out); return bigMulTo(self, num, out); } BN.prototype.mulTo = function mulTo(num, out) { var res; var len = this.length + num.length; if (this.length === 10 && num.length === 10) { res = comb10MulTo(this, num, out); } else if (len < 63) { res = smallMulTo(this, num, out); } else if (len < 1024) { res = bigMulTo(this, num, out); } else { res = jumboMulTo(this, num, out); } return res; }; // Cooley-Tukey algorithm for FFT // slightly revisited to rely on looping instead of recursion function FFTM(x, y) { this.x = x; this.y = y; } FFTM.prototype.makeRBT = function makeRBT(N) { var t = new Array(N); var l = BN.prototype._countBits(N) - 1; for (var i = 0; i < N; i++) { t[i] = this.revBin(i, l, N); } return t; }; // Returns binary-reversed representation of `x` FFTM.prototype.revBin = function revBin(x, l, N) { if (x === 0 || x === N - 1) return x; var rb = 0; for (var i = 0; i < l; i++) { rb |= (x & 1) << l - i - 1; x >>= 1; } return rb; }; // Performs "tweedling" phase, therefore 'emulating' // behaviour of the recursive algorithm FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N) { for (var i = 0; i < N; i++) { rtws[i] = rws[rbt[i]]; itws[i] = iws[rbt[i]]; } }; FFTM.prototype.transform = function transform(rws, iws, rtws, itws, N, rbt) { this.permute(rbt, rws, iws, rtws, itws, N); for (var s = 1; s < N; s <<= 1) { var l = s << 1; var rtwdf = Math.cos(2 * Math.PI / l); var itwdf = Math.sin(2 * Math.PI / l); for (var p = 0; p < N; p += l) { var rtwdf_ = rtwdf; var itwdf_ = itwdf; for (var j = 0; j < s; j++) { var re = rtws[p + j]; var ie = itws[p + j]; var ro = rtws[p + j + s]; var io = itws[p + j + s]; var rx = rtwdf_ * ro - itwdf_ * io; io = rtwdf_ * io + itwdf_ * ro; ro = rx; rtws[p + j] = re + ro; itws[p + j] = ie + io; rtws[p + j + s] = re - ro; itws[p + j + s] = ie - io; /* jshint maxdepth : false */ if (j !== l) { rx = rtwdf * rtwdf_ - itwdf * itwdf_; itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; rtwdf_ = rx; } } } } }; FFTM.prototype.guessLen13b = function guessLen13b(n, m) { var N = Math.max(m, n) | 1; var odd = N & 1; var i = 0; for (N = N / 2 | 0; N; N = N >>> 1) { i++; } return 1 << i + 1 + odd; }; FFTM.prototype.conjugate = function conjugate(rws, iws, N) { if (N <= 1) return; for (var i = 0; i < N / 2; i++) { var t = rws[i]; rws[i] = rws[N - i - 1]; rws[N - i - 1] = t; t = iws[i]; iws[i] = -iws[N - i - 1]; iws[N - i - 1] = -t; } }; FFTM.prototype.normalize13b = function normalize13b(ws, N) { var carry = 0; for (var i = 0; i < N / 2; i++) { var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry; ws[i] = w & 0x3ffffff; if (w < 0x4000000) { carry = 0; } else { carry = w / 0x4000000 | 0; } } return ws; }; FFTM.prototype.convert13b = function convert13b(ws, len, rws, N) { var carry = 0; for (var i = 0; i < len; i++) { carry = carry + (ws[i] | 0); rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; } // Pad with zeroes for (i = 2 * len; i < N; ++i) { rws[i] = 0; } assert(carry === 0); assert((carry & ~0x1fff) === 0); }; FFTM.prototype.stub = function stub(N) { var ph = new Array(N); for (var i = 0; i < N; i++) { ph[i] = 0; } return ph; }; FFTM.prototype.mulp = function mulp(x, y, out) { var N = 2 * this.guessLen13b(x.length, y.length); var rbt = this.makeRBT(N); var _ = this.stub(N); var rws = new Array(N); var rwst = new Array(N); var iwst = new Array(N); var nrws = new Array(N); var nrwst = new Array(N); var niwst = new Array(N); var rmws = out.words; rmws.length = N; this.convert13b(x.words, x.length, rws, N); this.convert13b(y.words, y.length, nrws, N); this.transform(rws, _, rwst, iwst, N, rbt); this.transform(nrws, _, nrwst, niwst, N, rbt); for (var i = 0; i < N; i++) { var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; rwst[i] = rx; } this.conjugate(rwst, iwst, N); this.transform(rwst, iwst, rmws, _, N, rbt); this.conjugate(rmws, _, N); this.normalize13b(rmws, N); out.negative = x.negative ^ y.negative; out.length = x.length + y.length; return out._strip(); }; // Multiply `this` by `num` BN.prototype.mul = function mul(num) { var out = new BN(null); out.words = new Array(this.length + num.length); return this.mulTo(num, out); }; // Multiply employing FFT BN.prototype.mulf = function mulf(num) { var out = new BN(null); out.words = new Array(this.length + num.length); return jumboMulTo(this, num, out); }; // In-place Multiplication BN.prototype.imul = function imul(num) { return this.clone().mulTo(num, this); }; BN.prototype.imuln = function imuln(num) { var isNegNum = num < 0; if (isNegNum) num = -num; assert(typeof num === 'number'); assert(num < 0x4000000); // Carry var carry = 0; for (var i = 0; i < this.length; i++) { var w = (this.words[i] | 0) * num; var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); carry >>= 26; carry += w / 0x4000000 | 0; // NOTE: lo is 27bit maximum carry += lo >>> 26; this.words[i] = lo & 0x3ffffff; } if (carry !== 0) { this.words[i] = carry; this.length++; } return isNegNum ? this.ineg() : this; }; BN.prototype.muln = function muln(num) { return this.clone().imuln(num); }; // `this` * `this` BN.prototype.sqr = function sqr() { return this.mul(this); }; // `this` * `this` in-place BN.prototype.isqr = function isqr() { return this.imul(this.clone()); }; // Math.pow(`this`, `num`) BN.prototype.pow = function pow(num) { var w = toBitArray(num); if (w.length === 0) return new BN(1); // Skip leading zeroes var res = this; for (var i = 0; i < w.length; i++, res = res.sqr()) { if (w[i] !== 0) break; } if (++i < w.length) { for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { if (w[i] === 0) continue; res = res.mul(q); } } return res; }; // Shift-left in-place BN.prototype.iushln = function iushln(bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; var carryMask = 0x3ffffff >>> 26 - r << 26 - r; var i; if (r !== 0) { var carry = 0; for (i = 0; i < this.length; i++) { var newCarry = this.words[i] & carryMask; var c = (this.words[i] | 0) - newCarry << r; this.words[i] = c | carry; carry = newCarry >>> 26 - r; } if (carry) { this.words[i] = carry; this.length++; } } if (s !== 0) { for (i = this.length - 1; i >= 0; i--) { this.words[i + s] = this.words[i]; } for (i = 0; i < s; i++) { this.words[i] = 0; } this.length += s; } return this._strip(); }; BN.prototype.ishln = function ishln(bits) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushln(bits); }; // Shift-right in-place // NOTE: `hint` is a lowest bit before trailing zeroes // NOTE: if `extended` is present - it will be filled with destroyed bits BN.prototype.iushrn = function iushrn(bits, hint, extended) { assert(typeof bits === 'number' && bits >= 0); var h; if (hint) { h = (hint - hint % 26) / 26; } else { h = 0; } var r = bits % 26; var s = Math.min((bits - r) / 26, this.length); var mask = 0x3ffffff ^ 0x3ffffff >>> r << r; var maskedWords = extended; h -= s; h = Math.max(0, h); // Extended mode, copy masked part if (maskedWords) { for (var i = 0; i < s; i++) { maskedWords.words[i] = this.words[i]; } maskedWords.length = s; } if (s === 0) {// No-op, we should not move anything at all } else if (this.length > s) { this.length -= s; for (i = 0; i < this.length; i++) { this.words[i] = this.words[i + s]; } } else { this.words[0] = 0; this.length = 1; } var carry = 0; for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { var word = this.words[i] | 0; this.words[i] = carry << 26 - r | word >>> r; carry = word & mask; } // Push carried bits as a mask if (maskedWords && carry !== 0) { maskedWords.words[maskedWords.length++] = carry; } if (this.length === 0) { this.words[0] = 0; this.length = 1; } return this._strip(); }; BN.prototype.ishrn = function ishrn(bits, hint, extended) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushrn(bits, hint, extended); }; // Shift-left BN.prototype.shln = function shln(bits) { return this.clone().ishln(bits); }; BN.prototype.ushln = function ushln(bits) { return this.clone().iushln(bits); }; // Shift-right BN.prototype.shrn = function shrn(bits) { return this.clone().ishrn(bits); }; BN.prototype.ushrn = function ushrn(bits) { return this.clone().iushrn(bits); }; // Test if n bit is set BN.prototype.testn = function testn(bit) { assert(typeof bit === 'number' && bit >= 0); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) return false; // Check bit and return var w = this.words[s]; return !!(w & q); }; // Return only lowers bits of number (in-place) BN.prototype.imaskn = function imaskn(bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; assert(this.negative === 0, 'imaskn works only with positive numbers'); if (this.length <= s) { return this; } if (r !== 0) { s++; } this.length = Math.min(s, this.length); if (r !== 0) { var mask = 0x3ffffff ^ 0x3ffffff >>> r << r; this.words[this.length - 1] &= mask; } return this._strip(); }; // Return only lowers bits of number BN.prototype.maskn = function maskn(bits) { return this.clone().imaskn(bits); }; // Add plain number `num` to `this` BN.prototype.iaddn = function iaddn(num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.isubn(-num); // Possible sign change if (this.negative !== 0) { if (this.length === 1 && (this.words[0] | 0) <= num) { this.words[0] = num - (this.words[0] | 0); this.negative = 0; return this; } this.negative = 0; this.isubn(num); this.negative = 1; return this; } // Add without checks return this._iaddn(num); }; BN.prototype._iaddn = function _iaddn(num) { this.words[0] += num; // Carry for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { this.words[i] -= 0x4000000; if (i === this.length - 1) { this.words[i + 1] = 1; } else { this.words[i + 1]++; } } this.length = Math.max(this.length, i + 1); return this; }; // Subtract plain number `num` from `this` BN.prototype.isubn = function isubn(num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.iaddn(-num); if (this.negative !== 0) { this.negative = 0; this.iaddn(num); this.negative = 1; return this; } this.words[0] -= num; if (this.length === 1 && this.words[0] < 0) { this.words[0] = -this.words[0]; this.negative = 1; } else { // Carry for (var i = 0; i < this.length && this.words[i] < 0; i++) { this.words[i] += 0x4000000; this.words[i + 1] -= 1; } } return this._strip(); }; BN.prototype.addn = function addn(num) { return this.clone().iaddn(num); }; BN.prototype.subn = function subn(num) { return this.clone().isubn(num); }; BN.prototype.iabs = function iabs() { this.negative = 0; return this; }; BN.prototype.abs = function abs() { return this.clone().iabs(); }; BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { var len = num.length + shift; var i; this._expand(len); var w; var carry = 0; for (i = 0; i < num.length; i++) { w = (this.words[i + shift] | 0) + carry; var right = (num.words[i] | 0) * mul; w -= right & 0x3ffffff; carry = (w >> 26) - (right / 0x4000000 | 0); this.words[i + shift] = w & 0x3ffffff; } for (; i < this.length - shift; i++) { w = (this.words[i + shift] | 0) + carry; carry = w >> 26; this.words[i + shift] = w & 0x3ffffff; } if (carry === 0) return this._strip(); // Subtraction overflow assert(carry === -1); carry = 0; for (i = 0; i < this.length; i++) { w = -(this.words[i] | 0) + carry; carry = w >> 26; this.words[i] = w & 0x3ffffff; } this.negative = 1; return this._strip(); }; BN.prototype._wordDiv = function _wordDiv(num, mode) { var shift = this.length - num.length; var a = this.clone(); var b = num; // Normalize var bhi = b.words[b.length - 1] | 0; var bhiBits = this._countBits(bhi); shift = 26 - bhiBits; if (shift !== 0) { b = b.ushln(shift); a.iushln(shift); bhi = b.words[b.length - 1] | 0; } // Initialize quotient var m = a.length - b.length; var q; if (mode !== 'mod') { q = new BN(null); q.length = m + 1; q.words = new Array(q.length); for (var i = 0; i < q.length; i++) { q.words[i] = 0; } } var diff = a.clone()._ishlnsubmul(b, 1, m); if (diff.negative === 0) { a = diff; if (q) { q.words[m] = 1; } } for (var j = m - 1; j >= 0; j--) { var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max // (0x7ffffff) qj = Math.min(qj / bhi | 0, 0x3ffffff); a._ishlnsubmul(b, qj, j); while (a.negative !== 0) { qj--; a.negative = 0; a._ishlnsubmul(b, 1, j); if (!a.isZero()) { a.negative ^= 1; } } if (q) { q.words[j] = qj; } } if (q) { q._strip(); } a._strip(); // Denormalize if (mode !== 'div' && shift !== 0) { a.iushrn(shift); } return { div: q || null, mod: a }; }; // NOTE: 1) `mode` can be set to `mod` to request mod only, // to `div` to request div only, or be absent to // request both div & mod // 2) `positive` is true if unsigned mod is requested BN.prototype.divmod = function divmod(num, mode, positive) { assert(!num.isZero()); if (this.isZero()) { return { div: new BN(0), mod: new BN(0) }; } var div, mod, res; if (this.negative !== 0 && num.negative === 0) { res = this.neg().divmod(num, mode); if (mode !== 'mod') { div = res.div.neg(); } if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.iadd(num); } } return { div: div, mod: mod }; } if (this.negative === 0 && num.negative !== 0) { res = this.divmod(num.neg(), mode); if (mode !== 'mod') { div = res.div.neg(); } return { div: div, mod: res.mod }; } if ((this.negative & num.negative) !== 0) { res = this.neg().divmod(num.neg(), mode); if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.isub(num); } } return { div: res.div, mod: mod }; } // Both numbers are positive at this point // Strip both numbers to approximate shift value if (num.length > this.length || this.cmp(num) < 0) { return { div: new BN(0), mod: this }; } // Very short reduction if (num.length === 1) { if (mode === 'div') { return { div: this.divn(num.words[0]), mod: null }; } if (mode === 'mod') { return { div: null, mod: new BN(this.modrn(num.words[0])) }; } return { div: this.divn(num.words[0]), mod: new BN(this.modrn(num.words[0])) }; } return this._wordDiv(num, mode); }; // Find `this` / `num` BN.prototype.div = function div(num) { return this.divmod(num, 'div', false).div; }; // Find `this` % `num` BN.prototype.mod = function mod(num) { return this.divmod(num, 'mod', false).mod; }; BN.prototype.umod = function umod(num) { return this.divmod(num, 'mod', true).mod; }; // Find Round(`this` / `num`) BN.prototype.divRound = function divRound(num) { var dm = this.divmod(num); // Fast case - exact division if (dm.mod.isZero()) return dm.div; var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; var half = num.ushrn(1); var r2 = num.andln(1); var cmp = mod.cmp(half); // Round down if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; // Round up return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); }; BN.prototype.modrn = function modrn(num) { var isNegNum = num < 0; if (isNegNum) num = -num; assert(num <= 0x3ffffff); var p = (1 << 26) % num; var acc = 0; for (var i = this.length - 1; i >= 0; i--) { acc = (p * acc + (this.words[i] | 0)) % num; } return isNegNum ? -acc : acc; }; // WARNING: DEPRECATED BN.prototype.modn = function modn(num) { return this.modrn(num); }; // In-place division by number BN.prototype.idivn = function idivn(num) { var isNegNum = num < 0; if (isNegNum) num = -num; assert(num <= 0x3ffffff); var carry = 0; for (var i = this.length - 1; i >= 0; i--) { var w = (this.words[i] | 0) + carry * 0x4000000; this.words[i] = w / num | 0; carry = w % num; } this._strip(); return isNegNum ? this.ineg() : this; }; BN.prototype.divn = function divn(num) { return this.clone().idivn(num); }; BN.prototype.egcd = function egcd(p) { assert(p.negative === 0); assert(!p.isZero()); var x = this; var y = p.clone(); if (x.negative !== 0) { x = x.umod(p); } else { x = x.clone(); } // A * x + B * y = x var A = new BN(1); var B = new BN(0); // C * x + D * y = y var C = new BN(0); var D = new BN(1); var g = 0; while (x.isEven() && y.isEven()) { x.iushrn(1); y.iushrn(1); ++g; } var yp = y.clone(); var xp = x.clone(); while (!x.isZero()) { for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1) { ; } if (i > 0) { x.iushrn(i); while (i-- > 0) { if (A.isOdd() || B.isOdd()) { A.iadd(yp); B.isub(xp); } A.iushrn(1); B.iushrn(1); } } for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) { ; } if (j > 0) { y.iushrn(j); while (j-- > 0) { if (C.isOdd() || D.isOdd()) { C.iadd(yp); D.isub(xp); } C.iushrn(1); D.iushrn(1); } } if (x.cmp(y) >= 0) { x.isub(y); A.isub(C); B.isub(D); } else { y.isub(x); C.isub(A); D.isub(B); } } return { a: C, b: D, gcd: y.iushln(g) }; }; // This is reduced incarnation of the binary EEA // above, designated to invert members of the // _prime_ fields F(p) at a maximal speed BN.prototype._invmp = function _invmp(p) { assert(p.negative === 0); assert(!p.isZero()); var a = this; var b = p.clone(); if (a.negative !== 0) { a = a.umod(p); } else { a = a.clone(); } var x1 = new BN(1); var x2 = new BN(0); var delta = b.clone(); while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1) { ; } if (i > 0) { a.iushrn(i); while (i-- > 0) { if (x1.isOdd()) { x1.iadd(delta); } x1.iushrn(1); } } for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) { ; } if (j > 0) { b.iushrn(j); while (j-- > 0) { if (x2.isOdd()) { x2.iadd(delta); } x2.iushrn(1); } } if (a.cmp(b) >= 0) { a.isub(b); x1.isub(x2); } else { b.isub(a); x2.isub(x1); } } var res; if (a.cmpn(1) === 0) { res = x1; } else { res = x2; } if (res.cmpn(0) < 0) { res.iadd(p); } return res; }; BN.prototype.gcd = function gcd(num) { if (this.isZero()) return num.abs(); if (num.isZero()) return this.abs(); var a = this.clone(); var b = num.clone(); a.negative = 0; b.negative = 0; // Remove common factor of two for (var shift = 0; a.isEven() && b.isEven(); shift++) { a.iushrn(1); b.iushrn(1); } do { while (a.isEven()) { a.iushrn(1); } while (b.isEven()) { b.iushrn(1); } var r = a.cmp(b); if (r < 0) { // Swap `a` and `b` to make `a` always bigger than `b` var t = a; a = b; b = t; } else if (r === 0 || b.cmpn(1) === 0) { break; } a.isub(b); } while (true); return b.iushln(shift); }; // Invert number in the field F(num) BN.prototype.invm = function invm(num) { return this.egcd(num).a.umod(num); }; BN.prototype.isEven = function isEven() { return (this.words[0] & 1) === 0; }; BN.prototype.isOdd = function isOdd() { return (this.words[0] & 1) === 1; }; // And first word and num BN.prototype.andln = function andln(num) { return this.words[0] & num; }; // Increment at the bit position in-line BN.prototype.bincn = function bincn(bit) { assert(typeof bit === 'number'); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) { this._expand(s + 1); this.words[s] |= q; return this; } // Add bit and propagate, if needed var carry = q; for (var i = s; carry !== 0 && i < this.length; i++) { var w = this.words[i] | 0; w += carry; carry = w >>> 26; w &= 0x3ffffff; this.words[i] = w; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.isZero = function isZero() { return this.length === 1 && this.words[0] === 0; }; BN.prototype.cmpn = function cmpn(num) { var negative = num < 0; if (this.negative !== 0 && !negative) return -1; if (this.negative === 0 && negative) return 1; this._strip(); var res; if (this.length > 1) { res = 1; } else { if (negative) { num = -num; } assert(num <= 0x3ffffff, 'Number is too big'); var w = this.words[0] | 0; res = w === num ? 0 : w < num ? -1 : 1; } if (this.negative !== 0) return -res | 0; return res; }; // Compare two numbers and return: // 1 - if `this` > `num` // 0 - if `this` == `num` // -1 - if `this` < `num` BN.prototype.cmp = function cmp(num) { if (this.negative !== 0 && num.negative === 0) return -1; if (this.negative === 0 && num.negative !== 0) return 1; var res = this.ucmp(num); if (this.negative !== 0) return -res | 0; return res; }; // Unsigned comparison BN.prototype.ucmp = function ucmp(num) { // At this point both numbers have the same sign if (this.length > num.length) return 1; if (this.length < num.length) return -1; var res = 0; for (var i = this.length - 1; i >= 0; i--) { var a = this.words[i] | 0; var b = num.words[i] | 0; if (a === b) continue; if (a < b) { res = -1; } else if (a > b) { res = 1; } break; } return res; }; BN.prototype.gtn = function gtn(num) { return this.cmpn(num) === 1; }; BN.prototype.gt = function gt(num) { return this.cmp(num) === 1; }; BN.prototype.gten = function gten(num) { return this.cmpn(num) >= 0; }; BN.prototype.gte = function gte(num) { return this.cmp(num) >= 0; }; BN.prototype.ltn = function ltn(num) { return this.cmpn(num) === -1; }; BN.prototype.lt = function lt(num) { return this.cmp(num) === -1; }; BN.prototype.lten = function lten(num) { return this.cmpn(num) <= 0; }; BN.prototype.lte = function lte(num) { return this.cmp(num) <= 0; }; BN.prototype.eqn = function eqn(num) { return this.cmpn(num) === 0; }; BN.prototype.eq = function eq(num) { return this.cmp(num) === 0; }; // // A reduce context, could be using montgomery or something better, depending // on the `m` itself. // BN.red = function red(num) { return new Red(num); }; BN.prototype.toRed = function toRed(ctx) { assert(!this.red, 'Already a number in reduction context'); assert(this.negative === 0, 'red works only with positives'); return ctx.convertTo(this)._forceRed(ctx); }; BN.prototype.fromRed = function fromRed() { assert(this.red, 'fromRed works only with numbers in reduction context'); return this.red.convertFrom(this); }; BN.prototype._forceRed = function _forceRed(ctx) { this.red = ctx; return this; }; BN.prototype.forceRed = function forceRed(ctx) { assert(!this.red, 'Already a number in reduction context'); return this._forceRed(ctx); }; BN.prototype.redAdd = function redAdd(num) { assert(this.red, 'redAdd works only with red numbers'); return this.red.add(this, num); }; BN.prototype.redIAdd = function redIAdd(num) { assert(this.red, 'redIAdd works only with red numbers'); return this.red.iadd(this, num); }; BN.prototype.redSub = function redSub(num) { assert(this.red, 'redSub works only with red numbers'); return this.red.sub(this, num); }; BN.prototype.redISub = function redISub(num) { assert(this.red, 'redISub works only with red numbers'); return this.red.isub(this, num); }; BN.prototype.redShl = function redShl(num) { assert(this.red, 'redShl works only with red numbers'); return this.red.shl(this, num); }; BN.prototype.redMul = function redMul(num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.mul(this, num); }; BN.prototype.redIMul = function redIMul(num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.imul(this, num); }; BN.prototype.redSqr = function redSqr() { assert(this.red, 'redSqr works only with red numbers'); this.red._verify1(this); return this.red.sqr(this); }; BN.prototype.redISqr = function redISqr() { assert(this.red, 'redISqr works only with red numbers'); this.red._verify1(this); return this.red.isqr(this); }; // Square root over p BN.prototype.redSqrt = function redSqrt() { assert(this.red, 'redSqrt works only with red numbers'); this.red._verify1(this); return this.red.sqrt(this); }; BN.prototype.redInvm = function redInvm() { assert(this.red, 'redInvm works only with red numbers'); this.red._verify1(this); return this.red.invm(this); }; // Return negative clone of `this` % `red modulo` BN.prototype.redNeg = function redNeg() { assert(this.red, 'redNeg works only with red numbers'); this.red._verify1(this); return this.red.neg(this); }; BN.prototype.redPow = function redPow(num) { assert(this.red && !num.red, 'redPow(normalNum)'); this.red._verify1(this); return this.red.pow(this, num); }; // Prime numbers with efficient reduction var primes = { k256: null, p224: null, p192: null, p25519: null }; // Pseudo-Mersenne prime function MPrime(name, p) { // P = 2 ^ N - K this.name = name; this.p = new BN(p, 16); this.n = this.p.bitLength(); this.k = new BN(1).iushln(this.n).isub(this.p); this.tmp = this._tmp(); } MPrime.prototype._tmp = function _tmp() { var tmp = new BN(null); tmp.words = new Array(Math.ceil(this.n / 13)); return tmp; }; MPrime.prototype.ireduce = function ireduce(num) { // Assumes that `num` is less than `P^2` // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) var r = num; var rlen; do { this.split(r, this.tmp); r = this.imulK(r); r = r.iadd(this.tmp); rlen = r.bitLength(); } while (rlen > this.n); var cmp = rlen < this.n ? -1 : r.ucmp(this.p); if (cmp === 0) { r.words[0] = 0; r.length = 1; } else if (cmp > 0) { r.isub(this.p); } else { if (r.strip !== undefined) { // r is a BN v4 instance r.strip(); } else { // r is a BN v5 instance r._strip(); } } return r; }; MPrime.prototype.split = function split(input, out) { input.iushrn(this.n, 0, out); }; MPrime.prototype.imulK = function imulK(num) { return num.imul(this.k); }; function K256() { MPrime.call(this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); } inherits(K256, MPrime); K256.prototype.split = function split(input, output) { // 256 = 9 * 26 + 22 var mask = 0x3fffff; var outLen = Math.min(input.length, 9); for (var i = 0; i < outLen; i++) { output.words[i] = input.words[i]; } output.length = outLen; if (input.length <= 9) { input.words[0] = 0; input.length = 1; return; } // Shift by 9 limbs var prev = input.words[9]; output.words[output.length++] = prev & mask; for (i = 10; i < input.length; i++) { var next = input.words[i] | 0; input.words[i - 10] = (next & mask) << 4 | prev >>> 22; prev = next; } prev >>>= 22; input.words[i - 10] = prev; if (prev === 0 && input.length > 10) { input.length -= 10; } else { input.length -= 9; } }; K256.prototype.imulK = function imulK(num) { // K = 0x1000003d1 = [ 0x40, 0x3d1 ] num.words[num.length] = 0; num.words[num.length + 1] = 0; num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 var lo = 0; for (var i = 0; i < num.length; i++) { var w = num.words[i] | 0; lo += w * 0x3d1; num.words[i] = lo & 0x3ffffff; lo = w * 0x40 + (lo / 0x4000000 | 0); } // Fast length reduction if (num.words[num.length - 1] === 0) { num.length--; if (num.words[num.length - 1] === 0) { num.length--; } } return num; }; function P224() { MPrime.call(this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } inherits(P224, MPrime); function P192() { MPrime.call(this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } inherits(P192, MPrime); function P25519() { // 2 ^ 255 - 19 MPrime.call(this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } inherits(P25519, MPrime); P25519.prototype.imulK = function imulK(num) { // K = 0x13 var carry = 0; for (var i = 0; i < num.length; i++) { var hi = (num.words[i] | 0) * 0x13 + carry; var lo = hi & 0x3ffffff; hi >>>= 26; num.words[i] = lo; carry = hi; } if (carry !== 0) { num.words[num.length++] = carry; } return num; }; // Exported mostly for testing purposes, use plain name instead BN._prime = function prime(name) { // Cached version of prime if (primes[name]) return primes[name]; var prime; if (name === 'k256') { prime = new K256(); } else if (name === 'p224') { prime = new P224(); } else if (name === 'p192') { prime = new P192(); } else if (name === 'p25519') { prime = new P25519(); } else { throw new Error('Unknown prime ' + name); } primes[name] = prime; return prime; }; // // Base reduction engine // function Red(m) { if (typeof m === 'string') { var prime = BN._prime(m); this.m = prime.p; this.prime = prime; } else { assert(m.gtn(1), 'modulus must be greater than 1'); this.m = m; this.prime = null; } } Red.prototype._verify1 = function _verify1(a) { assert(a.negative === 0, 'red works only with positives'); assert(a.red, 'red works only with red numbers'); }; Red.prototype._verify2 = function _verify2(a, b) { assert((a.negative | b.negative) === 0, 'red works only with positives'); assert(a.red && a.red === b.red, 'red works only with red numbers'); }; Red.prototype.imod = function imod(a) { if (this.prime) return this.prime.ireduce(a)._forceRed(this); move(a, a.umod(this.m)._forceRed(this)); return a; }; Red.prototype.neg = function neg(a) { if (a.isZero()) { return a.clone(); } return this.m.sub(a)._forceRed(this); }; Red.prototype.add = function add(a, b) { this._verify2(a, b); var res = a.add(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res._forceRed(this); }; Red.prototype.iadd = function iadd(a, b) { this._verify2(a, b); var res = a.iadd(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res; }; Red.prototype.sub = function sub(a, b) { this._verify2(a, b); var res = a.sub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res._forceRed(this); }; Red.prototype.isub = function isub(a, b) { this._verify2(a, b); var res = a.isub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res; }; Red.prototype.shl = function shl(a, num) { this._verify1(a); return this.imod(a.ushln(num)); }; Red.prototype.imul = function imul(a, b) { this._verify2(a, b); return this.imod(a.imul(b)); }; Red.prototype.mul = function mul(a, b) { this._verify2(a, b); return this.imod(a.mul(b)); }; Red.prototype.isqr = function isqr(a) { return this.imul(a, a.clone()); }; Red.prototype.sqr = function sqr(a) { return this.mul(a, a); }; Red.prototype.sqrt = function sqrt(a) { if (a.isZero()) return a.clone(); var mod3 = this.m.andln(3); assert(mod3 % 2 === 1); // Fast case if (mod3 === 3) { var pow = this.m.add(new BN(1)).iushrn(2); return this.pow(a, pow); } // Tonelli-Shanks algorithm (Totally unoptimized and slow) // // Find Q and S, that Q * 2 ^ S = (P - 1) var q = this.m.subn(1); var s = 0; while (!q.isZero() && q.andln(1) === 0) { s++; q.iushrn(1); } assert(!q.isZero()); var one = new BN(1).toRed(this); var nOne = one.redNeg(); // Find quadratic non-residue // NOTE: Max is such because of generalized Riemann hypothesis. var lpow = this.m.subn(1).iushrn(1); var z = this.m.bitLength(); z = new BN(2 * z * z).toRed(this); while (this.pow(z, lpow).cmp(nOne) !== 0) { z.redIAdd(nOne); } var c = this.pow(z, q); var r = this.pow(a, q.addn(1).iushrn(1)); var t = this.pow(a, q); var m = s; while (t.cmp(one) !== 0) { var tmp = t; for (var i = 0; tmp.cmp(one) !== 0; i++) { tmp = tmp.redSqr(); } assert(i < m); var b = this.pow(c, new BN(1).iushln(m - i - 1)); r = r.redMul(b); c = b.redSqr(); t = t.redMul(c); m = i; } return r; }; Red.prototype.invm = function invm(a) { var inv = a._invmp(this.m); if (inv.negative !== 0) { inv.negative = 0; return this.imod(inv).redNeg(); } else { return this.imod(inv); } }; Red.prototype.pow = function pow(a, num) { if (num.isZero()) return new BN(1).toRed(this); if (num.cmpn(1) === 0) return a.clone(); var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN(1).toRed(this); wnd[1] = a; for (var i = 2; i < wnd.length; i++) { wnd[i] = this.mul(wnd[i - 1], a); } var res = wnd[0]; var current = 0; var currentLen = 0; var start = num.bitLength() % 26; if (start === 0) { start = 26; } for (i = num.length - 1; i >= 0; i--) { var word = num.words[i]; for (var j = start - 1; j >= 0; j--) { var bit = word >> j & 1; if (res !== wnd[0]) { res = this.sqr(res); } if (bit === 0 && current === 0) { currentLen = 0; continue; } current <<= 1; current |= bit; currentLen++; if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; res = this.mul(res, wnd[current]); currentLen = 0; current = 0; } start = 26; } return res; }; Red.prototype.convertTo = function convertTo(num) { var r = num.umod(this.m); return r === num ? r.clone() : r; }; Red.prototype.convertFrom = function convertFrom(num) { var res = num.clone(); res.red = null; return res; }; // // Montgomery method engine // BN.mont = function mont(num) { return new Mont(num); }; function Mont(m) { Red.call(this, m); this.shift = this.m.bitLength(); if (this.shift % 26 !== 0) { this.shift += 26 - this.shift % 26; } this.r = new BN(1).iushln(this.shift); this.r2 = this.imod(this.r.sqr()); this.rinv = this.r._invmp(this.m); this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); this.minv = this.minv.umod(this.r); this.minv = this.r.sub(this.minv); } inherits(Mont, Red); Mont.prototype.convertTo = function convertTo(num) { return this.imod(num.ushln(this.shift)); }; Mont.prototype.convertFrom = function convertFrom(num) { var r = this.imod(num.mul(this.rinv)); r.red = null; return r; }; Mont.prototype.imul = function imul(a, b) { if (a.isZero() || b.isZero()) { a.words[0] = 0; a.length = 1; return a; } var t = a.imul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.mul = function mul(a, b) { if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); var t = a.mul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.invm = function invm(a) { // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R var res = this.imod(a._invmp(this.m).mul(this.r2)); return res._forceRed(this); }; })( false || module, this); /***/ }), /***/ 7179: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var r; module.exports = function rand(len) { if (!r) r = new Rand(null); return r.generate(len); }; function Rand(rand) { this.rand = rand; } module.exports.Rand = Rand; Rand.prototype.generate = function generate(len) { return this._rand(len); }; // Emulate crypto API using randy Rand.prototype._rand = function _rand(n) { if (this.rand.getBytes) return this.rand.getBytes(n); var res = new Uint8Array(n); for (var i = 0; i < res.length; i++) { res[i] = this.rand.getByte(); } return res; }; if ((typeof self === "undefined" ? "undefined" : _typeof(self)) === 'object') { if (self.crypto && self.crypto.getRandomValues) { // Modern browsers Rand.prototype._rand = function _rand(n) { var arr = new Uint8Array(n); self.crypto.getRandomValues(arr); return arr; }; } else if (self.msCrypto && self.msCrypto.getRandomValues) { // IE Rand.prototype._rand = function _rand(n) { var arr = new Uint8Array(n); self.msCrypto.getRandomValues(arr); return arr; }; // Safari's WebWorkers do not have `crypto` } else if ((typeof window === "undefined" ? "undefined" : _typeof(window)) === 'object') { // Old junk Rand.prototype._rand = function () { throw new Error('Not implemented yet'); }; } } else { // Node.js or Web worker with no crypto support try { var crypto = __webpack_require__(9214); if (typeof crypto.randomBytes !== 'function') throw new Error('Not supported'); Rand.prototype._rand = function _rand(n) { return crypto.randomBytes(n); }; } catch (e) {} } /***/ }), /***/ 7463: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // based on the aes implimentation in triple sec // https://github.com/keybase/triplesec // which is in turn based on the one from crypto-js // https://code.google.com/p/crypto-js/ var Buffer = (__webpack_require__(9047).Buffer); function asUInt32Array(buf) { if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf); var len = buf.length / 4 | 0; var out = new Array(len); for (var i = 0; i < len; i++) { out[i] = buf.readUInt32BE(i * 4); } return out; } function scrubVec(v) { for (var i = 0; i < v.length; v++) { v[i] = 0; } } function cryptBlock(M, keySchedule, SUB_MIX, SBOX, nRounds) { var SUB_MIX0 = SUB_MIX[0]; var SUB_MIX1 = SUB_MIX[1]; var SUB_MIX2 = SUB_MIX[2]; var SUB_MIX3 = SUB_MIX[3]; var s0 = M[0] ^ keySchedule[0]; var s1 = M[1] ^ keySchedule[1]; var s2 = M[2] ^ keySchedule[2]; var s3 = M[3] ^ keySchedule[3]; var t0, t1, t2, t3; var ksRow = 4; for (var round = 1; round < nRounds; round++) { t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[s1 >>> 16 & 0xff] ^ SUB_MIX2[s2 >>> 8 & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]; t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[s2 >>> 16 & 0xff] ^ SUB_MIX2[s3 >>> 8 & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]; t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[s3 >>> 16 & 0xff] ^ SUB_MIX2[s0 >>> 8 & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]; t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[s0 >>> 16 & 0xff] ^ SUB_MIX2[s1 >>> 8 & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]; s0 = t0; s1 = t1; s2 = t2; s3 = t3; } t0 = (SBOX[s0 >>> 24] << 24 | SBOX[s1 >>> 16 & 0xff] << 16 | SBOX[s2 >>> 8 & 0xff] << 8 | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; t1 = (SBOX[s1 >>> 24] << 24 | SBOX[s2 >>> 16 & 0xff] << 16 | SBOX[s3 >>> 8 & 0xff] << 8 | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; t2 = (SBOX[s2 >>> 24] << 24 | SBOX[s3 >>> 16 & 0xff] << 16 | SBOX[s0 >>> 8 & 0xff] << 8 | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; t3 = (SBOX[s3 >>> 24] << 24 | SBOX[s0 >>> 16 & 0xff] << 16 | SBOX[s1 >>> 8 & 0xff] << 8 | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; t0 = t0 >>> 0; t1 = t1 >>> 0; t2 = t2 >>> 0; t3 = t3 >>> 0; return [t0, t1, t2, t3]; } // AES constants var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; var G = function () { // Compute double table var d = new Array(256); for (var j = 0; j < 256; j++) { if (j < 128) { d[j] = j << 1; } else { d[j] = j << 1 ^ 0x11b; } } var SBOX = []; var INV_SBOX = []; var SUB_MIX = [[], [], [], []]; var INV_SUB_MIX = [[], [], [], []]; // Walk GF(2^8) var x = 0; var xi = 0; for (var i = 0; i < 256; ++i) { // Compute sbox var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4; sx = sx >>> 8 ^ sx & 0xff ^ 0x63; SBOX[x] = sx; INV_SBOX[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub bytes, mix columns tables var t = d[sx] * 0x101 ^ sx * 0x1010100; SUB_MIX[0][x] = t << 24 | t >>> 8; SUB_MIX[1][x] = t << 16 | t >>> 16; SUB_MIX[2][x] = t << 8 | t >>> 24; SUB_MIX[3][x] = t; // Compute inv sub bytes, inv mix columns tables t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100; INV_SUB_MIX[0][sx] = t << 24 | t >>> 8; INV_SUB_MIX[1][sx] = t << 16 | t >>> 16; INV_SUB_MIX[2][sx] = t << 8 | t >>> 24; INV_SUB_MIX[3][sx] = t; if (x === 0) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } return { SBOX: SBOX, INV_SBOX: INV_SBOX, SUB_MIX: SUB_MIX, INV_SUB_MIX: INV_SUB_MIX }; }(); function AES(key) { this._key = asUInt32Array(key); this._reset(); } AES.blockSize = 4 * 4; AES.keySize = 256 / 8; AES.prototype.blockSize = AES.blockSize; AES.prototype.keySize = AES.keySize; AES.prototype._reset = function () { var keyWords = this._key; var keySize = keyWords.length; var nRounds = keySize + 6; var ksRows = (nRounds + 1) * 4; var keySchedule = []; for (var k = 0; k < keySize; k++) { keySchedule[k] = keyWords[k]; } for (k = keySize; k < ksRows; k++) { var t = keySchedule[k - 1]; if (k % keySize === 0) { t = t << 8 | t >>> 24; t = G.SBOX[t >>> 24] << 24 | G.SBOX[t >>> 16 & 0xff] << 16 | G.SBOX[t >>> 8 & 0xff] << 8 | G.SBOX[t & 0xff]; t ^= RCON[k / keySize | 0] << 24; } else if (keySize > 6 && k % keySize === 4) { t = G.SBOX[t >>> 24] << 24 | G.SBOX[t >>> 16 & 0xff] << 16 | G.SBOX[t >>> 8 & 0xff] << 8 | G.SBOX[t & 0xff]; } keySchedule[k] = keySchedule[k - keySize] ^ t; } var invKeySchedule = []; for (var ik = 0; ik < ksRows; ik++) { var ksR = ksRows - ik; var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]; if (ik < 4 || ksR <= 4) { invKeySchedule[ik] = tt; } else { invKeySchedule[ik] = G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[tt >>> 16 & 0xff]] ^ G.INV_SUB_MIX[2][G.SBOX[tt >>> 8 & 0xff]] ^ G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]; } } this._nRounds = nRounds; this._keySchedule = keySchedule; this._invKeySchedule = invKeySchedule; }; AES.prototype.encryptBlockRaw = function (M) { M = asUInt32Array(M); return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds); }; AES.prototype.encryptBlock = function (M) { var out = this.encryptBlockRaw(M); var buf = Buffer.allocUnsafe(16); buf.writeUInt32BE(out[0], 0); buf.writeUInt32BE(out[1], 4); buf.writeUInt32BE(out[2], 8); buf.writeUInt32BE(out[3], 12); return buf; }; AES.prototype.decryptBlock = function (M) { M = asUInt32Array(M); // swap var m1 = M[1]; M[1] = M[3]; M[3] = m1; var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds); var buf = Buffer.allocUnsafe(16); buf.writeUInt32BE(out[0], 0); buf.writeUInt32BE(out[3], 4); buf.writeUInt32BE(out[2], 8); buf.writeUInt32BE(out[1], 12); return buf; }; AES.prototype.scrub = function () { scrubVec(this._keySchedule); scrubVec(this._invKeySchedule); scrubVec(this._key); }; module.exports.AES = AES; /***/ }), /***/ 3499: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var aes = __webpack_require__(7463); var Buffer = (__webpack_require__(9047).Buffer); var Transform = __webpack_require__(8842); var inherits = __webpack_require__(376); var GHASH = __webpack_require__(1225); var xor = __webpack_require__(5176); var incr32 = __webpack_require__(4001); function xorTest(a, b) { var out = 0; if (a.length !== b.length) out++; var len = Math.min(a.length, b.length); for (var i = 0; i < len; ++i) { out += a[i] ^ b[i]; } return out; } function calcIv(self, iv, ck) { if (iv.length === 12) { self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])]); return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])]); } var ghash = new GHASH(ck); var len = iv.length; var toPad = len % 16; ghash.update(iv); if (toPad) { toPad = 16 - toPad; ghash.update(Buffer.alloc(toPad, 0)); } ghash.update(Buffer.alloc(8, 0)); var ivBits = len * 8; var tail = Buffer.alloc(8); tail.writeUIntBE(ivBits, 0, 8); ghash.update(tail); self._finID = ghash.state; var out = Buffer.from(self._finID); incr32(out); return out; } function StreamCipher(mode, key, iv, decrypt) { Transform.call(this); var h = Buffer.alloc(4, 0); this._cipher = new aes.AES(key); var ck = this._cipher.encryptBlock(h); this._ghash = new GHASH(ck); iv = calcIv(this, iv, ck); this._prev = Buffer.from(iv); this._cache = Buffer.allocUnsafe(0); this._secCache = Buffer.allocUnsafe(0); this._decrypt = decrypt; this._alen = 0; this._len = 0; this._mode = mode; this._authTag = null; this._called = false; } inherits(StreamCipher, Transform); StreamCipher.prototype._update = function (chunk) { if (!this._called && this._alen) { var rump = 16 - this._alen % 16; if (rump < 16) { rump = Buffer.alloc(rump, 0); this._ghash.update(rump); } } this._called = true; var out = this._mode.encrypt(this, chunk); if (this._decrypt) { this._ghash.update(chunk); } else { this._ghash.update(out); } this._len += chunk.length; return out; }; StreamCipher.prototype._final = function () { if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data'); var tag = xor(this._ghash["final"](this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)); if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data'); this._authTag = tag; this._cipher.scrub(); }; StreamCipher.prototype.getAuthTag = function getAuthTag() { if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state'); return this._authTag; }; StreamCipher.prototype.setAuthTag = function setAuthTag(tag) { if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state'); this._authTag = tag; }; StreamCipher.prototype.setAAD = function setAAD(buf) { if (this._called) throw new Error('Attempting to set AAD in unsupported state'); this._ghash.update(buf); this._alen += buf.length; }; module.exports = StreamCipher; /***/ }), /***/ 4881: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var ciphers = __webpack_require__(8613); var deciphers = __webpack_require__(7909); var modes = __webpack_require__(4946); function getCiphers() { return Object.keys(modes); } exports.createCipher = exports.Cipher = ciphers.createCipher; exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv; exports.createDecipher = exports.Decipher = deciphers.createDecipher; exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv; exports.listCiphers = exports.getCiphers = getCiphers; /***/ }), /***/ 7909: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var AuthCipher = __webpack_require__(3499); var Buffer = (__webpack_require__(9047).Buffer); var MODES = __webpack_require__(6572); var StreamCipher = __webpack_require__(7188); var Transform = __webpack_require__(8842); var aes = __webpack_require__(7463); var ebtk = __webpack_require__(1248); var inherits = __webpack_require__(376); function Decipher(mode, key, iv) { Transform.call(this); this._cache = new Splitter(); this._last = void 0; this._cipher = new aes.AES(key); this._prev = Buffer.from(iv); this._mode = mode; this._autopadding = true; } inherits(Decipher, Transform); Decipher.prototype._update = function (data) { this._cache.add(data); var chunk; var thing; var out = []; while (chunk = this._cache.get(this._autopadding)) { thing = this._mode.decrypt(this, chunk); out.push(thing); } return Buffer.concat(out); }; Decipher.prototype._final = function () { var chunk = this._cache.flush(); if (this._autopadding) { return unpad(this._mode.decrypt(this, chunk)); } else if (chunk) { throw new Error('data not multiple of block length'); } }; Decipher.prototype.setAutoPadding = function (setTo) { this._autopadding = !!setTo; return this; }; function Splitter() { this.cache = Buffer.allocUnsafe(0); } Splitter.prototype.add = function (data) { this.cache = Buffer.concat([this.cache, data]); }; Splitter.prototype.get = function (autoPadding) { var out; if (autoPadding) { if (this.cache.length > 16) { out = this.cache.slice(0, 16); this.cache = this.cache.slice(16); return out; } } else { if (this.cache.length >= 16) { out = this.cache.slice(0, 16); this.cache = this.cache.slice(16); return out; } } return null; }; Splitter.prototype.flush = function () { if (this.cache.length) return this.cache; }; function unpad(last) { var padded = last[15]; if (padded < 1 || padded > 16) { throw new Error('unable to decrypt data'); } var i = -1; while (++i < padded) { if (last[i + (16 - padded)] !== padded) { throw new Error('unable to decrypt data'); } } if (padded === 16) return; return last.slice(0, 16 - padded); } function createDecipheriv(suite, password, iv) { var config = MODES[suite.toLowerCase()]; if (!config) throw new TypeError('invalid suite type'); if (typeof iv === 'string') iv = Buffer.from(iv); if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length); if (typeof password === 'string') password = Buffer.from(password); if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length); if (config.type === 'stream') { return new StreamCipher(config.module, password, iv, true); } else if (config.type === 'auth') { return new AuthCipher(config.module, password, iv, true); } return new Decipher(config.module, password, iv); } function createDecipher(suite, password) { var config = MODES[suite.toLowerCase()]; if (!config) throw new TypeError('invalid suite type'); var keys = ebtk(password, false, config.key, config.iv); return createDecipheriv(suite, keys.key, keys.iv); } exports.createDecipher = createDecipher; exports.createDecipheriv = createDecipheriv; /***/ }), /***/ 8613: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var MODES = __webpack_require__(6572); var AuthCipher = __webpack_require__(3499); var Buffer = (__webpack_require__(9047).Buffer); var StreamCipher = __webpack_require__(7188); var Transform = __webpack_require__(8842); var aes = __webpack_require__(7463); var ebtk = __webpack_require__(1248); var inherits = __webpack_require__(376); function Cipher(mode, key, iv) { Transform.call(this); this._cache = new Splitter(); this._cipher = new aes.AES(key); this._prev = Buffer.from(iv); this._mode = mode; this._autopadding = true; } inherits(Cipher, Transform); Cipher.prototype._update = function (data) { this._cache.add(data); var chunk; var thing; var out = []; while (chunk = this._cache.get()) { thing = this._mode.encrypt(this, chunk); out.push(thing); } return Buffer.concat(out); }; var PADDING = Buffer.alloc(16, 0x10); Cipher.prototype._final = function () { var chunk = this._cache.flush(); if (this._autopadding) { chunk = this._mode.encrypt(this, chunk); this._cipher.scrub(); return chunk; } if (!chunk.equals(PADDING)) { this._cipher.scrub(); throw new Error('data not multiple of block length'); } }; Cipher.prototype.setAutoPadding = function (setTo) { this._autopadding = !!setTo; return this; }; function Splitter() { this.cache = Buffer.allocUnsafe(0); } Splitter.prototype.add = function (data) { this.cache = Buffer.concat([this.cache, data]); }; Splitter.prototype.get = function () { if (this.cache.length > 15) { var out = this.cache.slice(0, 16); this.cache = this.cache.slice(16); return out; } return null; }; Splitter.prototype.flush = function () { var len = 16 - this.cache.length; var padBuff = Buffer.allocUnsafe(len); var i = -1; while (++i < len) { padBuff.writeUInt8(len, i); } return Buffer.concat([this.cache, padBuff]); }; function createCipheriv(suite, password, iv) { var config = MODES[suite.toLowerCase()]; if (!config) throw new TypeError('invalid suite type'); if (typeof password === 'string') password = Buffer.from(password); if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length); if (typeof iv === 'string') iv = Buffer.from(iv); if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length); if (config.type === 'stream') { return new StreamCipher(config.module, password, iv); } else if (config.type === 'auth') { return new AuthCipher(config.module, password, iv); } return new Cipher(config.module, password, iv); } function createCipher(suite, password) { var config = MODES[suite.toLowerCase()]; if (!config) throw new TypeError('invalid suite type'); var keys = ebtk(password, false, config.key, config.iv); return createCipheriv(suite, keys.key, keys.iv); } exports.createCipheriv = createCipheriv; exports.createCipher = createCipher; /***/ }), /***/ 1225: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var Buffer = (__webpack_require__(9047).Buffer); var ZEROES = Buffer.alloc(16, 0); function toArray(buf) { return [buf.readUInt32BE(0), buf.readUInt32BE(4), buf.readUInt32BE(8), buf.readUInt32BE(12)]; } function fromArray(out) { var buf = Buffer.allocUnsafe(16); buf.writeUInt32BE(out[0] >>> 0, 0); buf.writeUInt32BE(out[1] >>> 0, 4); buf.writeUInt32BE(out[2] >>> 0, 8); buf.writeUInt32BE(out[3] >>> 0, 12); return buf; } function GHASH(key) { this.h = key; this.state = Buffer.alloc(16, 0); this.cache = Buffer.allocUnsafe(0); } // from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html // by Juho Vähä-Herttua GHASH.prototype.ghash = function (block) { var i = -1; while (++i < block.length) { this.state[i] ^= block[i]; } this._multiply(); }; GHASH.prototype._multiply = function () { var Vi = toArray(this.h); var Zi = [0, 0, 0, 0]; var j, xi, lsbVi; var i = -1; while (++i < 128) { xi = (this.state[~~(i / 8)] & 1 << 7 - i % 8) !== 0; if (xi) { // Z_i+1 = Z_i ^ V_i Zi[0] ^= Vi[0]; Zi[1] ^= Vi[1]; Zi[2] ^= Vi[2]; Zi[3] ^= Vi[3]; } // Store the value of LSB(V_i) lsbVi = (Vi[3] & 1) !== 0; // V_i+1 = V_i >> 1 for (j = 3; j > 0; j--) { Vi[j] = Vi[j] >>> 1 | (Vi[j - 1] & 1) << 31; } Vi[0] = Vi[0] >>> 1; // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R if (lsbVi) { Vi[0] = Vi[0] ^ 0xe1 << 24; } } this.state = fromArray(Zi); }; GHASH.prototype.update = function (buf) { this.cache = Buffer.concat([this.cache, buf]); var chunk; while (this.cache.length >= 16) { chunk = this.cache.slice(0, 16); this.cache = this.cache.slice(16); this.ghash(chunk); } }; GHASH.prototype["final"] = function (abl, bl) { if (this.cache.length) { this.ghash(Buffer.concat([this.cache, ZEROES], 16)); } this.ghash(fromArray([0, abl, 0, bl])); return this.state; }; module.exports = GHASH; /***/ }), /***/ 4001: /***/ ((module) => { function incr32(iv) { var len = iv.length; var item; while (len--) { item = iv.readUInt8(len); if (item === 255) { iv.writeUInt8(0, len); } else { item++; iv.writeUInt8(item, len); break; } } } module.exports = incr32; /***/ }), /***/ 9628: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var xor = __webpack_require__(5176); exports.encrypt = function (self, block) { var data = xor(block, self._prev); self._prev = self._cipher.encryptBlock(data); return self._prev; }; exports.decrypt = function (self, block) { var pad = self._prev; self._prev = block; var out = self._cipher.decryptBlock(block); return xor(out, pad); }; /***/ }), /***/ 6674: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var Buffer = (__webpack_require__(9047).Buffer); var xor = __webpack_require__(5176); function encryptStart(self, data, decrypt) { var len = data.length; var out = xor(data, self._cache); self._cache = self._cache.slice(len); self._prev = Buffer.concat([self._prev, decrypt ? data : out]); return out; } exports.encrypt = function (self, data, decrypt) { var out = Buffer.allocUnsafe(0); var len; while (data.length) { if (self._cache.length === 0) { self._cache = self._cipher.encryptBlock(self._prev); self._prev = Buffer.allocUnsafe(0); } if (self._cache.length <= data.length) { len = self._cache.length; out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]); data = data.slice(len); } else { out = Buffer.concat([out, encryptStart(self, data, decrypt)]); break; } } return out; }; /***/ }), /***/ 9971: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var Buffer = (__webpack_require__(9047).Buffer); function encryptByte(self, byteParam, decrypt) { var pad; var i = -1; var len = 8; var out = 0; var bit, value; while (++i < len) { pad = self._cipher.encryptBlock(self._prev); bit = byteParam & 1 << 7 - i ? 0x80 : 0; value = pad[0] ^ bit; out += (value & 0x80) >> i % 8; self._prev = shiftIn(self._prev, decrypt ? bit : value); } return out; } function shiftIn(buffer, value) { var len = buffer.length; var i = -1; var out = Buffer.allocUnsafe(buffer.length); buffer = Buffer.concat([buffer, Buffer.from([value])]); while (++i < len) { out[i] = buffer[i] << 1 | buffer[i + 1] >> 7; } return out; } exports.encrypt = function (self, chunk, decrypt) { var len = chunk.length; var out = Buffer.allocUnsafe(len); var i = -1; while (++i < len) { out[i] = encryptByte(self, chunk[i], decrypt); } return out; }; /***/ }), /***/ 8194: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var Buffer = (__webpack_require__(9047).Buffer); function encryptByte(self, byteParam, decrypt) { var pad = self._cipher.encryptBlock(self._prev); var out = pad[0] ^ byteParam; self._prev = Buffer.concat([self._prev.slice(1), Buffer.from([decrypt ? byteParam : out])]); return out; } exports.encrypt = function (self, chunk, decrypt) { var len = chunk.length; var out = Buffer.allocUnsafe(len); var i = -1; while (++i < len) { out[i] = encryptByte(self, chunk[i], decrypt); } return out; }; /***/ }), /***/ 8871: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var xor = __webpack_require__(5176); var Buffer = (__webpack_require__(9047).Buffer); var incr32 = __webpack_require__(4001); function getBlock(self) { var out = self._cipher.encryptBlockRaw(self._prev); incr32(self._prev); return out; } var blockSize = 16; exports.encrypt = function (self, chunk) { var chunkNum = Math.ceil(chunk.length / blockSize); var start = self._cache.length; self._cache = Buffer.concat([self._cache, Buffer.allocUnsafe(chunkNum * blockSize)]); for (var i = 0; i < chunkNum; i++) { var out = getBlock(self); var offset = start + i * blockSize; self._cache.writeUInt32BE(out[0], offset + 0); self._cache.writeUInt32BE(out[1], offset + 4); self._cache.writeUInt32BE(out[2], offset + 8); self._cache.writeUInt32BE(out[3], offset + 12); } var pad = self._cache.slice(0, chunk.length); self._cache = self._cache.slice(chunk.length); return xor(chunk, pad); }; /***/ }), /***/ 8972: /***/ ((__unused_webpack_module, exports) => { exports.encrypt = function (self, block) { return self._cipher.encryptBlock(block); }; exports.decrypt = function (self, block) { return self._cipher.decryptBlock(block); }; /***/ }), /***/ 6572: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var modeModules = { ECB: __webpack_require__(8972), CBC: __webpack_require__(9628), CFB: __webpack_require__(6674), CFB8: __webpack_require__(8194), CFB1: __webpack_require__(9971), OFB: __webpack_require__(2343), CTR: __webpack_require__(8871), GCM: __webpack_require__(8871) }; var modes = __webpack_require__(4946); for (var key in modes) { modes[key].module = modeModules[modes[key].mode]; } module.exports = modes; /***/ }), /***/ 2343: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; var xor = __webpack_require__(5176); function getBlock(self) { self._prev = self._cipher.encryptBlock(self._prev); return self._prev; } exports.encrypt = function (self, chunk) { while (self._cache.length < chunk.length) { self._cache = Buffer.concat([self._cache, getBlock(self)]); } var pad = self._cache.slice(0, chunk.length); self._cache = self._cache.slice(chunk.length); return xor(chunk, pad); }; /***/ }), /***/ 7188: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var aes = __webpack_require__(7463); var Buffer = (__webpack_require__(9047).Buffer); var Transform = __webpack_require__(8842); var inherits = __webpack_require__(376); function StreamCipher(mode, key, iv, decrypt) { Transform.call(this); this._cipher = new aes.AES(key); this._prev = Buffer.from(iv); this._cache = Buffer.allocUnsafe(0); this._secCache = Buffer.allocUnsafe(0); this._decrypt = decrypt; this._mode = mode; } inherits(StreamCipher, Transform); StreamCipher.prototype._update = function (chunk) { return this._mode.encrypt(this, chunk, this._decrypt); }; StreamCipher.prototype._final = function () { this._cipher.scrub(); }; module.exports = StreamCipher; /***/ }), /***/ 5972: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var DES = __webpack_require__(7729); var aes = __webpack_require__(4881); var aesModes = __webpack_require__(6572); var desModes = __webpack_require__(3519); var ebtk = __webpack_require__(1248); function createCipher(suite, password) { suite = suite.toLowerCase(); var keyLen, ivLen; if (aesModes[suite]) { keyLen = aesModes[suite].key; ivLen = aesModes[suite].iv; } else if (desModes[suite]) { keyLen = desModes[suite].key * 8; ivLen = desModes[suite].iv; } else { throw new TypeError('invalid suite type'); } var keys = ebtk(password, false, keyLen, ivLen); return createCipheriv(suite, keys.key, keys.iv); } function createDecipher(suite, password) { suite = suite.toLowerCase(); var keyLen, ivLen; if (aesModes[suite]) { keyLen = aesModes[suite].key; ivLen = aesModes[suite].iv; } else if (desModes[suite]) { keyLen = desModes[suite].key * 8; ivLen = desModes[suite].iv; } else { throw new TypeError('invalid suite type'); } var keys = ebtk(password, false, keyLen, ivLen); return createDecipheriv(suite, keys.key, keys.iv); } function createCipheriv(suite, key, iv) { suite = suite.toLowerCase(); if (aesModes[suite]) return aes.createCipheriv(suite, key, iv); if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite }); throw new TypeError('invalid suite type'); } function createDecipheriv(suite, key, iv) { suite = suite.toLowerCase(); if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv); if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true }); throw new TypeError('invalid suite type'); } function getCiphers() { return Object.keys(desModes).concat(aes.getCiphers()); } exports.createCipher = exports.Cipher = createCipher; exports.createCipheriv = exports.Cipheriv = createCipheriv; exports.createDecipher = exports.Decipher = createDecipher; exports.createDecipheriv = exports.Decipheriv = createDecipheriv; exports.listCiphers = exports.getCiphers = getCiphers; /***/ }), /***/ 7729: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var CipherBase = __webpack_require__(8842); var des = __webpack_require__(167); var inherits = __webpack_require__(376); var Buffer = (__webpack_require__(9047).Buffer); var modes = { 'des-ede3-cbc': des.CBC.instantiate(des.EDE), 'des-ede3': des.EDE, 'des-ede-cbc': des.CBC.instantiate(des.EDE), 'des-ede': des.EDE, 'des-cbc': des.CBC.instantiate(des.DES), 'des-ecb': des.DES }; modes.des = modes['des-cbc']; modes.des3 = modes['des-ede3-cbc']; module.exports = DES; inherits(DES, CipherBase); function DES(opts) { CipherBase.call(this); var modeName = opts.mode.toLowerCase(); var mode = modes[modeName]; var type; if (opts.decrypt) { type = 'decrypt'; } else { type = 'encrypt'; } var key = opts.key; if (!Buffer.isBuffer(key)) { key = Buffer.from(key); } if (modeName === 'des-ede' || modeName === 'des-ede-cbc') { key = Buffer.concat([key, key.slice(0, 8)]); } var iv = opts.iv; if (!Buffer.isBuffer(iv)) { iv = Buffer.from(iv); } this._des = mode.create({ key: key, iv: iv, type: type }); } DES.prototype._update = function (data) { return Buffer.from(this._des.update(data)); }; DES.prototype._final = function () { return Buffer.from(this._des["final"]()); }; /***/ }), /***/ 3519: /***/ ((__unused_webpack_module, exports) => { exports["des-ecb"] = { key: 8, iv: 0 }; exports["des-cbc"] = exports.des = { key: 8, iv: 8 }; exports["des-ede3-cbc"] = exports.des3 = { key: 24, iv: 8 }; exports["des-ede3"] = { key: 24, iv: 0 }; exports["des-ede-cbc"] = { key: 16, iv: 8 }; exports["des-ede"] = { key: 16, iv: 0 }; /***/ }), /***/ 4364: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; var BN = __webpack_require__(6781); var randomBytes = __webpack_require__(5760); function blind(priv) { var r = getr(priv); var blinder = r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed(); return { blinder: blinder, unblinder: r.invm(priv.modulus) }; } function getr(priv) { var len = priv.modulus.byteLength(); var r; do { r = new BN(randomBytes(len)); } while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)); return r; } function crt(msg, priv) { var blinds = blind(priv); var len = priv.modulus.byteLength(); var blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus); var c1 = blinded.toRed(BN.mont(priv.prime1)); var c2 = blinded.toRed(BN.mont(priv.prime2)); var qinv = priv.coefficient; var p = priv.prime1; var q = priv.prime2; var m1 = c1.redPow(priv.exponent1).fromRed(); var m2 = c2.redPow(priv.exponent2).fromRed(); var h = m1.isub(m2).imul(qinv).umod(p).imul(q); return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer, 'be', len); } crt.getr = getr; module.exports = crt; /***/ }), /***/ 3363: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = __webpack_require__(5207); /***/ }), /***/ 1022: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var Buffer = (__webpack_require__(3173).Buffer); var createHash = __webpack_require__(8339); var stream = __webpack_require__(8237); var inherits = __webpack_require__(376); var sign = __webpack_require__(1437); var verify = __webpack_require__(1113); var algorithms = __webpack_require__(5207); Object.keys(algorithms).forEach(function (key) { algorithms[key].id = Buffer.from(algorithms[key].id, 'hex'); algorithms[key.toLowerCase()] = algorithms[key]; }); function Sign(algorithm) { stream.Writable.call(this); var data = algorithms[algorithm]; if (!data) throw new Error('Unknown message digest'); this._hashType = data.hash; this._hash = createHash(data.hash); this._tag = data.id; this._signType = data.sign; } inherits(Sign, stream.Writable); Sign.prototype._write = function _write(data, _, done) { this._hash.update(data); done(); }; Sign.prototype.update = function update(data, enc) { if (typeof data === 'string') data = Buffer.from(data, enc); this._hash.update(data); return this; }; Sign.prototype.sign = function signMethod(key, enc) { this.end(); var hash = this._hash.digest(); var sig = sign(hash, key, this._hashType, this._signType, this._tag); return enc ? sig.toString(enc) : sig; }; function Verify(algorithm) { stream.Writable.call(this); var data = algorithms[algorithm]; if (!data) throw new Error('Unknown message digest'); this._hash = createHash(data.hash); this._tag = data.id; this._signType = data.sign; } inherits(Verify, stream.Writable); Verify.prototype._write = function _write(data, _, done) { this._hash.update(data); done(); }; Verify.prototype.update = function update(data, enc) { if (typeof data === 'string') data = Buffer.from(data, enc); this._hash.update(data); return this; }; Verify.prototype.verify = function verifyMethod(key, sig, enc) { if (typeof sig === 'string') sig = Buffer.from(sig, enc); this.end(); var hash = this._hash.digest(); return verify(sig, hash, key, this._signType, this._tag); }; function createSign(algorithm) { return new Sign(algorithm); } function createVerify(algorithm) { return new Verify(algorithm); } module.exports = { Sign: createSign, Verify: createVerify, createSign: createSign, createVerify: createVerify }; /***/ }), /***/ 1437: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js var Buffer = (__webpack_require__(3173).Buffer); var createHmac = __webpack_require__(8736); var crt = __webpack_require__(4364); var EC = (__webpack_require__(8333).ec); var BN = __webpack_require__(6781); var parseKeys = __webpack_require__(2914); var curves = __webpack_require__(1308); function sign(hash, key, hashType, signType, tag) { var priv = parseKeys(key); if (priv.curve) { // rsa keys can be interpreted as ecdsa ones in openssl if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type'); return ecSign(hash, priv); } else if (priv.type === 'dsa') { if (signType !== 'dsa') throw new Error('wrong private key type'); return dsaSign(hash, priv, hashType); } else { if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type'); } hash = Buffer.concat([tag, hash]); var len = priv.modulus.byteLength(); var pad = [0, 1]; while (hash.length + pad.length + 1 < len) { pad.push(0xff); } pad.push(0x00); var i = -1; while (++i < hash.length) { pad.push(hash[i]); } var out = crt(pad, priv); return out; } function ecSign(hash, priv) { var curveId = curves[priv.curve.join('.')]; if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.')); var curve = new EC(curveId); var key = curve.keyFromPrivate(priv.privateKey); var out = key.sign(hash); return Buffer.from(out.toDER()); } function dsaSign(hash, priv, algo) { var x = priv.params.priv_key; var p = priv.params.p; var q = priv.params.q; var g = priv.params.g; var r = new BN(0); var k; var H = bits2int(hash, q).mod(q); var s = false; var kv = getKey(x, q, hash, algo); while (s === false) { k = makeKey(q, kv, algo); r = makeR(g, k, p, q); s = k.invm(q).imul(H.add(x.mul(r))).mod(q); if (s.cmpn(0) === 0) { s = false; r = new BN(0); } } return toDER(r, s); } function toDER(r, s) { r = r.toArray(); s = s.toArray(); // Pad values if (r[0] & 0x80) r = [0].concat(r); if (s[0] & 0x80) s = [0].concat(s); var total = r.length + s.length + 4; var res = [0x30, total, 0x02, r.length]; res = res.concat(r, [0x02, s.length], s); return Buffer.from(res); } function getKey(x, q, hash, algo) { x = Buffer.from(x.toArray()); if (x.length < q.byteLength()) { var zeros = Buffer.alloc(q.byteLength() - x.length); x = Buffer.concat([zeros, x]); } var hlen = hash.length; var hbits = bits2octets(hash, q); var v = Buffer.alloc(hlen); v.fill(1); var k = Buffer.alloc(hlen); k = createHmac(algo, k).update(v).update(Buffer.from([0])).update(x).update(hbits).digest(); v = createHmac(algo, k).update(v).digest(); k = createHmac(algo, k).update(v).update(Buffer.from([1])).update(x).update(hbits).digest(); v = createHmac(algo, k).update(v).digest(); return { k: k, v: v }; } function bits2int(obits, q) { var bits = new BN(obits); var shift = (obits.length << 3) - q.bitLength(); if (shift > 0) bits.ishrn(shift); return bits; } function bits2octets(bits, q) { bits = bits2int(bits, q); bits = bits.mod(q); var out = Buffer.from(bits.toArray()); if (out.length < q.byteLength()) { var zeros = Buffer.alloc(q.byteLength() - out.length); out = Buffer.concat([zeros, out]); } return out; } function makeKey(q, kv, algo) { var t; var k; do { t = Buffer.alloc(0); while (t.length * 8 < q.bitLength()) { kv.v = createHmac(algo, kv.k).update(kv.v).digest(); t = Buffer.concat([t, kv.v]); } k = bits2int(t, q); kv.k = createHmac(algo, kv.k).update(kv.v).update(Buffer.from([0])).digest(); kv.v = createHmac(algo, kv.k).update(kv.v).digest(); } while (k.cmp(q) !== -1); return k; } function makeR(g, k, p, q) { return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q); } module.exports = sign; module.exports.getKey = getKey; module.exports.makeKey = makeKey; /***/ }), /***/ 1113: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js var Buffer = (__webpack_require__(3173).Buffer); var BN = __webpack_require__(6781); var EC = (__webpack_require__(8333).ec); var parseKeys = __webpack_require__(2914); var curves = __webpack_require__(1308); function verify(sig, hash, key, signType, tag) { var pub = parseKeys(key); if (pub.type === 'ec') { // rsa keys can be interpreted as ecdsa ones in openssl if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type'); return ecVerify(sig, hash, pub); } else if (pub.type === 'dsa') { if (signType !== 'dsa') throw new Error('wrong public key type'); return dsaVerify(sig, hash, pub); } else { if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type'); } hash = Buffer.concat([tag, hash]); var len = pub.modulus.byteLength(); var pad = [1]; var padNum = 0; while (hash.length + pad.length + 2 < len) { pad.push(0xff); padNum++; } pad.push(0x00); var i = -1; while (++i < hash.length) { pad.push(hash[i]); } pad = Buffer.from(pad); var red = BN.mont(pub.modulus); sig = new BN(sig).toRed(red); sig = sig.redPow(new BN(pub.publicExponent)); sig = Buffer.from(sig.fromRed().toArray()); var out = padNum < 8 ? 1 : 0; len = Math.min(sig.length, pad.length); if (sig.length !== pad.length) out = 1; i = -1; while (++i < len) { out |= sig[i] ^ pad[i]; } return out === 0; } function ecVerify(sig, hash, pub) { var curveId = curves[pub.data.algorithm.curve.join('.')]; if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.')); var curve = new EC(curveId); var pubkey = pub.data.subjectPrivateKey.data; return curve.verify(hash, sig, pubkey); } function dsaVerify(sig, hash, pub) { var p = pub.data.p; var q = pub.data.q; var g = pub.data.g; var y = pub.data.pub_key; var unpacked = parseKeys.signature.decode(sig, 'der'); var s = unpacked.s; var r = unpacked.r; checkValue(s, q); checkValue(r, q); var montp = BN.mont(p); var w = s.invm(q); var v = g.toRed(montp).redPow(new BN(hash).mul(w).mod(q)).fromRed().mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()).mod(p).mod(q); return v.cmp(r) === 0; } function checkValue(b, q) { if (b.cmpn(0) <= 0) throw new Error('invalid sig'); if (b.cmp(q) >= q) throw new Error('invalid sig'); } module.exports = verify; /***/ }), /***/ 3173: /***/ ((module, exports, __webpack_require__) => { /*! safe-buffer. MIT License. Feross Aboukhadijeh */ /* eslint-disable node/no-deprecated-api */ var buffer = __webpack_require__(365); var Buffer = buffer.Buffer; // alternative to using Object.keys for old browsers function copyProps(src, dst) { for (var key in src) { dst[key] = src[key]; } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer; } else { // Copy properties from require('buffer') copyProps(buffer, exports); exports.Buffer = SafeBuffer; } function SafeBuffer(arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length); } SafeBuffer.prototype = Object.create(Buffer.prototype); // Copy static methods from Buffer copyProps(Buffer, SafeBuffer); SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number'); } return Buffer(arg, encodingOrOffset, length); }; SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number'); } var buf = Buffer(size); if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding); } else { buf.fill(fill); } } else { buf.fill(0); } return buf; }; SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number'); } return Buffer(size); }; SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number'); } return buffer.SlowBuffer(size); }; /***/ }), /***/ 3873: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "Decimal128": () => (/* binding */ _Decimal), /* harmony export */ "Kb": () => (/* binding */ _Binary), /* harmony export */ "t4": () => (/* binding */ _ObjectId) /* harmony export */ }); /* unused harmony exports BSONError, BSONRegExp, BSONSymbol, BSONTypeError, BSON_BINARY_SUBTYPE_BYTE_ARRAY, BSON_BINARY_SUBTYPE_COLUMN, BSON_BINARY_SUBTYPE_DEFAULT, BSON_BINARY_SUBTYPE_ENCRYPTED, BSON_BINARY_SUBTYPE_FUNCTION, BSON_BINARY_SUBTYPE_MD5, BSON_BINARY_SUBTYPE_USER_DEFINED, BSON_BINARY_SUBTYPE_UUID, BSON_BINARY_SUBTYPE_UUID_NEW, BSON_DATA_ARRAY, BSON_DATA_BINARY, BSON_DATA_BOOLEAN, BSON_DATA_CODE, BSON_DATA_CODE_W_SCOPE, BSON_DATA_DATE, BSON_DATA_DBPOINTER, BSON_DATA_DECIMAL128, BSON_DATA_INT, BSON_DATA_LONG, BSON_DATA_MAX_KEY, BSON_DATA_MIN_KEY, BSON_DATA_NULL, BSON_DATA_NUMBER, BSON_DATA_OBJECT, BSON_DATA_OID, BSON_DATA_REGEXP, BSON_DATA_STRING, BSON_DATA_SYMBOL, BSON_DATA_TIMESTAMP, BSON_DATA_UNDEFINED, BSON_INT32_MAX, BSON_INT32_MIN, BSON_INT64_MAX, BSON_INT64_MIN, Code, DBRef, Double, EJSON, Int32, Long, LongWithoutOverridesClass, Map, MaxKey, MinKey, ObjectId, Timestamp, UUID, calculateObjectSize, deserialize, deserializeStream, serialize, serializeWithBufferAndIndex, setInternalBufferSize */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var byteLength_1 = byteLength; var toByteArray_1 = toByteArray; var fromByteArray_1 = fromByteArray; var lookup = []; var revLookup = []; var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i]; revLookup[code.charCodeAt(i)] = i; } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62; revLookup['_'.charCodeAt(0)] = 63; function getLens(b64) { var len = b64.length; if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4'); } // Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen = b64.indexOf('='); if (validLen === -1) validLen = len; var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; return [validLen, placeHoldersLen]; } // base64 is 4/3 + up to two characters of the original data function byteLength(b64) { var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; } function _byteLength(b64, validLen, placeHoldersLen) { return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; } function toByteArray(b64) { var tmp; var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); var curByte = 0; // if there are placeholders, only get up to the last complete 4 chars var len = placeHoldersLen > 0 ? validLen - 4 : validLen; var i; for (i = 0; i < len; i += 4) { tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; arr[curByte++] = tmp >> 16 & 0xFF; arr[curByte++] = tmp >> 8 & 0xFF; arr[curByte++] = tmp & 0xFF; } if (placeHoldersLen === 2) { tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; arr[curByte++] = tmp & 0xFF; } if (placeHoldersLen === 1) { tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; arr[curByte++] = tmp >> 8 & 0xFF; arr[curByte++] = tmp & 0xFF; } return arr; } function tripletToBase64(num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; } function encodeChunk(uint8, start, end) { var tmp; var output = []; for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF); output.push(tripletToBase64(tmp)); } return output.join(''); } function fromByteArray(uint8) { var tmp; var len = uint8.length; var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes var parts = []; var maxChunkLength = 16383; // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1]; parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '=='); } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1]; parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + '='); } return parts.join(''); } var base64Js = { byteLength: byteLength_1, toByteArray: toByteArray_1, fromByteArray: fromByteArray_1 }; /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ var read = function read(buffer, offset, isLE, mLen, nBytes) { var e, m; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var nBits = -7; var i = isLE ? nBytes - 1 : 0; var d = isLE ? -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); }; var write = function write(buffer, value, offset, isLE, mLen, nBytes) { var e, m, c; 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 = isLE ? 0 : nBytes - 1; var d = isLE ? 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) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = e << mLen | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128; }; var ieee754 = { read: read, write: write }; var buffer$1 = createCommonjsModule(function (module, exports) { var customInspectSymbol = typeof Symbol === 'function' && typeof Symbol['for'] === 'function' ? // eslint-disable-line dot-notation Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation : null; exports.Buffer = Buffer; exports.SlowBuffer = SlowBuffer; exports.INSPECT_MAX_BYTES = 50; var K_MAX_LENGTH = 0x7fffffff; exports.kMaxLength = K_MAX_LENGTH; /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport(); if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') { console.error('This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'); } function typedArraySupport() { // Can typed array instances can be augmented? try { var arr = new Uint8Array(1); var proto = { foo: function foo() { return 42; } }; Object.setPrototypeOf(proto, Uint8Array.prototype); Object.setPrototypeOf(arr, proto); return arr.foo() === 42; } catch (e) { return false; } } Object.defineProperty(Buffer.prototype, 'parent', { enumerable: true, get: function get() { if (!Buffer.isBuffer(this)) return undefined; return this.buffer; } }); Object.defineProperty(Buffer.prototype, 'offset', { enumerable: true, get: function get() { if (!Buffer.isBuffer(this)) return undefined; return this.byteOffset; } }); function createBuffer(length) { if (length > K_MAX_LENGTH) { throw new RangeError('The value "' + length + '" is invalid for option "size"'); } // Return an augmented `Uint8Array` instance var buf = new Uint8Array(length); Object.setPrototypeOf(buf, Buffer.prototype); return buf; } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer(arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new TypeError('The "string" argument must be of type string. Received type number'); } return allocUnsafe(arg); } return from(arg, encodingOrOffset, length); } Buffer.poolSize = 8192; // not used by this implementation function from(value, encodingOrOffset, length) { if (typeof value === 'string') { return fromString(value, encodingOrOffset); } if (ArrayBuffer.isView(value)) { return fromArrayView(value); } if (value == null) { throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value)); } if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { return fromArrayBuffer(value, encodingOrOffset, length); } if (typeof SharedArrayBuffer !== 'undefined' && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { return fromArrayBuffer(value, encodingOrOffset, length); } if (typeof value === 'number') { throw new TypeError('The "value" argument must not be of type number. Received type number'); } var valueOf = value.valueOf && value.valueOf(); if (valueOf != null && valueOf !== value) { return Buffer.from(valueOf, encodingOrOffset, length); } var b = fromObject(value); if (b) return b; if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') { return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length); } throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value)); } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length); }; // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); Object.setPrototypeOf(Buffer, Uint8Array); function assertSize(size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be of type number'); } else if (size < 0) { throw new RangeError('The value "' + size + '" is invalid for option "size"'); } } function alloc(size, fill, encoding) { assertSize(size); if (size <= 0) { return createBuffer(size); } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpreted as a start offset. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); } return createBuffer(size); } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(size, fill, encoding); }; function allocUnsafe(size) { assertSize(size); return createBuffer(size < 0 ? 0 : checked(size) | 0); } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(size); }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(size); }; function fromString(string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8'; } if (!Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding); } var length = byteLength(string, encoding) | 0; var buf = createBuffer(length); var actual = buf.write(string, encoding); if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') buf = buf.slice(0, actual); } return buf; } function fromArrayLike(array) { var length = array.length < 0 ? 0 : checked(array.length) | 0; var buf = createBuffer(length); for (var i = 0; i < length; i += 1) { buf[i] = array[i] & 255; } return buf; } function fromArrayView(arrayView) { if (isInstance(arrayView, Uint8Array)) { var copy = new Uint8Array(arrayView); return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); } return fromArrayLike(arrayView); } function fromArrayBuffer(array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('"offset" is outside of buffer bounds'); } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('"length" is outside of buffer bounds'); } var buf; if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array); } else if (length === undefined) { buf = new Uint8Array(array, byteOffset); } else { buf = new Uint8Array(array, byteOffset, length); } // Return an augmented `Uint8Array` instance Object.setPrototypeOf(buf, Buffer.prototype); return buf; } function fromObject(obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0; var buf = createBuffer(len); if (buf.length === 0) { return buf; } obj.copy(buf, 0, 0, len); return buf; } if (obj.length !== undefined) { if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { return createBuffer(0); } return fromArrayLike(obj); } if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data); } } function checked(length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes'); } return length | 0; } function SlowBuffer(length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0; } return Buffer.alloc(+length); } Buffer.isBuffer = function isBuffer(b) { return b != null && b._isBuffer === true && b !== Buffer.prototype; // so Buffer.isBuffer(Buffer.prototype) will be false }; Buffer.compare = function compare(a, b) { if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength); if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength); if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'); } if (a === b) return 0; var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } } if (x < y) return -1; if (y < x) return 1; return 0; }; Buffer.isEncoding = function isEncoding(encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true; default: return false; } }; Buffer.concat = function concat(list, length) { if (!Array.isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers'); } if (list.length === 0) { return Buffer.alloc(0); } var i; if (length === undefined) { length = 0; for (i = 0; i < list.length; ++i) { length += list[i].length; } } var buffer = Buffer.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; if (isInstance(buf, Uint8Array)) { if (pos + buf.length > buffer.length) { Buffer.from(buf).copy(buffer, pos); } else { Uint8Array.prototype.set.call(buffer, buf, pos); } } else if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers'); } else { buf.copy(buffer, pos); } pos += buf.length; } return buffer; }; function byteLength(string, encoding) { if (Buffer.isBuffer(string)) { return string.length; } if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { return string.byteLength; } if (typeof string !== 'string') { throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + babelHelpers["typeof"](string)); } var len = string.length; var mustMatch = arguments.length > 2 && arguments[2] === true; if (!mustMatch && len === 0) return 0; // Use a for loop to avoid recursion var loweredCase = false; for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len; case 'utf8': case 'utf-8': return utf8ToBytes(string).length; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2; case 'hex': return len >>> 1; case 'base64': return base64ToBytes(string).length; default: if (loweredCase) { return mustMatch ? -1 : utf8ToBytes(string).length; // assume utf8 } encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } } Buffer.byteLength = byteLength; function slowToString(encoding, start, end) { var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0; } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return ''; } if (end === undefined || end > this.length) { end = this.length; } if (end <= 0) { return ''; } // Force coercion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0; start >>>= 0; if (end <= start) { return ''; } if (!encoding) encoding = 'utf8'; while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end); case 'utf8': case 'utf-8': return utf8Slice(this, start, end); case 'ascii': return asciiSlice(this, start, end); case 'latin1': case 'binary': return latin1Slice(this, start, end); case 'base64': return base64Slice(this, start, end); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end); default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); encoding = (encoding + '').toLowerCase(); loweredCase = true; } } } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) // to detect a Buffer instance. It's not possible to use `instanceof Buffer` // reliably in a browserify context because there could be multiple different // copies of the 'buffer' package in use. This method works even for Buffer // instances that were created from another copy of the `buffer` package. // See: https://github.com/feross/buffer/issues/154 Buffer.prototype._isBuffer = true; function swap(b, n, m) { var i = b[n]; b[n] = b[m]; b[m] = i; } Buffer.prototype.swap16 = function swap16() { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits'); } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1); } return this; }; Buffer.prototype.swap32 = function swap32() { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits'); } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3); swap(this, i + 1, i + 2); } return this; }; Buffer.prototype.swap64 = function swap64() { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits'); } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7); swap(this, i + 1, i + 6); swap(this, i + 2, i + 5); swap(this, i + 3, i + 4); } return this; }; Buffer.prototype.toString = function toString() { var length = this.length; if (length === 0) return ''; if (arguments.length === 0) return utf8Slice(this, 0, length); return slowToString.apply(this, arguments); }; Buffer.prototype.toLocaleString = Buffer.prototype.toString; Buffer.prototype.equals = function equals(b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer'); if (this === b) return true; return Buffer.compare(this, b) === 0; }; Buffer.prototype.inspect = function inspect() { var str = ''; var max = exports.INSPECT_MAX_BYTES; str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim(); if (this.length > max) str += ' ... '; return ''; }; if (customInspectSymbol) { Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect; } Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { if (isInstance(target, Uint8Array)) { target = Buffer.from(target, target.offset, target.byteLength); } if (!Buffer.isBuffer(target)) { throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + babelHelpers["typeof"](target)); } if (start === undefined) { start = 0; } if (end === undefined) { end = target ? target.length : 0; } if (thisStart === undefined) { thisStart = 0; } if (thisEnd === undefined) { thisEnd = this.length; } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index'); } if (thisStart >= thisEnd && start >= end) { return 0; } if (thisStart >= thisEnd) { return -1; } if (start >= end) { return 1; } start >>>= 0; end >>>= 0; thisStart >>>= 0; thisEnd >>>= 0; if (this === target) return 0; var x = thisEnd - thisStart; var y = end - start; var len = Math.min(x, y); var thisCopy = this.slice(thisStart, thisEnd); var targetCopy = target.slice(start, end); for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i]; y = targetCopy[i]; break; } } if (x < y) return -1; if (y < x) return 1; return 0; }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1; // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = 0; } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff; } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000; } byteOffset = +byteOffset; // Coerce to Number. if (numberIsNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : buffer.length - 1; } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset; if (byteOffset >= buffer.length) { if (dir) return -1;else byteOffset = buffer.length - 1; } else if (byteOffset < 0) { if (dir) byteOffset = 0;else return -1; } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1; } return arrayIndexOf(buffer, val, byteOffset, encoding, dir); } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] if (typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); } } return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); } throw new TypeError('val must be string, number or Buffer'); } function arrayIndexOf(arr, val, byteOffset, encoding, dir) { var indexSize = 1; var arrLength = arr.length; var valLength = val.length; if (encoding !== undefined) { encoding = String(encoding).toLowerCase(); if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1; } indexSize = 2; arrLength /= 2; valLength /= 2; byteOffset /= 2; } } function read(buf, i) { if (indexSize === 1) { return buf[i]; } else { return buf.readUInt16BE(i * indexSize); } } var i; if (dir) { var foundIndex = -1; for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i; if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; } else { if (foundIndex !== -1) i -= i - foundIndex; foundIndex = -1; } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; for (i = byteOffset; i >= 0; i--) { var found = true; for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false; break; } } if (found) return i; } } return -1; } Buffer.prototype.includes = function includes(val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1; }; Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true); }; Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false); }; function hexWrite(buf, string, offset, length) { offset = Number(offset) || 0; var remaining = buf.length - offset; if (!length) { length = remaining; } else { length = Number(length); if (length > remaining) { length = remaining; } } var strLen = string.length; if (length > strLen / 2) { length = strLen / 2; } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16); if (numberIsNaN(parsed)) return i; buf[offset + i] = parsed; } return i; } function utf8Write(buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); } function asciiWrite(buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length); } function base64Write(buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length); } function ucs2Write(buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); } Buffer.prototype.write = function write(string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; length = this.length; offset = 0; // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset; length = this.length; offset = 0; // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset >>> 0; if (isFinite(length)) { length = length >>> 0; if (encoding === undefined) encoding = 'utf8'; } else { encoding = length; length = undefined; } } else { throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported'); } var remaining = this.length - offset; if (length === undefined || length > remaining) length = remaining; if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds'); } if (!encoding) encoding = 'utf8'; var loweredCase = false; for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length); case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length); case 'ascii': case 'latin1': case 'binary': return asciiWrite(this, string, offset, length); case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length); default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } }; Buffer.prototype.toJSON = function toJSON() { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) }; }; function base64Slice(buf, start, end) { if (start === 0 && end === buf.length) { return base64Js.fromByteArray(buf); } else { return base64Js.fromByteArray(buf.slice(start, end)); } } function utf8Slice(buf, start, end) { end = Math.min(buf.length, end); var res = []; var i = start; while (i < end) { var firstByte = buf[i]; var codePoint = null; var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint; switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte; } break; case 2: secondByte = buf[i + 1]; if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; if (tempCodePoint > 0x7F) { codePoint = tempCodePoint; } } break; case 3: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint; } } break; case 4: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; fourthByte = buf[i + 3]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint; } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD; bytesPerSequence = 1; } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000; res.push(codePoint >>> 10 & 0x3FF | 0xD800); codePoint = 0xDC00 | codePoint & 0x3FF; } res.push(codePoint); i += bytesPerSequence; } return decodeCodePointsArray(res); } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000; function decodeCodePointsArray(codePoints) { var len = codePoints.length; if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints); // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = ''; var i = 0; while (i < len) { res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); } return res; } function asciiSlice(buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F); } return ret; } function latin1Slice(buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]); } return ret; } function hexSlice(buf, start, end) { var len = buf.length; if (!start || start < 0) start = 0; if (!end || end < 0 || end > len) end = len; var out = ''; for (var i = start; i < end; ++i) { out += hexSliceLookupTable[buf[i]]; } return out; } function utf16leSlice(buf, start, end) { var bytes = buf.slice(start, end); var res = ''; // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) for (var i = 0; i < bytes.length - 1; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); } return res; } Buffer.prototype.slice = function slice(start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; if (start < 0) { start += len; if (start < 0) start = 0; } else if (start > len) { start = len; } if (end < 0) { end += len; if (end < 0) end = 0; } else if (end > len) { end = len; } if (end < start) end = start; var newBuf = this.subarray(start, end); // Return an augmented `Uint8Array` instance Object.setPrototypeOf(newBuf, Buffer.prototype); return newBuf; }; /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset(offset, ext, length) { if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); } Buffer.prototype.readUintLE = Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } return val; }; Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) { checkOffset(offset, byteLength, this.length); } var val = this[offset + --byteLength]; var mul = 1; while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul; } return val; }; Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 1, this.length); return this[offset]; }; Buffer.prototype.readUint16LE = Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | this[offset + 1] << 8; }; Buffer.prototype.readUint16BE = Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] << 8 | this[offset + 1]; }; Buffer.prototype.readUint32LE = Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000; }; Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); }; Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var i = byteLength; var mul = 1; var val = this[offset + --i]; while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return this[offset]; return (0xff - this[offset] + 1) * -1; }; Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | this[offset + 1] << 8; return val & 0x8000 ? val | 0xFFFF0000 : val; }; Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | this[offset] << 8; return val & 0x8000 ? val | 0xFFFF0000 : val; }; Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; }; Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; }; Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ieee754.read(this, offset, true, 23, 4); }; Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ieee754.read(this, offset, false, 23, 4); }; Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 8, this.length); return ieee754.read(this, offset, true, 52, 8); }; Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 8, this.length); return ieee754.read(this, offset, false, 52, 8); }; function checkInt(buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); if (offset + ext > buf.length) throw new RangeError('Index out of range'); } Buffer.prototype.writeUintLE = Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var mul = 1; var i = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = value / mul & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var i = byteLength - 1; var mul = 1; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = value / mul & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); this[offset] = value & 0xff; return offset + 1; }; Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); this[offset] = value & 0xff; this[offset + 1] = value >>> 8; return offset + 2; }; Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); this[offset] = value >>> 8; this[offset + 1] = value & 0xff; return offset + 2; }; Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); this[offset + 3] = value >>> 24; this[offset + 2] = value >>> 16; this[offset + 1] = value >>> 8; this[offset] = value & 0xff; return offset + 4; }; Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 0xff; return offset + 4; }; Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = 0; var mul = 1; var sub = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1; } this[offset + i] = (value / mul >> 0) - sub & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = byteLength - 1; var mul = 1; var sub = 0; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1; } this[offset + i] = (value / mul >> 0) - sub & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); if (value < 0) value = 0xff + value + 1; this[offset] = value & 0xff; return offset + 1; }; Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); this[offset] = value & 0xff; this[offset + 1] = value >>> 8; return offset + 2; }; Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); this[offset] = value >>> 8; this[offset + 1] = value & 0xff; return offset + 2; }; Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); this[offset] = value & 0xff; this[offset + 1] = value >>> 8; this[offset + 2] = value >>> 16; this[offset + 3] = value >>> 24; return offset + 4; }; Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (value < 0) value = 0xffffffff + value + 1; this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 0xff; return offset + 4; }; function checkIEEE754(buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range'); if (offset < 0) throw new RangeError('Index out of range'); } function writeFloat(buf, value, offset, littleEndian, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { checkIEEE754(buf, value, offset, 4); } ieee754.write(buf, value, offset, littleEndian, 23, 4); return offset + 4; } Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert); }; Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert); }; function writeDouble(buf, value, offset, littleEndian, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { checkIEEE754(buf, value, offset, 8); } ieee754.write(buf, value, offset, littleEndian, 52, 8); return offset + 8; } Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert); }; Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert); }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy(target, targetStart, start, end) { if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer'); if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; if (!targetStart) targetStart = 0; if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done if (end === start) return 0; if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds'); } if (start < 0 || start >= this.length) throw new RangeError('Index out of range'); if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? if (end > this.length) end = this.length; if (target.length - targetStart < end - start) { end = target.length - targetStart + start; } var len = end - start; if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { // Use built-in when available, missing from IE11 this.copyWithin(targetStart, start, end); } else { Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart); } return len; }; // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill(val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start; start = 0; end = this.length; } else if (typeof end === 'string') { encoding = end; end = this.length; } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string'); } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding); } if (val.length === 1) { var code = val.charCodeAt(0); if (encoding === 'utf8' && code < 128 || encoding === 'latin1') { // Fast path: If `val` fits into a single byte, use that numeric value. val = code; } } } else if (typeof val === 'number') { val = val & 255; } else if (typeof val === 'boolean') { val = Number(val); } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index'); } if (end <= start) { return this; } start = start >>> 0; end = end === undefined ? this.length : end >>> 0; if (!val) val = 0; var i; if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val; } } else { var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding); var len = bytes.length; if (len === 0) { throw new TypeError('The value "' + val + '" is invalid for argument "value"'); } for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; } } return this; }; // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; function base64clean(str) { // Node takes equal signs as end of the Base64 encoding str = str.split('=')[0]; // Node strips out invalid characters like \n and \t from the string, base64-js does not str = str.trim().replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '='; } return str; } function utf8ToBytes(string, units) { units = units || Infinity; var codePoint; var length = string.length; var leadSurrogate = null; var bytes = []; for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i); // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue; } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue; } // valid lead leadSurrogate = codePoint; continue; } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); leadSurrogate = codePoint; continue; } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); } leadSurrogate = null; // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break; bytes.push(codePoint); } else if (codePoint < 0x800) { if ((units -= 2) < 0) break; bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break; bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break; bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); } else { throw new Error('Invalid code point'); } } return bytes; } function asciiToBytes(str) { var byteArray = []; for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF); } return byteArray; } function utf16leToBytes(str, units) { var c, hi, lo; var byteArray = []; for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break; c = str.charCodeAt(i); hi = c >> 8; lo = c % 256; byteArray.push(lo); byteArray.push(hi); } return byteArray; } function base64ToBytes(str) { return base64Js.toByteArray(base64clean(str)); } function blitBuffer(src, dst, offset, length) { for (var i = 0; i < length; ++i) { if (i + offset >= dst.length || i >= src.length) break; dst[i + offset] = src[i]; } return i; } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass // the `instanceof` check but they should be treated as of that type. // See: https://github.com/feross/buffer/issues/166 function isInstance(obj, type) { return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; } function numberIsNaN(obj) { // For IE11 support return obj !== obj; // eslint-disable-line no-self-compare } // Create lookup table for `toString('hex')` // See: https://github.com/feross/buffer/issues/219 var hexSliceLookupTable = function () { var alphabet = '0123456789abcdef'; var table = new Array(256); for (var i = 0; i < 16; ++i) { var i16 = i * 16; for (var j = 0; j < 16; ++j) { table[i16 + j] = alphabet[i] + alphabet[j]; } } return table; }(); }); var buffer_1 = buffer$1.Buffer; buffer$1.SlowBuffer; buffer$1.INSPECT_MAX_BYTES; buffer$1.kMaxLength; /*! ***************************************************************************** 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 extendStatics(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 _assign = function __assign() { _assign = Object.assign || function __assign(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); }; /** @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 get() { return 'BSONError'; }, enumerable: false, configurable: true }); return BSONError; }(Error); /** @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 get() { return 'BSONTypeError'; }, enumerable: false, configurable: true }); return BSONTypeError; }(TypeError); 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 === "undefined" ? "undefined" : _typeof(globalThis)) === 'object' && globalThis) || checkForMath((typeof window === "undefined" ? "undefined" : _typeof(window)) === 'object' && window) || checkForMath((typeof self === "undefined" ? "undefined" : _typeof(self)) === 'object' && self) || checkForMath((typeof __webpack_require__.g === "undefined" ? "undefined" : _typeof(__webpack_require__.g)) === 'object' && __webpack_require__.g) || Function('return this')(); } /** * 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 ('); } function isReactNative() { var g = 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.alloc(size); for (var i = 0; i < size; ++i) { result[i] = Math.floor(Math.random() * 256); } return result; }; var detectRandomBytes = function detectRandomBytes() { 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.alloc(size)); }; } } if (typeof __webpack_require__.g !== 'undefined' && __webpack_require__.g.crypto && __webpack_require__.g.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 __webpack_require__.g.crypto.getRandomValues(buffer_1.alloc(size)); }; } var requiredRandomBytes; try { // eslint-disable-next-line @typescript-eslint/no-var-requires requiredRandomBytes = (__webpack_require__(462)/* .randomBytes */ .O6); } catch (e) {// keep the fallback } // NOTE: in transpiled cases the above require might return null/undefined return requiredRandomBytes || insecureRandomBytes; }; var randomBytes = detectRandomBytes(); function isAnyArrayBuffer(value) { return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); } function isUint8Array(value) { return Object.prototype.toString.call(value) === '[object Uint8Array]'; } function isBigInt64Array(value) { return Object.prototype.toString.call(value) === '[object BigInt64Array]'; } function isBigUInt64Array(value) { return Object.prototype.toString.call(value) === '[object BigUint64Array]'; } function isRegExp(d) { return Object.prototype.toString.call(d) === '[object RegExp]'; } function isMap(d) { return Object.prototype.toString.call(d) === '[object Map]'; } // To ensure that 0.4 of node works correctly function isDate(d) { return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]'; } /** * @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; } 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; } /** * 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.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); } if (isAnyArrayBuffer(potentialBuffer)) { return buffer_1.from(potentialBuffer); } throw new BSONTypeError('Must use either Buffer or TypedArray'); } // 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 uuidValidateString(str) { return typeof str === 'string' && VALIDATION_REGEX.test(str); }; var uuidHexStringToBuffer = function uuidHexStringToBuffer(hexString) { if (!uuidValidateString(hexString)) { throw new 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.from(sanitizedHexString, 'hex'); }; var bufferToUuidHexString = function bufferToUuidHexString(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'); }; var BYTE_LENGTH = 16; var kId$1 = 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$1] = buffer_1.from(input.id); this.__id = input.__id; } else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) { this.id = ensureBuffer(input); } else if (typeof input === 'string') { this.id = uuidHexStringToBuffer(input); } else { throw new 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", { /** * The UUID bytes * @readonly */ get: function get() { return this[kId$1]; }, set: function set(value) { this[kId$1] = value; if (UUID.cacheHexString) { this.__id = 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 = 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(this.id, _Binary.SUBTYPE_UUID); }; /** * Generates a populated buffer containing a v4 uuid */ UUID.generate = function () { var bytes = 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.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 uuidValidateString(input); } if (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.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 = 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; }(); Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' }); /** * A class representation of the BSON Binary type. * @public * @category BSONType */ 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 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.alloc(Binary.BUFFER_SIZE); this.position = 0; } else { if (typeof buffer === 'string') { // string this.buffer = buffer_1.from(buffer, 'binary'); } else if (Array.isArray(buffer)) { // number[] this.buffer = buffer_1.from(buffer); } else { // Buffer | TypedArray | ArrayBuffer this.buffer = ensureBuffer(buffer); } this.position = this.buffer.byteLength; } } /** * 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 BSONTypeError('only accepts single character String'); } else if (typeof byteValue !== 'number' && byteValue.length !== 1) throw new BSONTypeError('only accepts single character Uint8Array or Array'); // Decode the byte value once var decodedByte; if (typeof byteValue === 'string') { decodedByte = byteValue.charCodeAt(0); } else if (typeof byteValue === 'number') { decodedByte = byteValue; } else { decodedByte = byteValue[0]; } if (decodedByte < 0 || decodedByte > 255) { throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255'); } if (this.buffer.length > this.position) { this.buffer[this.position++] = decodedByte; } else { var buffer = buffer_1.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; } }; /** * 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.alloc(this.buffer.length + sequence.length); this.buffer.copy(buffer, 0, 0, this.buffer.length); // Assign the new buffer this.buffer = buffer; } if (ArrayBuffer.isView(sequence)) { this.buffer.set(ensureBuffer(sequence), offset); this.position = offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; } 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; } }; /** * 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 it's a node.js buffer object if (asRaw) { return this.buffer.slice(0, this.position); } 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 }; } 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(this.buffer.slice(0, this.position)); } throw new 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.from(doc.$binary, 'base64'); } else { if (typeof doc.$binary !== 'string') { type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; data = buffer_1.from(doc.$binary.base64, 'base64'); } } } else if ('$uuid' in doc) { type = 4; data = uuidHexStringToBuffer(doc.$uuid); } if (!data) { throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc)); } 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; }(); Object.defineProperty(_Binary.prototype, '_bsontype', { value: 'Binary' }); /** * A class representation of the BSON Code type. * @public * @category BSONType */ 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; } 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; }(); Object.defineProperty(_Code.prototype, '_bsontype', { value: 'Code' }); /** @internal */ function isDBRefLike(value) { return isObjectLike(value) && value.$id != null && typeof value.$ref === 'string' && (value.$db == null || typeof value.$db === 'string'); } /** * A class representation of the BSON DBRef type. * @public * @category BSONType */ 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; 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 get() { return this.collection; }, set: function set(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 }; 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; }(); Object.defineProperty(_DBRef.prototype, '_bsontype', { value: 'DBRef' }); /** * 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 * @category BSONType * @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)); } else { this.low = low | 0; this.high = high | 0; this.unsigned = !!unsigned; } 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; } 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; } }; /** * 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; } 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; } else { unsigned = !!unsigned; } 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(); } // 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)); } } 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 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 = 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; c16 += a16 + b16; c32 += c16 >>> 16; c16 &= 0xffff; c32 += a32 + b32; c48 += c32 >>> 16; c32 &= 0xffff; c48 += a48 + b48; c48 &= 0xffff; return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32, 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; } 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; } // 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); } 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(); } 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 = 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; c16 += a16 * b00; c32 += c16 >>> 16; c16 &= 0xffff; c16 += a00 * b16; c32 += c16 >>> 16; c16 &= 0xffff; c32 += a32 * b00; c48 += c32 >>> 16; c32 &= 0xffff; c32 += a16 * b16; c48 += c32 >>> 16; c32 &= 0xffff; c32 += a00 * b32; c48 += c32 >>> 16; c32 &= 0xffff; c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; c48 &= 0xffff; return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32, 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 (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()) { // 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 (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), 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; }(); Object.defineProperty(_Long.prototype, '__isLong__', { value: true }); Object.defineProperty(_Long.prototype, '_bsontype', { value: 'Long' }); 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.fromNumber(1000 * 1000 * 1000); var _rem = _Long.fromNumber(0); if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { return { quotient: value, rem: _rem }; } 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(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.fromNumber(0), low: _Long.fromNumber(0) }; } var leftHigh = left.shiftRightUnsigned(32); var leftLow = new _Long(left.getLowBits(), 0); var rightHigh = right.shiftRightUnsigned(32); var rightLow = new _Long(right.getLowBits(), 0); var productHigh = leftHigh.multiply(rightHigh); var productMid = leftHigh.multiply(rightLow); var productMid2 = leftLow.multiply(rightHigh); var productLow = leftLow.multiply(rightLow); productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); productMid = new _Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32)); productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); productLow = productMid.shiftLeft(32).add(new _Long(productLow.getLowBits(), 0)); // Return the 128 bit result return { high: productHigh, low: productLow }; } 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 BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message); } /** * A class representation of the BSON Decimal128 type. * @public * @category BSONType */ var _Decimal = /** @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; } else if (isUint8Array(bytes)) { if (bytes.byteLength !== 16) { throw new BSONTypeError('Decimal128 must take a Buffer of 16 bytes'); } this.bytes = bytes; } else { throw new BSONTypeError('Decimal128 must take a Buffer or 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 var nDigitsRead = 0; // Total number of digits (no leading zeros) var nDigits = 0; // The number of the digits after radix var radixPosition = 0; // The index of the first non-zero in *str* var firstNonZero = 0; // Digits Array var digits = [0]; // The number of digits in digits var nDigitsStored = 0; // Insertion pointer for digits var digitsInsert = 0; // The index of the first non-zero digit var firstDigit = 0; // The index of the last digit var lastDigit = 0; // Exponent var exponent = 0; // loop index over array var i = 0; // The high 17 digits of the significand var significandHigh = new _Long(0, 0); // The low 17 digits of the significand var significandLow = new _Long(0, 0); // The biased exponent var biasedExponent = 0; // Read index var index = 0; // Naively prevent against REDOS attacks. // TODO: implementing a custom parsing for this, or refactoring the regex would yield // further gains. if (representation.length >= 7000) { throw new BSONTypeError('' + representation + ' not a valid Decimal128 string'); } // Results 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 || representation.length === 0) { throw new 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 (representation[index] === '+' || representation[index] === '-') { isNegative = representation[index++] === '-'; } // Check if user passed Infinity or NaN if (!isDigit(representation[index]) && representation[index] !== '.') { if (representation[index] === 'i' || representation[index] === 'I') { return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); } else if (representation[index] === 'N') { return new Decimal128(buffer_1.from(NAN_BUFFER)); } } // Read all the digits while (isDigit(representation[index]) || representation[index] === '.') { if (representation[index] === '.') { if (sawRadix) invalidErr(representation, 'contains multiple periods'); sawRadix = true; index = index + 1; continue; } 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 BSONTypeError('' + representation + ' not a valid Decimal128 string'); // Read exponent if exists 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.from(NAN_BUFFER)); // Get exponent exponent = parseInt(match[0], 10); // Adjust the index index = index + match[0].length; } // Return not a number if (representation[index]) return new Decimal128(buffer_1.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 (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; } // 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; } invalidErr(representation, 'overflow'); } exponent = exponent - 1; } while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { // 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) { 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(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); } } } } } } // Encode significand // The high 17 digits of the significand significandHigh = _Long.fromNumber(0); // The low 17 digits of the significand significandLow = _Long.fromNumber(0); // read a zero if (significantDigits === 0) { significandHigh = _Long.fromNumber(0); significandLow = _Long.fromNumber(0); } else if (lastDigit - firstDigit < 17) { var 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 { var dIdx = firstDigit; significandHigh = _Long.fromNumber(digits[dIdx++]); for (; dIdx <= lastDigit - 17; dIdx++) { significandHigh = significandHigh.multiply(_Long.fromNumber(10)); significandHigh = significandHigh.add(_Long.fromNumber(digits[dIdx])); } significandLow = _Long.fromNumber(digits[dIdx++]); for (; dIdx <= lastDigit; dIdx++) { significandLow = significandLow.multiply(_Long.fromNumber(10)); significandLow = significandLow.add(_Long.fromNumber(digits[dIdx])); } } var significand = multiply64x2(significandHigh, _Long.fromString('100000000000000000')); significand.low = significand.low.add(significandLow); if (lessThan(significand.low, significandLow)) { significand.high = significand.high.add(_Long.fromNumber(1)); } // Biased exponent biasedExponent = exponent + EXPONENT_BIAS; var dec = { low: _Long.fromNumber(0), high: _Long.fromNumber(0) }; // Encode combination, exponent, and significand. if (significand.high.shiftRightUnsigned(49).and(_Long.fromNumber(1)).equals(_Long.fromNumber(1))) { // Encode '11' into bits 1 to 3 dec.high = dec.high.or(_Long.fromNumber(0x3).shiftLeft(61)); dec.high = dec.high.or(_Long.fromNumber(biasedExponent).and(_Long.fromNumber(0x3fff).shiftLeft(47))); dec.high = dec.high.or(significand.high.and(_Long.fromNumber(0x7fffffffffff))); } else { dec.high = dec.high.or(_Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); dec.high = dec.high.or(significand.high.and(_Long.fromNumber(0x1ffffffffffff))); } dec.low = significand.low; // Encode sign if (isNegative) { dec.high = dec.high.or(_Long.fromString('9223372036854775808')); } // Encode into a buffer var buffer = buffer_1.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; // Encode high bits buffer[index++] = dec.low.high & 0xff; buffer[index++] = dec.low.high >> 8 & 0xff; buffer[index++] = dec.low.high >> 16 & 0xff; buffer[index++] = dec.low.high >> 24 & 0xff; // Encode the high 64 bits of the decimal // Encode low bits buffer[index++] = dec.high.low & 0xff; buffer[index++] = dec.high.low >> 8 & 0xff; buffer[index++] = dec.high.low >> 16 & 0xff; buffer[index++] = dec.high.low >> 24 & 0xff; // Encode high bits buffer[index++] = dec.high.high & 0xff; buffer[index++] = dec.high.high >> 8 & 0xff; buffer[index++] = dec.high.high >> 16 & 0xff; buffer[index++] = dec.high.high >> 24 & 0xff; // Return the new Decimal128 return new Decimal128(buffer); }; /** 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. // decoded biased exponent (14 bits) var biased_exponent; // the number of significand digits var significand_digits = 0; // the base-10 digits in the significand var significand = new Array(36); for (var i = 0; i < significand.length; i++) { significand[i] = 0; } // read pointer into significand var index = 0; // true if the number is zero var is_zero = false; // the most significant significand bits (50-46) var significand_msb; // temporary storage for significand decoding var significand128 = { parts: [0, 0, 0, 0] }; // indexing variables var j, k; // Output string var string = []; // Unpack index index = 0; // Buffer reference var buffer = this.bytes; // Unpack the low 64bits into a long // 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 // 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) }; if (dec.high.lessThan(_Long.ZERO)) { string.push('-'); } // Decode combination field and exponent // 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; } // 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[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; // 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; 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. // // We must check exponent > 0, because if this is the case, the number // has trailing zeros. However, we *cannot* output these trailing zeros, // because doing so would change the precision of the value, and would // change stored data if the string converted number is round tripped. if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { // Scientific format // 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('.'); } for (var 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 (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; }(); Object.defineProperty(_Decimal.prototype, '_bsontype', { value: 'Decimal128' }); /** * A class representation of the BSON Double type. * @public * @category BSONType */ 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; }; Double.prototype.toJSON = function () { return this.value; }; 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; } // 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; }(); Object.defineProperty(_Double.prototype, '_bsontype', { value: 'Double' }); /** * A class representation of a BSON Int32 type. * @public * @category BSONType */ var _Int = /** @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; }; Int32.prototype.toString = function (radix) { return this.value.toString(radix); }; Int32.prototype.toJSON = function () { return this.value; }; /** @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; }(); Object.defineProperty(_Int.prototype, '_bsontype', { value: 'Int32' }); /** * A class representation of the BSON MaxKey type. * @public * @category BSONType */ 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; }(); Object.defineProperty(_MaxKey.prototype, '_bsontype', { value: 'MaxKey' }); /** * A class representation of the BSON MinKey type. * @public * @category BSONType */ 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; }(); Object.defineProperty(_MinKey.prototype, '_bsontype', { value: 'MinKey' }); // 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 * @category BSONType */ 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 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.from(inputId.toHexString(), 'hex'); } else { workingId = inputId.id; } } 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) { // If intstanceof matches we can escape calling ensure buffer in Node.js environments this[kId] = workingId instanceof buffer_1 ? workingId : ensureBuffer(workingId); } else if (typeof workingId === 'string') { if (workingId.length === 12) { var bytes = buffer_1.from(workingId); if (bytes.byteLength === 12) { this[kId] = bytes; } else { throw new BSONTypeError('Argument passed in must be a string of 12 bytes'); } } else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { this[kId] = buffer_1.from(workingId, 'hex'); } else { throw new BSONTypeError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer'); } } else { throw new BSONTypeError('Argument passed in does not match the accepted types'); } // If we are caching the hex string if (ObjectId.cacheHexString) { this.__id = this.id.toString('hex'); } } Object.defineProperty(ObjectId.prototype, "id", { /** * The ObjectId bytes * @readonly */ get: function get() { return this[kId]; }, set: function set(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 get() { return this.id.readInt32BE(0); }, set: function set(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; } var hexString = this.id.toString('hex'); if (ObjectId.cacheHexString && !this.__id) { this.__id = hexString; } return hexString; }; /** * 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.alloc(12); // 4-byte timestamp buffer.writeUInt32BE(time, 0); // set PROCESS_UNIQUE if yet not initialized if (PROCESS_UNIQUE === null) { PROCESS_UNIQUE = 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 buffer; }; /** * 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 (format) return this.id.toString(format); return this.toHexString(); }; /** 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`. * * @param otherId - ObjectId instance to compare against. */ ObjectId.prototype.equals = function (otherId) { if (otherId === undefined || otherId === null) { return false; } if (otherId instanceof ObjectId) { return this[kId][11] === otherId[kId][11] && this[kId].equals(otherId[kId]); } if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12 && isUint8Array(this.id)) { return otherId === buffer_1.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.from(otherId).equals(this.id); } if (_typeof(otherId) === 'object' && 'toHexString' in otherId && typeof otherId.toHexString === 'function') { var otherIdString = otherId.toHexString(); var thisIdString = this.toHexString().toLowerCase(); return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString; } 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.readUInt32BE(0); timestamp.setTime(Math.floor(time) * 1000); return timestamp; }; /** @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.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // Encode time into first 4 bytes buffer.writeUInt32BE(time, 0); // Return the new objectId 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 hexString === 'undefined' || hexString != null && hexString.length !== 24) { throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); } return new ObjectId(buffer_1.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; try { new ObjectId(id); return true; } catch (_a) { return false; } }; /** @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; }(); // Deprecated methods Object.defineProperty(_ObjectId.prototype, 'generate', { value: deprecate(function (time) { return _ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead') }); Object.defineProperty(_ObjectId.prototype, 'getInc', { value: deprecate(function () { return _ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') }); Object.defineProperty(_ObjectId.prototype, 'get_inc', { value: deprecate(function () { return _ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') }); Object.defineProperty(_ObjectId, 'get_inc', { value: deprecate(function () { return _ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead') }); Object.defineProperty(_ObjectId.prototype, '_bsontype', { value: 'ObjectID' }); function alphabetize(str) { return str.split('').sort().join(''); } /** * A class representation of the BSON RegExp type. * @public * @category BSONType */ 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 BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern)); } if (this.options.indexOf('\x00') !== -1) { throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.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 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 BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc)); }; return BSONRegExp; }(); Object.defineProperty(_BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); /** * A class representation of the BSON Symbol type. * @public * @category BSONType */ 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; }; BSONSymbol.prototype.toString = function () { return this.value; }; /** @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; }(); Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); /** @public */ var LongWithoutOverridesClass = _Long; /** * @public * @category BSONType * */ 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.isLong(low)) { _this = _super.call(this, low.low, low.high, true) || this; } else if (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.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.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.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.MAX_UNSIGNED_VALUE; return Timestamp; }(LongWithoutOverridesClass); function isBSONType(value) { return isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string'; } // INT32 boundaries var BSON_INT32_MAX$1 = 0x7fffffff; var BSON_INT32_MIN$1 = -0x80000000; // INT64 boundaries var BSON_INT64_MAX$1 = 0x7fffffffffffffff; var BSON_INT64_MIN$1 = -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, $binary: _Binary, $uuid: _Binary, $symbol: BSONSymbol, $numberInt: _Int, $numberDecimal: _Decimal, $numberDouble: _Double, $numberLong: _Long, $minKey: _MinKey, $maxKey: _MaxKey, $regex: _BSONRegExp, $regularExpression: _BSONRegExp, $timestamp: _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$1 && value <= BSON_INT32_MAX$1) return new _Int(value); if (value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1) return _Long.fromNumber(value); } // If the number is a non-integer or out of integer range, should interpret as BSON Double. return new _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.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.fromExtendedJSON(value); } if (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 _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 _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 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 || 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$1 && value <= BSON_INT32_MAX$1, int64Range = value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1; // 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 || isRegExp(value)) { var flags = value.flags; if (flags === undefined) { var match = value.toString().match(/[gimuy]*$/); if (match) { flags = match[0]; } } var rx = new _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 Binary(o) { return new _Binary(o.value(), o.sub_type); }, Code: function Code(o) { return new _Code(o.code, o.scope); }, DBRef: function DBRef(o) { return new _DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); }, Decimal128: function Decimal128(o) { return new _Decimal(o.bytes); }, Double: function Double(o) { return new _Double(o.value); }, Int32: function Int32(o) { return new _Int(o.value); }, Long: function Long(o) { return _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 MaxKey() { return new _MaxKey(); }, MinKey: function MinKey() { return new _MinKey(); }, ObjectID: function ObjectID(o) { return new _ObjectId(o); }, ObjectId: function ObjectId(o) { return new _ObjectId(o); }, BSONRegExp: function BSONRegExp(o) { return new _BSONRegExp(o.pattern, o.options); }, Symbol: function Symbol(o) { return new BSONSymbol(o.value); }, Timestamp: function Timestamp(o) { return _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 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 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(outDoc.code, serializeValue(outDoc.scope, options)); } else if (bsontype === 'DBRef' && outDoc.oid) { outDoc = new _DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); } return outDoc.toExtendedJSON(options); } else { throw new 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 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 || (EJSON = {})); /* eslint-disable @typescript-eslint/no-explicit-any */ /** @public */ var bsonMap; var bsonGlobal = getGlobal(); if (bsonGlobal.Map) { bsonMap = bsonGlobal.Map; } else { // We will return a polyfill 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 }; } } Map.prototype.clear = function () { this._keys = []; this._values = {}; }; Map.prototype["delete"] = function (key) { var value = this._values[key]; if (value == null) return false; // Delete entry delete this._values[key]; // Remove the key from the ordered keys list this._keys.splice(value.i, 1); return true; }; Map.prototype.entries = function () { var _this = this; var index = 0; return { next: function next() { 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); } }; Map.prototype.get = function (key) { return this._values[key] ? this._values[key].v : undefined; }; Map.prototype.has = function (key) { return this._values[key] != null; }; Map.prototype.keys = function () { var _this = this; var index = 0; return { next: function next() { 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; 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 _this = this; var index = 0; return { next: function next() { 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 get() { return this._keys.length; }, enumerable: false, configurable: true }); return Map; }(); } /** @internal */ var BSON_INT32_MAX = 0x7fffffff; /** @internal */ var BSON_INT32_MIN = -0x80000000; /** @internal */ var BSON_INT64_MAX = Math.pow(2, 63) - 1; /** @internal */ var BSON_INT64_MIN = -Math.pow(2, 63); /** * Any integer up to 2^53 can be precisely represented by a double. * @internal */ var JS_INT_MAX = Math.pow(2, 53); /** * Any integer down to -2^53 can be precisely represented by a double. * @internal */ var JS_INT_MIN = -Math.pow(2, 53); /** Number BSON Type @internal */ var BSON_DATA_NUMBER = 1; /** String BSON Type @internal */ var BSON_DATA_STRING = 2; /** Object BSON Type @internal */ var BSON_DATA_OBJECT = 3; /** Array BSON Type @internal */ var BSON_DATA_ARRAY = 4; /** Binary BSON Type @internal */ var BSON_DATA_BINARY = 5; /** Binary BSON Type @internal */ var BSON_DATA_UNDEFINED = 6; /** ObjectId BSON Type @internal */ var BSON_DATA_OID = 7; /** Boolean BSON Type @internal */ var BSON_DATA_BOOLEAN = 8; /** Date BSON Type @internal */ var BSON_DATA_DATE = 9; /** null BSON Type @internal */ var BSON_DATA_NULL = 10; /** RegExp BSON Type @internal */ var BSON_DATA_REGEXP = 11; /** Code BSON Type @internal */ var BSON_DATA_DBPOINTER = 12; /** Code BSON Type @internal */ var BSON_DATA_CODE = 13; /** Symbol BSON Type @internal */ var BSON_DATA_SYMBOL = 14; /** Code with Scope BSON Type @internal */ var BSON_DATA_CODE_W_SCOPE = 15; /** 32 bit Integer BSON Type @internal */ var BSON_DATA_INT = 16; /** Timestamp BSON Type @internal */ var BSON_DATA_TIMESTAMP = 17; /** Long BSON Type @internal */ var BSON_DATA_LONG = 18; /** Decimal128 BSON Type @internal */ var BSON_DATA_DECIMAL128 = 19; /** MinKey BSON Type @internal */ var BSON_DATA_MIN_KEY = 0xff; /** MaxKey BSON Type @internal */ var BSON_DATA_MAX_KEY = 0x7f; /** Binary Default Type @internal */ var BSON_BINARY_SUBTYPE_DEFAULT = 0; /** Binary Function Type @internal */ var BSON_BINARY_SUBTYPE_FUNCTION = 1; /** Binary Byte Array Type @internal */ var BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; /** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */ var BSON_BINARY_SUBTYPE_UUID = 3; /** Binary UUID Type @internal */ var BSON_BINARY_SUBTYPE_UUID_NEW = 4; /** Binary MD5 Type @internal */ var BSON_BINARY_SUBTYPE_MD5 = 5; /** Encrypted BSON type @internal */ var BSON_BINARY_SUBTYPE_ENCRYPTED = 6; /** Column BSON type @internal */ var BSON_BINARY_SUBTYPE_COLUMN = 7; /** Binary User Defined Type @internal */ var BSON_BINARY_SUBTYPE_USER_DEFINED = 128; function calculateObjectSize$1(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 (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') { object = object.toBSON(); } // Calculate size for (var key in object) { totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); } } return totalLength; } /** @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 (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') { value = value.toBSON(); } switch (_typeof(value)) { case 'string': return 1 + buffer_1.byteLength(name, 'utf8') + 1 + 4 + buffer_1.byteLength(value, 'utf8') + 1; case 'number': if (Math.floor(value) === value && value >= JS_INT_MIN && value <= JS_INT_MAX) { if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { // 32 bit return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); } else { return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); } } else { // 64 bit return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); } case 'undefined': if (isArray || !ignoreUndefined) return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1; return 0; case 'boolean': return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); case 'object': if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1; } else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') { return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); } else if (value instanceof Date || isDate(value)) { return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); } else if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || isAnyArrayBuffer(value)) { return (name != null ? buffer_1.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.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); } else if (value['_bsontype'] === 'Decimal128') { return (name != null ? buffer_1.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.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + buffer_1.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined); } else { return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + buffer_1.byteLength(value.code.toString(), 'utf8') + 1; } } else if (value['_bsontype'] === 'Binary') { // Check what kind of subtype we have if (value.sub_type === _Binary.SUBTYPE_BYTE_ARRAY) { return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4); } else { return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1); } } else if (value['_bsontype'] === 'Symbol') { return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + buffer_1.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.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize$1(ordered_values, serializeFunctions, ignoreUndefined); } else if (value instanceof RegExp || isRegExp(value)) { return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1 + buffer_1.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.byteLength(name, 'utf8') + 1 : 0) + 1 + buffer_1.byteLength(value.pattern, 'utf8') + 1 + buffer_1.byteLength(value.options, 'utf8') + 1; } else { return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize$1(value, serializeFunctions, ignoreUndefined) + 1; } case 'function': // WTF for 0.4.X where typeof /someregexp/ === 'function' if (value instanceof RegExp || isRegExp(value) || String.call(value) === '[object RegExp]') { return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1 + buffer_1.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.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + buffer_1.byteLength(normalizedFunctionString(value), 'utf8') + 1 + calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined); } else if (serializeFunctions) { return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + buffer_1.byteLength(normalizedFunctionString(value), 'utf8') + 1; } } } return 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; } // Internal long versions var JS_INT_MAX_LONG = _Long.fromNumber(JS_INT_MAX); var JS_INT_MIN_LONG = _Long.fromNumber(JS_INT_MIN); var functionCache = {}; function deserialize$1(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 BSONError("bson size must be >= 5, is " + size); } if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size); } if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { throw new BSONError("buffer length " + buffer.length + " must === bson size " + size); } if (size + index > buffer.byteLength) { throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")"); } // Illegal end value if (buffer[index + size - 1] !== 0) { throw new 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); } 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 BSONError('UTF-8 validation setting cannot be empty'); } if (typeof utf8ValidationValues[0] !== 'boolean') { throw new 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 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 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 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.byteLength) throw new 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 === 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 BSONError('bad string length in bson'); } value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); index = index + stringSize; } else if (elementType === BSON_DATA_OID) { var oid = buffer_1.alloc(12); buffer.copy(oid, 0, index, index + 12); value = new _ObjectId(oid); index = index + 12; } else if (elementType === BSON_DATA_INT && promoteValues === false) { value = new _Int(buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24); } else if (elementType === BSON_DATA_INT) { value = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; } else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { value = new _Double(buffer.readDoubleLE(index)); index = index + 8; } else if (elementType === BSON_DATA_NUMBER) { value = buffer.readDoubleLE(index); index = index + 8; } else if (elementType === 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(lowBits, highBits).toNumber()); } else if (elementType === BSON_DATA_BOOLEAN) { if (buffer[index] !== 0 && buffer[index] !== 1) throw new BSONError('illegal boolean type value'); value = buffer[index++] === 1; } else if (elementType === BSON_DATA_OBJECT) { var _index = index; var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; if (objectSize <= 0 || objectSize > buffer.length - index) throw new BSONError('bad embedded document length in bson'); // We have a raw value if (raw) { 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_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; } 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 BSONError('invalid array terminator byte'); if (index !== stopIndex) throw new BSONError('corrupted array bson'); } else if (elementType === BSON_DATA_UNDEFINED) { value = undefined; } else if (elementType === BSON_DATA_NULL) { value = null; } else if (elementType === BSON_DATA_LONG) { // Unpack the low and high bits 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(lowBits, highBits); // Promote the long if possible if (promoteLongs && promoteValues === true) { value = _long.lessThanOrEqual(JS_INT_MAX_LONG) && _long.greaterThanOrEqual(JS_INT_MIN_LONG) ? _long.toNumber() : _long; } else { value = _long; } } else if (elementType === BSON_DATA_DECIMAL128) { // Buffer to contain the decimal bytes var bytes = buffer_1.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 _Decimal(bytes); // If we have an alternative mapper use that if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') { value = decimal128.toObject(); } else { value = decimal128; } } else if (elementType === 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 BSONError('Negative binary type element size found'); // Is the length longer than the document if (binarySize > buffer.byteLength) throw new 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 BSONError('Negative binary type element size found for subtype 0x02'); if (binarySize > totalBinarySize - 4) throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); if (binarySize < totalBinarySize - 4) throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); } if (promoteBuffers && promoteValues) { value = buffer.slice(index, index + binarySize); } else { value = new _Binary(buffer.slice(index, index + binarySize), subType); } } else { var _buffer = buffer_1.alloc(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 BSONError('Negative binary type element size found for subtype 0x02'); if (binarySize > totalBinarySize - 4) throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); if (binarySize < totalBinarySize - 4) throw new 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(_buffer, subType); } } // Update the index index = index + binarySize; } else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { // Get the start search index i = index; // Locate the end of the c string while (buffer[i] !== 0x00 && i < buffer.length) { i++; } // If are at the end of the buffer there is a problem with the document if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); // Return the C string var source = buffer.toString('utf8', index, i); // Create the regexp index = i + 1; // Get the start search index i = index; // Locate the end of the c string while (buffer[i] !== 0x00 && i < buffer.length) { i++; } // If are at the end of the buffer there is a problem with the document if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); // Return the C string var regExpOptions = buffer.toString('utf8', index, i); index = i + 1; // For each option add the corresponding one for javascript var optionsArray = new Array(regExpOptions.length); // Parse options for (i = 0; i < regExpOptions.length; i++) { switch (regExpOptions[i]) { case 'm': optionsArray[i] = 'm'; break; case 's': optionsArray[i] = 'g'; break; case 'i': optionsArray[i] = 'i'; break; } } value = new RegExp(source, optionsArray.join('')); } else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { // Get the start search index i = index; // Locate the end of the c string while (buffer[i] !== 0x00 && i < buffer.length) { i++; } // If are at the end of the buffer there is a problem with the document if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); // Return the C string 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++; } // If are at the end of the buffer there is a problem with the document if (i >= buffer.length) throw new BSONError('Bad BSON Document: illegal CString'); // Return the C string var regExpOptions = buffer.toString('utf8', index, i); index = i + 1; // Set the object value = new _BSONRegExp(source, regExpOptions); } else if (elementType === 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 BSONError('bad string length in bson'); } var symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); value = promoteValues ? symbol : new BSONSymbol(symbol); index = index + stringSize; } else if (elementType === 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(lowBits, highBits); } else if (elementType === BSON_DATA_MIN_KEY) { value = new _MinKey(); } else if (elementType === BSON_DATA_MAX_KEY) { value = new _MaxKey(); } else if (elementType === 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 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) { // 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(functionString); } // Update parse index position index = index + stringSize; } else if (elementType === 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 BSONError('code_w_scope total size shorter minimum expected length'); } // Get the code string size 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 BSONError('bad string length in bson'); } // Javascript function var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); // Update parse index position index = index + stringSize; // Parse the element var _index = index; // Decode the size of the object document 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 too short if (totalSize < 4 + 4 + objectSize + stringSize) { throw new BSONError('code_w_scope total size is too short, truncating scope'); } // Check if totalSize field is too long if (totalSize > 4 + 4 + objectSize + stringSize) { throw new 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) { // 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(functionString, scopeObject); } } else if (elementType === BSON_DATA_DBPOINTER) { // Get the code string size 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 BSONError('bad string length in bson'); // Namespace if (validation != null && validation.utf8) { if (!validateUtf8(buffer, index, index + stringSize - 1)) { throw new 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 = buffer_1.alloc(12); buffer.copy(oidBuffer, 0, index, index + 12); var oid = new _ObjectId(oidBuffer); // Update the index index = index + 12; // Upgrade to DBRef type value = new _DBRef(namespace, oid); } else { throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"'); } 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 BSONError('corrupt array bson'); throw new 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; if (isDBRefLike(object)) { var copy = Object.assign({}, object); delete copy.$ref; delete copy.$id; delete copy.$db; return new _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 (!validateUtf8(buffer, start, end)) { throw new BSONError('Invalid UTF-8 string in BSON document'); } break; } } } return value; } // Copyright (c) 2008, Fair Oaks Labs, Inc. 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) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } 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; } 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++] = 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 >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { // If the value fits in 32 bits encode as int32 // Set int type 32 bits or less buffer[index++] = 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; } else { // Encode as double buffer[index++] = 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 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++] = 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++] = 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++] = 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.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++] = 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++] = 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++] = BSON_DATA_NULL; } else if (value._bsontype === 'MinKey') { buffer[index++] = BSON_DATA_MIN_KEY; } else { buffer[index++] = 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++] = 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 (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 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++] = 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++] = BSON_BINARY_SUBTYPE_DEFAULT; // Copy the content form the binary field to the buffer buffer.set(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 BSONError('cyclic dependency detected'); } // Push value to stack path.push(value); // Write the type buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : 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++] = 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' ? BSON_DATA_LONG : 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++] = 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++] = 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 writeIEEE754(buffer, value.value, index, 'little', 52, 8); // Adjust index index = index + 8; return index; } function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) { buffer[index++] = 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 = 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_DATA_CODE_W_SCOPE; // 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; // 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++] = 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 = value.code.toString(); // 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 serializeBinary(buffer, key, value, index, isArray) { // Write the type buffer[index++] = 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.SUBTYPE_BYTE_ARRAY) size = size + 4; // Write the size of the string to buffer buffer[index++] = size & 0xff; buffer[index++] = size >> 8 & 0xff; buffer[index++] = size >> 16 & 0xff; buffer[index++] = size >> 24 & 0xff; // Write the subtype to the buffer buffer[index++] = value.sub_type; // If we have binary type 2 the 4 first bytes are the size if (value.sub_type === _Binary.SUBTYPE_BYTE_ARRAY) { size = size - 4; buffer[index++] = size & 0xff; buffer[index++] = size >> 8 & 0xff; buffer[index++] = size >> 16 & 0xff; buffer[index++] = size >> 24 & 0xff; } // Write the data to the object 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++] = 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++] = 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 (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') { value = value.toBSON(); } if (typeof value === 'string') { index = serializeString(buffer, key, value, index, true); } else if (typeof value === 'number') { index = serializeNumber(buffer, key, value, index, true); } else if (typeof value === 'bigint') { throw new BSONTypeError('Unsupported type BigInt, please use Decimal128'); } else if (typeof value === '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 (isUint8Array(value)) { index = serializeBuffer(buffer, key, value, index, true); } else if (value instanceof RegExp || 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' && 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 BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); } } } else if (object instanceof bsonMap || isMap(object)) { var iterator = object.entries(); var done = false; while (!done) { // Unpack the next entry var entry = iterator.next(); done = !!entry.done; // Are we done, then skip and terminate if (done) continue; // Get the entry values var key = entry.value[0]; var value = entry.value[1]; // 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' || isBigInt64Array(value) || isBigUInt64Array(value)) { throw new BSONTypeError('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 === 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 (isUint8Array(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 BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); } } } else { if (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') { // Provided a custom serialization method object = object.toBSON(); if (object != null && _typeof(object) !== 'object') { throw new 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 (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === '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 BSONTypeError('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) 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 (isUint8Array(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 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; } /** @internal */ // Default Max Size var MAXSIZE = 1024 * 1024 * 17; // Current Internal Temporary Serialization Buffer var buffer = buffer_1.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.alloc(size); } } /** * 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.alloc(minInternalBufferSize); } // Attempt to serialize var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); // Create the final buffer var finishedBuffer = buffer_1.alloc(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 - 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 = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined); buffer.copy(finalBuffer, startIndex, 0, serializationIndex); // Return the index return startIndex + serializationIndex - 1; } /** * 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 deserialize$1(buffer instanceof buffer_1 ? buffer : ensureBuffer(buffer), options); } /** * 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 calculateObjectSize$1(object, serializeFunctions, ignoreUndefined); } /** * 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 = 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] = deserialize$1(bufferData, internalOptions); // Adjust index by the document size index = index + size; } // Return object containing end index of parsing and list of documents return index; } /** * 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, Code: _Code, DBRef: _DBRef, Decimal128: _Decimal, Double: _Double, Int32: _Int, Long: _Long, UUID: UUID, Map: bsonMap, MaxKey: _MaxKey, MinKey: _MinKey, ObjectId: _ObjectId, ObjectID: _ObjectId, BSONRegExp: _BSONRegExp, BSONSymbol: BSONSymbol, Timestamp: _Timestamp, EJSON: EJSON, setInternalBufferSize: setInternalBufferSize, serialize: serialize, serializeWithBufferAndIndex: serializeWithBufferAndIndex, deserialize: deserialize, calculateObjectSize: calculateObjectSize, deserializeStream: deserializeStream, BSONError: BSONError, BSONTypeError: BSONTypeError }; /* unused harmony default export */ var __WEBPACK_DEFAULT_EXPORT__ = ((/* unused pure expression or super */ null && (BSON))); /***/ }), /***/ 5176: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; module.exports = function xor(a, b) { var length = Math.min(a.length, b.length); var buffer = new Buffer(length); for (var i = 0; i < length; ++i) { buffer[i] = a[i] ^ b[i]; } return buffer; }; /***/ }), /***/ 365: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var base64 = __webpack_require__(7943); var ieee754 = __webpack_require__(8405); var customInspectSymbol = typeof Symbol === 'function' && typeof Symbol['for'] === 'function' // eslint-disable-line dot-notation ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation : null; exports.Buffer = Buffer; exports.SlowBuffer = SlowBuffer; exports.INSPECT_MAX_BYTES = 50; var K_MAX_LENGTH = 0x7fffffff; exports.kMaxLength = K_MAX_LENGTH; /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport(); if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') { console.error('This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'); } function typedArraySupport() { // Can typed array instances can be augmented? try { var arr = new Uint8Array(1); var proto = { foo: function foo() { return 42; } }; Object.setPrototypeOf(proto, Uint8Array.prototype); Object.setPrototypeOf(arr, proto); return arr.foo() === 42; } catch (e) { return false; } } Object.defineProperty(Buffer.prototype, 'parent', { enumerable: true, get: function get() { if (!Buffer.isBuffer(this)) return undefined; return this.buffer; } }); Object.defineProperty(Buffer.prototype, 'offset', { enumerable: true, get: function get() { if (!Buffer.isBuffer(this)) return undefined; return this.byteOffset; } }); function createBuffer(length) { if (length > K_MAX_LENGTH) { throw new RangeError('The value "' + length + '" is invalid for option "size"'); } // Return an augmented `Uint8Array` instance var buf = new Uint8Array(length); Object.setPrototypeOf(buf, Buffer.prototype); return buf; } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer(arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new TypeError('The "string" argument must be of type string. Received type number'); } return allocUnsafe(arg); } return from(arg, encodingOrOffset, length); } Buffer.poolSize = 8192; // not used by this implementation function from(value, encodingOrOffset, length) { if (typeof value === 'string') { return fromString(value, encodingOrOffset); } if (ArrayBuffer.isView(value)) { return fromArrayView(value); } if (value == null) { throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + _typeof(value)); } if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { return fromArrayBuffer(value, encodingOrOffset, length); } if (typeof SharedArrayBuffer !== 'undefined' && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { return fromArrayBuffer(value, encodingOrOffset, length); } if (typeof value === 'number') { throw new TypeError('The "value" argument must not be of type number. Received type number'); } var valueOf = value.valueOf && value.valueOf(); if (valueOf != null && valueOf !== value) { return Buffer.from(valueOf, encodingOrOffset, length); } var b = fromObject(value); if (b) return b; if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') { return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length); } throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + _typeof(value)); } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length); }; // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); Object.setPrototypeOf(Buffer, Uint8Array); function assertSize(size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be of type number'); } else if (size < 0) { throw new RangeError('The value "' + size + '" is invalid for option "size"'); } } function alloc(size, fill, encoding) { assertSize(size); if (size <= 0) { return createBuffer(size); } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpreted as a start offset. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); } return createBuffer(size); } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(size, fill, encoding); }; function allocUnsafe(size) { assertSize(size); return createBuffer(size < 0 ? 0 : checked(size) | 0); } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(size); }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(size); }; function fromString(string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8'; } if (!Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding); } var length = byteLength(string, encoding) | 0; var buf = createBuffer(length); var actual = buf.write(string, encoding); if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') buf = buf.slice(0, actual); } return buf; } function fromArrayLike(array) { var length = array.length < 0 ? 0 : checked(array.length) | 0; var buf = createBuffer(length); for (var i = 0; i < length; i += 1) { buf[i] = array[i] & 255; } return buf; } function fromArrayView(arrayView) { if (isInstance(arrayView, Uint8Array)) { var copy = new Uint8Array(arrayView); return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); } return fromArrayLike(arrayView); } function fromArrayBuffer(array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('"offset" is outside of buffer bounds'); } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('"length" is outside of buffer bounds'); } var buf; if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array); } else if (length === undefined) { buf = new Uint8Array(array, byteOffset); } else { buf = new Uint8Array(array, byteOffset, length); } // Return an augmented `Uint8Array` instance Object.setPrototypeOf(buf, Buffer.prototype); return buf; } function fromObject(obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0; var buf = createBuffer(len); if (buf.length === 0) { return buf; } obj.copy(buf, 0, 0, len); return buf; } if (obj.length !== undefined) { if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { return createBuffer(0); } return fromArrayLike(obj); } if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data); } } function checked(length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes'); } return length | 0; } function SlowBuffer(length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0; } return Buffer.alloc(+length); } Buffer.isBuffer = function isBuffer(b) { return b != null && b._isBuffer === true && b !== Buffer.prototype; // so Buffer.isBuffer(Buffer.prototype) will be false }; Buffer.compare = function compare(a, b) { if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength); if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength); if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'); } if (a === b) return 0; var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } } if (x < y) return -1; if (y < x) return 1; return 0; }; Buffer.isEncoding = function isEncoding(encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true; default: return false; } }; Buffer.concat = function concat(list, length) { if (!Array.isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers'); } if (list.length === 0) { return Buffer.alloc(0); } var i; if (length === undefined) { length = 0; for (i = 0; i < list.length; ++i) { length += list[i].length; } } var buffer = Buffer.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; if (isInstance(buf, Uint8Array)) { if (pos + buf.length > buffer.length) { Buffer.from(buf).copy(buffer, pos); } else { Uint8Array.prototype.set.call(buffer, buf, pos); } } else if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers'); } else { buf.copy(buffer, pos); } pos += buf.length; } return buffer; }; function byteLength(string, encoding) { if (Buffer.isBuffer(string)) { return string.length; } if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { return string.byteLength; } if (typeof string !== 'string') { throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + _typeof(string)); } var len = string.length; var mustMatch = arguments.length > 2 && arguments[2] === true; if (!mustMatch && len === 0) return 0; // Use a for loop to avoid recursion var loweredCase = false; for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len; case 'utf8': case 'utf-8': return utf8ToBytes(string).length; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2; case 'hex': return len >>> 1; case 'base64': return base64ToBytes(string).length; default: if (loweredCase) { return mustMatch ? -1 : utf8ToBytes(string).length; // assume utf8 } encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } } Buffer.byteLength = byteLength; function slowToString(encoding, start, end) { var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0; } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return ''; } if (end === undefined || end > this.length) { end = this.length; } if (end <= 0) { return ''; } // Force coercion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0; start >>>= 0; if (end <= start) { return ''; } if (!encoding) encoding = 'utf8'; while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end); case 'utf8': case 'utf-8': return utf8Slice(this, start, end); case 'ascii': return asciiSlice(this, start, end); case 'latin1': case 'binary': return latin1Slice(this, start, end); case 'base64': return base64Slice(this, start, end); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end); default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); encoding = (encoding + '').toLowerCase(); loweredCase = true; } } } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) // to detect a Buffer instance. It's not possible to use `instanceof Buffer` // reliably in a browserify context because there could be multiple different // copies of the 'buffer' package in use. This method works even for Buffer // instances that were created from another copy of the `buffer` package. // See: https://github.com/feross/buffer/issues/154 Buffer.prototype._isBuffer = true; function swap(b, n, m) { var i = b[n]; b[n] = b[m]; b[m] = i; } Buffer.prototype.swap16 = function swap16() { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits'); } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1); } return this; }; Buffer.prototype.swap32 = function swap32() { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits'); } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3); swap(this, i + 1, i + 2); } return this; }; Buffer.prototype.swap64 = function swap64() { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits'); } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7); swap(this, i + 1, i + 6); swap(this, i + 2, i + 5); swap(this, i + 3, i + 4); } return this; }; Buffer.prototype.toString = function toString() { var length = this.length; if (length === 0) return ''; if (arguments.length === 0) return utf8Slice(this, 0, length); return slowToString.apply(this, arguments); }; Buffer.prototype.toLocaleString = Buffer.prototype.toString; Buffer.prototype.equals = function equals(b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer'); if (this === b) return true; return Buffer.compare(this, b) === 0; }; Buffer.prototype.inspect = function inspect() { var str = ''; var max = exports.INSPECT_MAX_BYTES; str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim(); if (this.length > max) str += ' ... '; return ''; }; if (customInspectSymbol) { Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect; } Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { if (isInstance(target, Uint8Array)) { target = Buffer.from(target, target.offset, target.byteLength); } if (!Buffer.isBuffer(target)) { throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + _typeof(target)); } if (start === undefined) { start = 0; } if (end === undefined) { end = target ? target.length : 0; } if (thisStart === undefined) { thisStart = 0; } if (thisEnd === undefined) { thisEnd = this.length; } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index'); } if (thisStart >= thisEnd && start >= end) { return 0; } if (thisStart >= thisEnd) { return -1; } if (start >= end) { return 1; } start >>>= 0; end >>>= 0; thisStart >>>= 0; thisEnd >>>= 0; if (this === target) return 0; var x = thisEnd - thisStart; var y = end - start; var len = Math.min(x, y); var thisCopy = this.slice(thisStart, thisEnd); var targetCopy = target.slice(start, end); for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i]; y = targetCopy[i]; break; } } if (x < y) return -1; if (y < x) return 1; return 0; }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1; // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = 0; } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff; } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000; } byteOffset = +byteOffset; // Coerce to Number. if (numberIsNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : buffer.length - 1; } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset; if (byteOffset >= buffer.length) { if (dir) return -1;else byteOffset = buffer.length - 1; } else if (byteOffset < 0) { if (dir) byteOffset = 0;else return -1; } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1; } return arrayIndexOf(buffer, val, byteOffset, encoding, dir); } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] if (typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); } } return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); } throw new TypeError('val must be string, number or Buffer'); } function arrayIndexOf(arr, val, byteOffset, encoding, dir) { var indexSize = 1; var arrLength = arr.length; var valLength = val.length; if (encoding !== undefined) { encoding = String(encoding).toLowerCase(); if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1; } indexSize = 2; arrLength /= 2; valLength /= 2; byteOffset /= 2; } } function read(buf, i) { if (indexSize === 1) { return buf[i]; } else { return buf.readUInt16BE(i * indexSize); } } var i; if (dir) { var foundIndex = -1; for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i; if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; } else { if (foundIndex !== -1) i -= i - foundIndex; foundIndex = -1; } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; for (i = byteOffset; i >= 0; i--) { var found = true; for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false; break; } } if (found) return i; } } return -1; } Buffer.prototype.includes = function includes(val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1; }; Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true); }; Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false); }; function hexWrite(buf, string, offset, length) { offset = Number(offset) || 0; var remaining = buf.length - offset; if (!length) { length = remaining; } else { length = Number(length); if (length > remaining) { length = remaining; } } var strLen = string.length; if (length > strLen / 2) { length = strLen / 2; } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16); if (numberIsNaN(parsed)) return i; buf[offset + i] = parsed; } return i; } function utf8Write(buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); } function asciiWrite(buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length); } function base64Write(buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length); } function ucs2Write(buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); } Buffer.prototype.write = function write(string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; length = this.length; offset = 0; // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset; length = this.length; offset = 0; // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset >>> 0; if (isFinite(length)) { length = length >>> 0; if (encoding === undefined) encoding = 'utf8'; } else { encoding = length; length = undefined; } } else { throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported'); } var remaining = this.length - offset; if (length === undefined || length > remaining) length = remaining; if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds'); } if (!encoding) encoding = 'utf8'; var loweredCase = false; for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length); case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length); case 'ascii': case 'latin1': case 'binary': return asciiWrite(this, string, offset, length); case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length); default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } }; Buffer.prototype.toJSON = function toJSON() { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) }; }; function base64Slice(buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf); } else { return base64.fromByteArray(buf.slice(start, end)); } } function utf8Slice(buf, start, end) { end = Math.min(buf.length, end); var res = []; var i = start; while (i < end) { var firstByte = buf[i]; var codePoint = null; var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint; switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte; } break; case 2: secondByte = buf[i + 1]; if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; if (tempCodePoint > 0x7F) { codePoint = tempCodePoint; } } break; case 3: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint; } } break; case 4: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; fourthByte = buf[i + 3]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint; } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD; bytesPerSequence = 1; } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000; res.push(codePoint >>> 10 & 0x3FF | 0xD800); codePoint = 0xDC00 | codePoint & 0x3FF; } res.push(codePoint); i += bytesPerSequence; } return decodeCodePointsArray(res); } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000; function decodeCodePointsArray(codePoints) { var len = codePoints.length; if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints); // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = ''; var i = 0; while (i < len) { res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); } return res; } function asciiSlice(buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F); } return ret; } function latin1Slice(buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]); } return ret; } function hexSlice(buf, start, end) { var len = buf.length; if (!start || start < 0) start = 0; if (!end || end < 0 || end > len) end = len; var out = ''; for (var i = start; i < end; ++i) { out += hexSliceLookupTable[buf[i]]; } return out; } function utf16leSlice(buf, start, end) { var bytes = buf.slice(start, end); var res = ''; // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) for (var i = 0; i < bytes.length - 1; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); } return res; } Buffer.prototype.slice = function slice(start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; if (start < 0) { start += len; if (start < 0) start = 0; } else if (start > len) { start = len; } if (end < 0) { end += len; if (end < 0) end = 0; } else if (end > len) { end = len; } if (end < start) end = start; var newBuf = this.subarray(start, end); // Return an augmented `Uint8Array` instance Object.setPrototypeOf(newBuf, Buffer.prototype); return newBuf; }; /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset(offset, ext, length) { if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); } Buffer.prototype.readUintLE = Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } return val; }; Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) { checkOffset(offset, byteLength, this.length); } var val = this[offset + --byteLength]; var mul = 1; while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul; } return val; }; Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 1, this.length); return this[offset]; }; Buffer.prototype.readUint16LE = Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | this[offset + 1] << 8; }; Buffer.prototype.readUint16BE = Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] << 8 | this[offset + 1]; }; Buffer.prototype.readUint32LE = Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000; }; Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); }; Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var i = byteLength; var mul = 1; var val = this[offset + --i]; while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return this[offset]; return (0xff - this[offset] + 1) * -1; }; Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | this[offset + 1] << 8; return val & 0x8000 ? val | 0xFFFF0000 : val; }; Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | this[offset] << 8; return val & 0x8000 ? val | 0xFFFF0000 : val; }; Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; }; Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; }; Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ieee754.read(this, offset, true, 23, 4); }; Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ieee754.read(this, offset, false, 23, 4); }; Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 8, this.length); return ieee754.read(this, offset, true, 52, 8); }; Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 8, this.length); return ieee754.read(this, offset, false, 52, 8); }; function checkInt(buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); if (offset + ext > buf.length) throw new RangeError('Index out of range'); } Buffer.prototype.writeUintLE = Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var mul = 1; var i = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = value / mul & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var i = byteLength - 1; var mul = 1; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = value / mul & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); this[offset] = value & 0xff; return offset + 1; }; Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); this[offset] = value & 0xff; this[offset + 1] = value >>> 8; return offset + 2; }; Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); this[offset] = value >>> 8; this[offset + 1] = value & 0xff; return offset + 2; }; Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); this[offset + 3] = value >>> 24; this[offset + 2] = value >>> 16; this[offset + 1] = value >>> 8; this[offset] = value & 0xff; return offset + 4; }; Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 0xff; return offset + 4; }; Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = 0; var mul = 1; var sub = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1; } this[offset + i] = (value / mul >> 0) - sub & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = byteLength - 1; var mul = 1; var sub = 0; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1; } this[offset + i] = (value / mul >> 0) - sub & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); if (value < 0) value = 0xff + value + 1; this[offset] = value & 0xff; return offset + 1; }; Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); this[offset] = value & 0xff; this[offset + 1] = value >>> 8; return offset + 2; }; Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); this[offset] = value >>> 8; this[offset + 1] = value & 0xff; return offset + 2; }; Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); this[offset] = value & 0xff; this[offset + 1] = value >>> 8; this[offset + 2] = value >>> 16; this[offset + 3] = value >>> 24; return offset + 4; }; Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (value < 0) value = 0xffffffff + value + 1; this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 0xff; return offset + 4; }; function checkIEEE754(buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range'); if (offset < 0) throw new RangeError('Index out of range'); } function writeFloat(buf, value, offset, littleEndian, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38); } ieee754.write(buf, value, offset, littleEndian, 23, 4); return offset + 4; } Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert); }; Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert); }; function writeDouble(buf, value, offset, littleEndian, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308); } ieee754.write(buf, value, offset, littleEndian, 52, 8); return offset + 8; } Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert); }; Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert); }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy(target, targetStart, start, end) { if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer'); if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; if (!targetStart) targetStart = 0; if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done if (end === start) return 0; if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds'); } if (start < 0 || start >= this.length) throw new RangeError('Index out of range'); if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? if (end > this.length) end = this.length; if (target.length - targetStart < end - start) { end = target.length - targetStart + start; } var len = end - start; if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { // Use built-in when available, missing from IE11 this.copyWithin(targetStart, start, end); } else { Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart); } return len; }; // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill(val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start; start = 0; end = this.length; } else if (typeof end === 'string') { encoding = end; end = this.length; } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string'); } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding); } if (val.length === 1) { var code = val.charCodeAt(0); if (encoding === 'utf8' && code < 128 || encoding === 'latin1') { // Fast path: If `val` fits into a single byte, use that numeric value. val = code; } } } else if (typeof val === 'number') { val = val & 255; } else if (typeof val === 'boolean') { val = Number(val); } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index'); } if (end <= start) { return this; } start = start >>> 0; end = end === undefined ? this.length : end >>> 0; if (!val) val = 0; var i; if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val; } } else { var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding); var len = bytes.length; if (len === 0) { throw new TypeError('The value "' + val + '" is invalid for argument "value"'); } for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; } } return this; }; // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; function base64clean(str) { // Node takes equal signs as end of the Base64 encoding str = str.split('=')[0]; // Node strips out invalid characters like \n and \t from the string, base64-js does not str = str.trim().replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '='; } return str; } function utf8ToBytes(string, units) { units = units || Infinity; var codePoint; var length = string.length; var leadSurrogate = null; var bytes = []; for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i); // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue; } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue; } // valid lead leadSurrogate = codePoint; continue; } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); leadSurrogate = codePoint; continue; } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); } leadSurrogate = null; // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break; bytes.push(codePoint); } else if (codePoint < 0x800) { if ((units -= 2) < 0) break; bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break; bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break; bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); } else { throw new Error('Invalid code point'); } } return bytes; } function asciiToBytes(str) { var byteArray = []; for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF); } return byteArray; } function utf16leToBytes(str, units) { var c, hi, lo; var byteArray = []; for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break; c = str.charCodeAt(i); hi = c >> 8; lo = c % 256; byteArray.push(lo); byteArray.push(hi); } return byteArray; } function base64ToBytes(str) { return base64.toByteArray(base64clean(str)); } function blitBuffer(src, dst, offset, length) { for (var i = 0; i < length; ++i) { if (i + offset >= dst.length || i >= src.length) break; dst[i + offset] = src[i]; } return i; } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass // the `instanceof` check but they should be treated as of that type. // See: https://github.com/feross/buffer/issues/166 function isInstance(obj, type) { return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; } function numberIsNaN(obj) { // For IE11 support return obj !== obj; // eslint-disable-line no-self-compare } // Create lookup table for `toString('hex')` // See: https://github.com/feross/buffer/issues/219 var hexSliceLookupTable = function () { var alphabet = '0123456789abcdef'; var table = new Array(256); for (var i = 0; i < 16; ++i) { var i16 = i * 16; for (var j = 0; j < 16; ++j) { table[i16 + j] = alphabet[i] + alphabet[j]; } } return table; }(); /***/ }), /***/ 8780: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var GetIntrinsic = __webpack_require__(6893); var callBind = __webpack_require__(3862); var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); module.exports = function callBoundIntrinsic(name, allowMissing) { var intrinsic = GetIntrinsic(name, !!allowMissing); if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { return callBind(intrinsic); } return intrinsic; }; /***/ }), /***/ 3862: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var bind = __webpack_require__(5246); var GetIntrinsic = __webpack_require__(6893); var $apply = GetIntrinsic('%Function.prototype.apply%'); var $call = GetIntrinsic('%Function.prototype.call%'); var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); var $max = GetIntrinsic('%Math.max%'); if ($defineProperty) { try { $defineProperty({}, 'a', { value: 1 }); } catch (e) { // IE 8 has a broken defineProperty $defineProperty = null; } } module.exports = function callBind(originalFunction) { var func = $reflectApply(bind, $call, arguments); if ($gOPD && $defineProperty) { var desc = $gOPD(func, 'length'); if (desc.configurable) { // original length, plus the receiver, minus any additional arguments (after the receiver) $defineProperty(func, 'length', { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }); } } return func; }; var applyBind = function applyBind() { return $reflectApply(bind, $apply, arguments); }; if ($defineProperty) { $defineProperty(module.exports, 'apply', { value: applyBind }); } else { module.exports.apply = applyBind; } /***/ }), /***/ 8842: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var Buffer = (__webpack_require__(9047).Buffer); var Transform = (__webpack_require__(4723).Transform); var StringDecoder = (__webpack_require__(113)/* .StringDecoder */ .s); var inherits = __webpack_require__(376); function CipherBase(hashMode) { Transform.call(this); this.hashMode = typeof hashMode === 'string'; if (this.hashMode) { this[hashMode] = this._finalOrDigest; } else { this["final"] = this._finalOrDigest; } if (this._final) { this.__final = this._final; this._final = null; } this._decoder = null; this._encoding = null; } inherits(CipherBase, Transform); CipherBase.prototype.update = function (data, inputEnc, outputEnc) { if (typeof data === 'string') { data = Buffer.from(data, inputEnc); } var outData = this._update(data); if (this.hashMode) return this; if (outputEnc) { outData = this._toString(outData, outputEnc); } return outData; }; CipherBase.prototype.setAutoPadding = function () {}; CipherBase.prototype.getAuthTag = function () { throw new Error('trying to get auth tag in unsupported state'); }; CipherBase.prototype.setAuthTag = function () { throw new Error('trying to set auth tag in unsupported state'); }; CipherBase.prototype.setAAD = function () { throw new Error('trying to set aad in unsupported state'); }; CipherBase.prototype._transform = function (data, _, next) { var err; try { if (this.hashMode) { this._update(data); } else { this.push(this._update(data)); } } catch (e) { err = e; } finally { next(err); } }; CipherBase.prototype._flush = function (done) { var err; try { this.push(this.__final()); } catch (e) { err = e; } done(err); }; CipherBase.prototype._finalOrDigest = function (outputEnc) { var outData = this.__final() || Buffer.alloc(0); if (outputEnc) { outData = this._toString(outData, outputEnc, true); } return outData; }; CipherBase.prototype._toString = function (value, enc, fin) { if (!this._decoder) { this._decoder = new StringDecoder(enc); this._encoding = enc; } if (this._encoding !== enc) throw new Error('can\'t switch encodings'); var out = this._decoder.write(value); if (fin) { out += this._decoder.end(); } return out; }; module.exports = CipherBase; /***/ }), /***/ 4637: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; var elliptic = __webpack_require__(8333); var BN = __webpack_require__(6781); module.exports = function createECDH(curve) { return new ECDH(curve); }; var aliases = { secp256k1: { name: 'secp256k1', byteLength: 32 }, secp224r1: { name: 'p224', byteLength: 28 }, prime256v1: { name: 'p256', byteLength: 32 }, prime192v1: { name: 'p192', byteLength: 24 }, ed25519: { name: 'ed25519', byteLength: 32 }, secp384r1: { name: 'p384', byteLength: 48 }, secp521r1: { name: 'p521', byteLength: 66 } }; aliases.p224 = aliases.secp224r1; aliases.p256 = aliases.secp256r1 = aliases.prime256v1; aliases.p192 = aliases.secp192r1 = aliases.prime192v1; aliases.p384 = aliases.secp384r1; aliases.p521 = aliases.secp521r1; function ECDH(curve) { this.curveType = aliases[curve]; if (!this.curveType) { this.curveType = { name: curve }; } this.curve = new elliptic.ec(this.curveType.name); // eslint-disable-line new-cap this.keys = void 0; } ECDH.prototype.generateKeys = function (enc, format) { this.keys = this.curve.genKeyPair(); return this.getPublicKey(enc, format); }; ECDH.prototype.computeSecret = function (other, inenc, enc) { inenc = inenc || 'utf8'; if (!Buffer.isBuffer(other)) { other = new Buffer(other, inenc); } var otherPub = this.curve.keyFromPublic(other).getPublic(); var out = otherPub.mul(this.keys.getPrivate()).getX(); return formatReturnValue(out, enc, this.curveType.byteLength); }; ECDH.prototype.getPublicKey = function (enc, format) { var key = this.keys.getPublic(format === 'compressed', true); if (format === 'hybrid') { if (key[key.length - 1] % 2) { key[0] = 7; } else { key[0] = 6; } } return formatReturnValue(key, enc); }; ECDH.prototype.getPrivateKey = function (enc) { return formatReturnValue(this.keys.getPrivate(), enc); }; ECDH.prototype.setPublicKey = function (pub, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(pub)) { pub = new Buffer(pub, enc); } this.keys._importPublic(pub); return this; }; ECDH.prototype.setPrivateKey = function (priv, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(priv)) { priv = new Buffer(priv, enc); } var _priv = new BN(priv); _priv = _priv.toString(16); this.keys = this.curve.genKeyPair(); this.keys._importPrivate(_priv); return this; }; function formatReturnValue(bn, enc, len) { if (!Array.isArray(bn)) { bn = bn.toArray(); } var buf = new Buffer(bn); if (len && buf.length < len) { var zeros = new Buffer(len - buf.length); zeros.fill(0); buf = Buffer.concat([zeros, buf]); } if (!enc) { return buf; } else { return buf.toString(enc); } } /***/ }), /***/ 8339: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var inherits = __webpack_require__(376); var MD5 = __webpack_require__(722); var RIPEMD160 = __webpack_require__(8100); var sha = __webpack_require__(1806); var Base = __webpack_require__(8842); function Hash(hash) { Base.call(this, 'digest'); this._hash = hash; } inherits(Hash, Base); Hash.prototype._update = function (data) { this._hash.update(data); }; Hash.prototype._final = function () { return this._hash.digest(); }; module.exports = function createHash(alg) { alg = alg.toLowerCase(); if (alg === 'md5') return new MD5(); if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160(); return new Hash(sha(alg)); }; /***/ }), /***/ 3277: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var MD5 = __webpack_require__(722); module.exports = function (buffer) { return new MD5().update(buffer).digest(); }; /***/ }), /***/ 8736: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var inherits = __webpack_require__(376); var Legacy = __webpack_require__(2912); var Base = __webpack_require__(8842); var Buffer = (__webpack_require__(9047).Buffer); var md5 = __webpack_require__(3277); var RIPEMD160 = __webpack_require__(8100); var sha = __webpack_require__(1806); var ZEROS = Buffer.alloc(128); function Hmac(alg, key) { Base.call(this, 'digest'); if (typeof key === 'string') { key = Buffer.from(key); } var blocksize = alg === 'sha512' || alg === 'sha384' ? 128 : 64; this._alg = alg; this._key = key; if (key.length > blocksize) { var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg); key = hash.update(key).digest(); } else if (key.length < blocksize) { key = Buffer.concat([key, ZEROS], blocksize); } var ipad = this._ipad = Buffer.allocUnsafe(blocksize); var opad = this._opad = Buffer.allocUnsafe(blocksize); for (var i = 0; i < blocksize; i++) { ipad[i] = key[i] ^ 0x36; opad[i] = key[i] ^ 0x5C; } this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg); this._hash.update(ipad); } inherits(Hmac, Base); Hmac.prototype._update = function (data) { this._hash.update(data); }; Hmac.prototype._final = function () { var h = this._hash.digest(); var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg); return hash.update(this._opad).update(h).digest(); }; module.exports = function createHmac(alg, key) { alg = alg.toLowerCase(); if (alg === 'rmd160' || alg === 'ripemd160') { return new Hmac('rmd160', key); } if (alg === 'md5') { return new Legacy(md5, key); } return new Hmac(alg, key); }; /***/ }), /***/ 2912: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var inherits = __webpack_require__(376); var Buffer = (__webpack_require__(9047).Buffer); var Base = __webpack_require__(8842); var ZEROS = Buffer.alloc(128); var blocksize = 64; function Hmac(alg, key) { Base.call(this, 'digest'); if (typeof key === 'string') { key = Buffer.from(key); } this._alg = alg; this._key = key; if (key.length > blocksize) { key = alg(key); } else if (key.length < blocksize) { key = Buffer.concat([key, ZEROS], blocksize); } var ipad = this._ipad = Buffer.allocUnsafe(blocksize); var opad = this._opad = Buffer.allocUnsafe(blocksize); for (var i = 0; i < blocksize; i++) { ipad[i] = key[i] ^ 0x36; opad[i] = key[i] ^ 0x5C; } this._hash = [ipad]; } inherits(Hmac, Base); Hmac.prototype._update = function (data) { this._hash.push(data); }; Hmac.prototype._final = function () { var h = this._alg(Buffer.concat(this._hash)); return this._alg(Buffer.concat([this._opad, h])); }; module.exports = Hmac; /***/ }), /***/ 462: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var __webpack_unused_export__; exports.O6 = __webpack_unused_export__ = __webpack_unused_export__ = /* unused reexport */ __webpack_require__(5760); __webpack_unused_export__ = /* unused reexport */ __webpack_require__(8339); __webpack_unused_export__ = /* unused reexport */ __webpack_require__(8736); var algos = __webpack_require__(3363); var algoKeys = Object.keys(algos); var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys); __webpack_unused_export__ = function () { return hashes; }; var p = __webpack_require__(9379); __webpack_unused_export__ = p.pbkdf2; __webpack_unused_export__ = p.pbkdf2Sync; var aes = __webpack_require__(5972); __webpack_unused_export__ = aes.Cipher; __webpack_unused_export__ = aes.createCipher; __webpack_unused_export__ = aes.Cipheriv; __webpack_unused_export__ = aes.createCipheriv; __webpack_unused_export__ = aes.Decipher; __webpack_unused_export__ = aes.createDecipher; __webpack_unused_export__ = aes.Decipheriv; __webpack_unused_export__ = aes.createDecipheriv; __webpack_unused_export__ = aes.getCiphers; __webpack_unused_export__ = aes.listCiphers; var dh = __webpack_require__(1822); __webpack_unused_export__ = dh.DiffieHellmanGroup; __webpack_unused_export__ = dh.createDiffieHellmanGroup; __webpack_unused_export__ = dh.getDiffieHellman; __webpack_unused_export__ = dh.createDiffieHellman; __webpack_unused_export__ = dh.DiffieHellman; var sign = __webpack_require__(1022); __webpack_unused_export__ = sign.createSign; __webpack_unused_export__ = sign.Sign; __webpack_unused_export__ = sign.createVerify; __webpack_unused_export__ = sign.Verify; /* unused reexport */ __webpack_require__(4637); var publicEncrypt = __webpack_require__(2368); __webpack_unused_export__ = publicEncrypt.publicEncrypt; __webpack_unused_export__ = publicEncrypt.privateEncrypt; __webpack_unused_export__ = publicEncrypt.publicDecrypt; __webpack_unused_export__ = publicEncrypt.privateDecrypt; // the least I can do is make error messages for the rest of the node.js/crypto api. // ;[ // 'createCredentials' // ].forEach(function (name) { // exports[name] = function () { // throw new Error([ // 'sorry, ' + name + ' is not implemented yet', // 'we accept pull requests', // 'https://github.com/crypto-browserify/crypto-browserify' // ].join('\n')) // } // }) var rf = __webpack_require__(9301); __webpack_unused_export__ = rf.randomFill; __webpack_unused_export__ = rf.randomFillSync; __webpack_unused_export__ = function () { throw new Error(['sorry, createCredentials is not implemented yet', 'we accept pull requests', 'https://github.com/crypto-browserify/crypto-browserify'].join('\n')); }; __webpack_unused_export__ = { 'DH_CHECK_P_NOT_SAFE_PRIME': 2, 'DH_CHECK_P_NOT_PRIME': 1, 'DH_UNABLE_TO_CHECK_GENERATOR': 4, 'DH_NOT_SUITABLE_GENERATOR': 8, 'NPN_ENABLED': 1, 'ALPN_ENABLED': 1, 'RSA_PKCS1_PADDING': 1, 'RSA_SSLV23_PADDING': 2, 'RSA_NO_PADDING': 3, 'RSA_PKCS1_OAEP_PADDING': 4, 'RSA_X931_PADDING': 5, 'RSA_PKCS1_PSS_PADDING': 6, 'POINT_CONVERSION_COMPRESSED': 2, 'POINT_CONVERSION_UNCOMPRESSED': 4, 'POINT_CONVERSION_HYBRID': 6 }; /***/ }), /***/ 5509: /***/ ((module) => { function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } /** * 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)); }; /** * 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; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ 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 */ 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' : ''); } /***/ }), /***/ 8801: /***/ ((module, exports, __webpack_require__) => { /* eslint-env browser */ /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = function () { var warned = false; return function () { 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`.'); } }; }(); /** * 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; } // 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; } var 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 var index = 0; var lastC = 0; args[0].replace(/%[a-zA-Z%]/g, function (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 || function () {}; /** * 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() { var 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 ({env:{}}) !== 'undefined' && 'env' in ({env:{}})) { r = ({env:{}}).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? } } module.exports = __webpack_require__(5331)(exports); var formatters = module.exports.formatters; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; /***/ }), /***/ 5331: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /** * 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 = __webpack_require__(5509); createDebug.destroy = destroy; Object.keys(env).forEach(function (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) { var hash = 0; for (var 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) { var prevTime; var enableOverride = null; var namespacesCache; var enabledCache; function debug() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } // Disabled? if (!debug.enabled) { return; } var self = debug; // Set `diff` timestamp var curr = Number(new Date()); var 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 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 '%'; } index++; var formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { var val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); var 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: function get() { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: function 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) { var 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 = []; var i; var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); var 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.slice(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { var namespaces = [].concat(_toConsumableArray(createDebug.names.map(toNamespace)), _toConsumableArray(createDebug.skips.map(toNamespace).map(function (namespace) { return '-' + 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; } var i; var 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; /***/ }), /***/ 7921: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var keys = __webpack_require__(3818); var hasSymbols = typeof Symbol === 'function' && _typeof(Symbol('foo')) === 'symbol'; var toStr = Object.prototype.toString; var concat = Array.prototype.concat; var origDefineProperty = Object.defineProperty; var isFunction = function isFunction(fn) { return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; }; var hasPropertyDescriptors = __webpack_require__(2579)(); var supportsDescriptors = origDefineProperty && hasPropertyDescriptors; var defineProperty = function defineProperty(object, name, value, predicate) { if (name in object && (!isFunction(predicate) || !predicate())) { return; } if (supportsDescriptors) { origDefineProperty(object, name, { configurable: true, enumerable: false, value: value, writable: true }); } else { object[name] = value; // eslint-disable-line no-param-reassign } }; var defineProperties = function defineProperties(object, map) { var predicates = arguments.length > 2 ? arguments[2] : {}; var props = keys(map); if (hasSymbols) { props = concat.call(props, Object.getOwnPropertySymbols(map)); } for (var i = 0; i < props.length; i += 1) { defineProperty(object, props[i], map[props[i]], predicates[props[i]]); } }; defineProperties.supportsDescriptors = !!supportsDescriptors; module.exports = defineProperties; /***/ }), /***/ 167: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.utils = __webpack_require__(5061); exports.Cipher = __webpack_require__(7499); exports.DES = __webpack_require__(9484); exports.CBC = __webpack_require__(8254); exports.EDE = __webpack_require__(5573); /***/ }), /***/ 8254: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var assert = __webpack_require__(1130); var inherits = __webpack_require__(376); var proto = {}; function CBCState(iv) { assert.equal(iv.length, 8, 'Invalid IV length'); this.iv = new Array(8); for (var i = 0; i < this.iv.length; i++) { this.iv[i] = iv[i]; } } function instantiate(Base) { function CBC(options) { Base.call(this, options); this._cbcInit(); } inherits(CBC, Base); var keys = Object.keys(proto); for (var i = 0; i < keys.length; i++) { var key = keys[i]; CBC.prototype[key] = proto[key]; } CBC.create = function create(options) { return new CBC(options); }; return CBC; } exports.instantiate = instantiate; proto._cbcInit = function _cbcInit() { var state = new CBCState(this.options.iv); this._cbcState = state; }; proto._update = function _update(inp, inOff, out, outOff) { var state = this._cbcState; var superProto = this.constructor.super_.prototype; var iv = state.iv; if (this.type === 'encrypt') { for (var i = 0; i < this.blockSize; i++) { iv[i] ^= inp[inOff + i]; } superProto._update.call(this, iv, 0, out, outOff); for (var i = 0; i < this.blockSize; i++) { iv[i] = out[outOff + i]; } } else { superProto._update.call(this, inp, inOff, out, outOff); for (var i = 0; i < this.blockSize; i++) { out[outOff + i] ^= iv[i]; } for (var i = 0; i < this.blockSize; i++) { iv[i] = inp[inOff + i]; } } }; /***/ }), /***/ 7499: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var assert = __webpack_require__(1130); function Cipher(options) { this.options = options; this.type = this.options.type; this.blockSize = 8; this._init(); this.buffer = new Array(this.blockSize); this.bufferOff = 0; } module.exports = Cipher; Cipher.prototype._init = function _init() {// Might be overrided }; Cipher.prototype.update = function update(data) { if (data.length === 0) return []; if (this.type === 'decrypt') return this._updateDecrypt(data);else return this._updateEncrypt(data); }; Cipher.prototype._buffer = function _buffer(data, off) { // Append data to buffer var min = Math.min(this.buffer.length - this.bufferOff, data.length - off); for (var i = 0; i < min; i++) { this.buffer[this.bufferOff + i] = data[off + i]; } this.bufferOff += min; // Shift next return min; }; Cipher.prototype._flushBuffer = function _flushBuffer(out, off) { this._update(this.buffer, 0, out, off); this.bufferOff = 0; return this.blockSize; }; Cipher.prototype._updateEncrypt = function _updateEncrypt(data) { var inputOff = 0; var outputOff = 0; var count = (this.bufferOff + data.length) / this.blockSize | 0; var out = new Array(count * this.blockSize); if (this.bufferOff !== 0) { inputOff += this._buffer(data, inputOff); if (this.bufferOff === this.buffer.length) outputOff += this._flushBuffer(out, outputOff); } // Write blocks var max = data.length - (data.length - inputOff) % this.blockSize; for (; inputOff < max; inputOff += this.blockSize) { this._update(data, inputOff, out, outputOff); outputOff += this.blockSize; } // Queue rest for (; inputOff < data.length; inputOff++, this.bufferOff++) { this.buffer[this.bufferOff] = data[inputOff]; } return out; }; Cipher.prototype._updateDecrypt = function _updateDecrypt(data) { var inputOff = 0; var outputOff = 0; var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1; var out = new Array(count * this.blockSize); // TODO(indutny): optimize it, this is far from optimal for (; count > 0; count--) { inputOff += this._buffer(data, inputOff); outputOff += this._flushBuffer(out, outputOff); } // Buffer rest of the input inputOff += this._buffer(data, inputOff); return out; }; Cipher.prototype["final"] = function _final(buffer) { var first; if (buffer) first = this.update(buffer); var last; if (this.type === 'encrypt') last = this._finalEncrypt();else last = this._finalDecrypt(); if (first) return first.concat(last);else return last; }; Cipher.prototype._pad = function _pad(buffer, off) { if (off === 0) return false; while (off < buffer.length) { buffer[off++] = 0; } return true; }; Cipher.prototype._finalEncrypt = function _finalEncrypt() { if (!this._pad(this.buffer, this.bufferOff)) return []; var out = new Array(this.blockSize); this._update(this.buffer, 0, out, 0); return out; }; Cipher.prototype._unpad = function _unpad(buffer) { return buffer; }; Cipher.prototype._finalDecrypt = function _finalDecrypt() { assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt'); var out = new Array(this.blockSize); this._flushBuffer(out, 0); return this._unpad(out); }; /***/ }), /***/ 9484: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var assert = __webpack_require__(1130); var inherits = __webpack_require__(376); var utils = __webpack_require__(5061); var Cipher = __webpack_require__(7499); function DESState() { this.tmp = new Array(2); this.keys = null; } function DES(options) { Cipher.call(this, options); var state = new DESState(); this._desState = state; this.deriveKeys(state, options.key); } inherits(DES, Cipher); module.exports = DES; DES.create = function create(options) { return new DES(options); }; var shiftTable = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1]; DES.prototype.deriveKeys = function deriveKeys(state, key) { state.keys = new Array(16 * 2); assert.equal(key.length, this.blockSize, 'Invalid key length'); var kL = utils.readUInt32BE(key, 0); var kR = utils.readUInt32BE(key, 4); utils.pc1(kL, kR, state.tmp, 0); kL = state.tmp[0]; kR = state.tmp[1]; for (var i = 0; i < state.keys.length; i += 2) { var shift = shiftTable[i >>> 1]; kL = utils.r28shl(kL, shift); kR = utils.r28shl(kR, shift); utils.pc2(kL, kR, state.keys, i); } }; DES.prototype._update = function _update(inp, inOff, out, outOff) { var state = this._desState; var l = utils.readUInt32BE(inp, inOff); var r = utils.readUInt32BE(inp, inOff + 4); // Initial Permutation utils.ip(l, r, state.tmp, 0); l = state.tmp[0]; r = state.tmp[1]; if (this.type === 'encrypt') this._encrypt(state, l, r, state.tmp, 0);else this._decrypt(state, l, r, state.tmp, 0); l = state.tmp[0]; r = state.tmp[1]; utils.writeUInt32BE(out, l, outOff); utils.writeUInt32BE(out, r, outOff + 4); }; DES.prototype._pad = function _pad(buffer, off) { var value = buffer.length - off; for (var i = off; i < buffer.length; i++) { buffer[i] = value; } return true; }; DES.prototype._unpad = function _unpad(buffer) { var pad = buffer[buffer.length - 1]; for (var i = buffer.length - pad; i < buffer.length; i++) { assert.equal(buffer[i], pad); } return buffer.slice(0, buffer.length - pad); }; DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) { var l = lStart; var r = rStart; // Apply f() x16 times for (var i = 0; i < state.keys.length; i += 2) { var keyL = state.keys[i]; var keyR = state.keys[i + 1]; // f(r, k) utils.expand(r, state.tmp, 0); keyL ^= state.tmp[0]; keyR ^= state.tmp[1]; var s = utils.substitute(keyL, keyR); var f = utils.permute(s); var t = r; r = (l ^ f) >>> 0; l = t; } // Reverse Initial Permutation utils.rip(r, l, out, off); }; DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) { var l = rStart; var r = lStart; // Apply f() x16 times for (var i = state.keys.length - 2; i >= 0; i -= 2) { var keyL = state.keys[i]; var keyR = state.keys[i + 1]; // f(r, k) utils.expand(l, state.tmp, 0); keyL ^= state.tmp[0]; keyR ^= state.tmp[1]; var s = utils.substitute(keyL, keyR); var f = utils.permute(s); var t = l; l = (r ^ f) >>> 0; r = t; } // Reverse Initial Permutation utils.rip(l, r, out, off); }; /***/ }), /***/ 5573: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var assert = __webpack_require__(1130); var inherits = __webpack_require__(376); var Cipher = __webpack_require__(7499); var DES = __webpack_require__(9484); function EDEState(type, key) { assert.equal(key.length, 24, 'Invalid key length'); var k1 = key.slice(0, 8); var k2 = key.slice(8, 16); var k3 = key.slice(16, 24); if (type === 'encrypt') { this.ciphers = [DES.create({ type: 'encrypt', key: k1 }), DES.create({ type: 'decrypt', key: k2 }), DES.create({ type: 'encrypt', key: k3 })]; } else { this.ciphers = [DES.create({ type: 'decrypt', key: k3 }), DES.create({ type: 'encrypt', key: k2 }), DES.create({ type: 'decrypt', key: k1 })]; } } function EDE(options) { Cipher.call(this, options); var state = new EDEState(this.type, this.options.key); this._edeState = state; } inherits(EDE, Cipher); module.exports = EDE; EDE.create = function create(options) { return new EDE(options); }; EDE.prototype._update = function _update(inp, inOff, out, outOff) { var state = this._edeState; state.ciphers[0]._update(inp, inOff, out, outOff); state.ciphers[1]._update(out, outOff, out, outOff); state.ciphers[2]._update(out, outOff, out, outOff); }; EDE.prototype._pad = DES.prototype._pad; EDE.prototype._unpad = DES.prototype._unpad; /***/ }), /***/ 5061: /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.readUInt32BE = function readUInt32BE(bytes, off) { var res = bytes[0 + off] << 24 | bytes[1 + off] << 16 | bytes[2 + off] << 8 | bytes[3 + off]; return res >>> 0; }; exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) { bytes[0 + off] = value >>> 24; bytes[1 + off] = value >>> 16 & 0xff; bytes[2 + off] = value >>> 8 & 0xff; bytes[3 + off] = value & 0xff; }; exports.ip = function ip(inL, inR, out, off) { var outL = 0; var outR = 0; for (var i = 6; i >= 0; i -= 2) { for (var j = 0; j <= 24; j += 8) { outL <<= 1; outL |= inR >>> j + i & 1; } for (var j = 0; j <= 24; j += 8) { outL <<= 1; outL |= inL >>> j + i & 1; } } for (var i = 6; i >= 0; i -= 2) { for (var j = 1; j <= 25; j += 8) { outR <<= 1; outR |= inR >>> j + i & 1; } for (var j = 1; j <= 25; j += 8) { outR <<= 1; outR |= inL >>> j + i & 1; } } out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; exports.rip = function rip(inL, inR, out, off) { var outL = 0; var outR = 0; for (var i = 0; i < 4; i++) { for (var j = 24; j >= 0; j -= 8) { outL <<= 1; outL |= inR >>> j + i & 1; outL <<= 1; outL |= inL >>> j + i & 1; } } for (var i = 4; i < 8; i++) { for (var j = 24; j >= 0; j -= 8) { outR <<= 1; outR |= inR >>> j + i & 1; outR <<= 1; outR |= inL >>> j + i & 1; } } out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; exports.pc1 = function pc1(inL, inR, out, off) { var outL = 0; var outR = 0; // 7, 15, 23, 31, 39, 47, 55, 63 // 6, 14, 22, 30, 39, 47, 55, 63 // 5, 13, 21, 29, 39, 47, 55, 63 // 4, 12, 20, 28 for (var i = 7; i >= 5; i--) { for (var j = 0; j <= 24; j += 8) { outL <<= 1; outL |= inR >> j + i & 1; } for (var j = 0; j <= 24; j += 8) { outL <<= 1; outL |= inL >> j + i & 1; } } for (var j = 0; j <= 24; j += 8) { outL <<= 1; outL |= inR >> j + i & 1; } // 1, 9, 17, 25, 33, 41, 49, 57 // 2, 10, 18, 26, 34, 42, 50, 58 // 3, 11, 19, 27, 35, 43, 51, 59 // 36, 44, 52, 60 for (var i = 1; i <= 3; i++) { for (var j = 0; j <= 24; j += 8) { outR <<= 1; outR |= inR >> j + i & 1; } for (var j = 0; j <= 24; j += 8) { outR <<= 1; outR |= inL >> j + i & 1; } } for (var j = 0; j <= 24; j += 8) { outR <<= 1; outR |= inL >> j + i & 1; } out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; exports.r28shl = function r28shl(num, shift) { return num << shift & 0xfffffff | num >>> 28 - shift; }; var pc2table = [// inL => outL 14, 11, 17, 4, 27, 23, 25, 0, 13, 22, 7, 18, 5, 9, 16, 24, 2, 20, 12, 21, 1, 8, 15, 26, // inR => outR 15, 4, 25, 19, 9, 1, 26, 16, 5, 11, 23, 8, 12, 7, 17, 0, 22, 3, 10, 14, 6, 20, 27, 24]; exports.pc2 = function pc2(inL, inR, out, off) { var outL = 0; var outR = 0; var len = pc2table.length >>> 1; for (var i = 0; i < len; i++) { outL <<= 1; outL |= inL >>> pc2table[i] & 0x1; } for (var i = len; i < pc2table.length; i++) { outR <<= 1; outR |= inR >>> pc2table[i] & 0x1; } out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; exports.expand = function expand(r, out, off) { var outL = 0; var outR = 0; outL = (r & 1) << 5 | r >>> 27; for (var i = 23; i >= 15; i -= 4) { outL <<= 6; outL |= r >>> i & 0x3f; } for (var i = 11; i >= 3; i -= 4) { outR |= r >>> i & 0x3f; outR <<= 6; } outR |= (r & 0x1f) << 1 | r >>> 31; out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; var sTable = [14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13, 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9, 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10, 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12, 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14, 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6, 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3, 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13, 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7, 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12, 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13, 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11]; exports.substitute = function substitute(inL, inR) { var out = 0; for (var i = 0; i < 4; i++) { var b = inL >>> 18 - i * 6 & 0x3f; var sb = sTable[i * 0x40 + b]; out <<= 4; out |= sb; } for (var i = 0; i < 4; i++) { var b = inR >>> 18 - i * 6 & 0x3f; var sb = sTable[4 * 0x40 + i * 0x40 + b]; out <<= 4; out |= sb; } return out >>> 0; }; var permuteTable = [16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22, 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7]; exports.permute = function permute(num) { var out = 0; for (var i = 0; i < permuteTable.length; i++) { out <<= 1; out |= num >>> permuteTable[i] & 0x1; } return out >>> 0; }; exports.padSplit = function padSplit(num, size, group) { var str = num.toString(2); while (str.length < size) { str = '0' + str; } var out = []; for (var i = 0; i < size; i += group) { out.push(str.slice(i, i + group)); } return out.join(' '); }; /***/ }), /***/ 1822: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; var generatePrime = __webpack_require__(2227); var primes = __webpack_require__(9799); var DH = __webpack_require__(6951); function getDiffieHellman(mod) { var prime = new Buffer(primes[mod].prime, 'hex'); var gen = new Buffer(primes[mod].gen, 'hex'); return new DH(prime, gen); } var ENCODINGS = { 'binary': true, 'hex': true, 'base64': true }; function createDiffieHellman(prime, enc, generator, genc) { if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) { return createDiffieHellman(prime, 'binary', enc, generator); } enc = enc || 'binary'; genc = genc || 'binary'; generator = generator || new Buffer([2]); if (!Buffer.isBuffer(generator)) { generator = new Buffer(generator, genc); } if (typeof prime === 'number') { return new DH(generatePrime(prime, generator), generator, true); } if (!Buffer.isBuffer(prime)) { prime = new Buffer(prime, enc); } return new DH(prime, generator, true); } exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman; exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman; /***/ }), /***/ 6951: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; var BN = __webpack_require__(6781); var MillerRabin = __webpack_require__(9318); var millerRabin = new MillerRabin(); var TWENTYFOUR = new BN(24); var ELEVEN = new BN(11); var TEN = new BN(10); var THREE = new BN(3); var SEVEN = new BN(7); var primes = __webpack_require__(2227); var randomBytes = __webpack_require__(5760); module.exports = DH; function setPublicKey(pub, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(pub)) { pub = new Buffer(pub, enc); } this._pub = new BN(pub); return this; } function setPrivateKey(priv, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(priv)) { priv = new Buffer(priv, enc); } this._priv = new BN(priv); return this; } var primeCache = {}; function checkPrime(prime, generator) { var gen = generator.toString('hex'); var hex = [gen, prime.toString(16)].join('_'); if (hex in primeCache) { return primeCache[hex]; } var error = 0; if (prime.isEven() || !primes.simpleSieve || !primes.fermatTest(prime) || !millerRabin.test(prime)) { //not a prime so +1 error += 1; if (gen === '02' || gen === '05') { // we'd be able to check the generator // it would fail so +8 error += 8; } else { //we wouldn't be able to test the generator // so +4 error += 4; } primeCache[hex] = error; return error; } if (!millerRabin.test(prime.shrn(1))) { //not a safe prime error += 2; } var rem; switch (gen) { case '02': if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) { // unsuidable generator error += 8; } break; case '05': rem = prime.mod(TEN); if (rem.cmp(THREE) && rem.cmp(SEVEN)) { // prime mod 10 needs to equal 3 or 7 error += 8; } break; default: error += 4; } primeCache[hex] = error; return error; } function DH(prime, generator, malleable) { this.setGenerator(generator); this.__prime = new BN(prime); this._prime = BN.mont(this.__prime); this._primeLen = prime.length; this._pub = undefined; this._priv = undefined; this._primeCode = undefined; if (malleable) { this.setPublicKey = setPublicKey; this.setPrivateKey = setPrivateKey; } else { this._primeCode = 8; } } Object.defineProperty(DH.prototype, 'verifyError', { enumerable: true, get: function get() { if (typeof this._primeCode !== 'number') { this._primeCode = checkPrime(this.__prime, this.__gen); } return this._primeCode; } }); DH.prototype.generateKeys = function () { if (!this._priv) { this._priv = new BN(randomBytes(this._primeLen)); } this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed(); return this.getPublicKey(); }; DH.prototype.computeSecret = function (other) { other = new BN(other); other = other.toRed(this._prime); var secret = other.redPow(this._priv).fromRed(); var out = new Buffer(secret.toArray()); var prime = this.getPrime(); if (out.length < prime.length) { var front = new Buffer(prime.length - out.length); front.fill(0); out = Buffer.concat([front, out]); } return out; }; DH.prototype.getPublicKey = function getPublicKey(enc) { return formatReturnValue(this._pub, enc); }; DH.prototype.getPrivateKey = function getPrivateKey(enc) { return formatReturnValue(this._priv, enc); }; DH.prototype.getPrime = function (enc) { return formatReturnValue(this.__prime, enc); }; DH.prototype.getGenerator = function (enc) { return formatReturnValue(this._gen, enc); }; DH.prototype.setGenerator = function (gen, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(gen)) { gen = new Buffer(gen, enc); } this.__gen = gen; this._gen = new BN(gen); return this; }; function formatReturnValue(bn, enc) { var buf = new Buffer(bn.toArray()); if (!enc) { return buf; } else { return buf.toString(enc); } } /***/ }), /***/ 2227: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var randomBytes = __webpack_require__(5760); module.exports = findPrime; findPrime.simpleSieve = simpleSieve; findPrime.fermatTest = fermatTest; var BN = __webpack_require__(6781); var TWENTYFOUR = new BN(24); var MillerRabin = __webpack_require__(9318); var millerRabin = new MillerRabin(); var ONE = new BN(1); var TWO = new BN(2); var FIVE = new BN(5); var SIXTEEN = new BN(16); var EIGHT = new BN(8); var TEN = new BN(10); var THREE = new BN(3); var SEVEN = new BN(7); var ELEVEN = new BN(11); var FOUR = new BN(4); var TWELVE = new BN(12); var primes = null; function _getPrimes() { if (primes !== null) return primes; var limit = 0x100000; var res = []; res[0] = 2; for (var i = 1, k = 3; k < limit; k += 2) { var sqrt = Math.ceil(Math.sqrt(k)); for (var j = 0; j < i && res[j] <= sqrt; j++) { if (k % res[j] === 0) break; } if (i !== j && res[j] <= sqrt) continue; res[i++] = k; } primes = res; return res; } function simpleSieve(p) { var primes = _getPrimes(); for (var i = 0; i < primes.length; i++) { if (p.modn(primes[i]) === 0) { if (p.cmpn(primes[i]) === 0) { return true; } else { return false; } } } return true; } function fermatTest(p) { var red = BN.mont(p); return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0; } function findPrime(bits, gen) { if (bits < 16) { // this is what openssl does if (gen === 2 || gen === 5) { return new BN([0x8c, 0x7b]); } else { return new BN([0x8c, 0x27]); } } gen = new BN(gen); var num, n2; while (true) { num = new BN(randomBytes(Math.ceil(bits / 8))); while (num.bitLength() > bits) { num.ishrn(1); } if (num.isEven()) { num.iadd(ONE); } if (!num.testn(1)) { num.iadd(TWO); } if (!gen.cmp(TWO)) { while (num.mod(TWENTYFOUR).cmp(ELEVEN)) { num.iadd(FOUR); } } else if (!gen.cmp(FIVE)) { while (num.mod(TEN).cmp(THREE)) { num.iadd(FOUR); } } n2 = num.shrn(1); if (simpleSieve(n2) && simpleSieve(num) && fermatTest(n2) && fermatTest(num) && millerRabin.test(n2) && millerRabin.test(num)) { return num; } } } /***/ }), /***/ 8333: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var elliptic = exports; elliptic.version = (__webpack_require__(8597)/* .version */ .i8); elliptic.utils = __webpack_require__(7891); elliptic.rand = __webpack_require__(7179); elliptic.curve = __webpack_require__(4720); elliptic.curves = __webpack_require__(1478); // Protocols elliptic.ec = __webpack_require__(5806); elliptic.eddsa = __webpack_require__(8318); /***/ }), /***/ 9952: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var BN = __webpack_require__(6781); var utils = __webpack_require__(7891); var getNAF = utils.getNAF; var getJSF = utils.getJSF; var assert = utils.assert; function BaseCurve(type, conf) { this.type = type; this.p = new BN(conf.p, 16); // Use Montgomery, when there is no fast reduction for the prime this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); // Useful for many curves this.zero = new BN(0).toRed(this.red); this.one = new BN(1).toRed(this.red); this.two = new BN(2).toRed(this.red); // Curve configuration, optional this.n = conf.n && new BN(conf.n, 16); this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); // Temporary arrays this._wnafT1 = new Array(4); this._wnafT2 = new Array(4); this._wnafT3 = new Array(4); this._wnafT4 = new Array(4); this._bitLength = this.n ? this.n.bitLength() : 0; // Generalized Greg Maxwell's trick var adjustCount = this.n && this.p.div(this.n); if (!adjustCount || adjustCount.cmpn(100) > 0) { this.redN = null; } else { this._maxwellTrick = true; this.redN = this.n.toRed(this.red); } } module.exports = BaseCurve; BaseCurve.prototype.point = function point() { throw new Error('Not implemented'); }; BaseCurve.prototype.validate = function validate() { throw new Error('Not implemented'); }; BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { assert(p.precomputed); var doubles = p._getDoubles(); var naf = getNAF(k, 1, this._bitLength); var I = (1 << doubles.step + 1) - (doubles.step % 2 === 0 ? 2 : 1); I /= 3; // Translate into more windowed form var repr = []; var j; var nafW; for (j = 0; j < naf.length; j += doubles.step) { nafW = 0; for (var l = j + doubles.step - 1; l >= j; l--) { nafW = (nafW << 1) + naf[l]; } repr.push(nafW); } var a = this.jpoint(null, null, null); var b = this.jpoint(null, null, null); for (var i = I; i > 0; i--) { for (j = 0; j < repr.length; j++) { nafW = repr[j]; if (nafW === i) b = b.mixedAdd(doubles.points[j]);else if (nafW === -i) b = b.mixedAdd(doubles.points[j].neg()); } a = a.add(b); } return a.toP(); }; BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { var w = 4; // Precompute window var nafPoints = p._getNAFPoints(w); w = nafPoints.wnd; var wnd = nafPoints.points; // Get NAF form var naf = getNAF(k, w, this._bitLength); // Add `this`*(N+1) for every w-NAF index var acc = this.jpoint(null, null, null); for (var i = naf.length - 1; i >= 0; i--) { // Count zeroes for (var l = 0; i >= 0 && naf[i] === 0; i--) { l++; } if (i >= 0) l++; acc = acc.dblp(l); if (i < 0) break; var z = naf[i]; assert(z !== 0); if (p.type === 'affine') { // J +- P if (z > 0) acc = acc.mixedAdd(wnd[z - 1 >> 1]);else acc = acc.mixedAdd(wnd[-z - 1 >> 1].neg()); } else { // J +- J if (z > 0) acc = acc.add(wnd[z - 1 >> 1]);else acc = acc.add(wnd[-z - 1 >> 1].neg()); } } return p.type === 'affine' ? acc.toP() : acc; }; BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, points, coeffs, len, jacobianResult) { var wndWidth = this._wnafT1; var wnd = this._wnafT2; var naf = this._wnafT3; // Fill all arrays var max = 0; var i; var j; var p; for (i = 0; i < len; i++) { p = points[i]; var nafPoints = p._getNAFPoints(defW); wndWidth[i] = nafPoints.wnd; wnd[i] = nafPoints.points; } // Comb small window NAFs for (i = len - 1; i >= 1; i -= 2) { var a = i - 1; var b = i; if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength); naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength); max = Math.max(naf[a].length, max); max = Math.max(naf[b].length, max); continue; } var comb = [points[a], /* 1 */ null, /* 3 */ null, /* 5 */ points[b] /* 7 */ ]; // Try to avoid Projective points, if possible if (points[a].y.cmp(points[b].y) === 0) { comb[1] = points[a].add(points[b]); comb[2] = points[a].toJ().mixedAdd(points[b].neg()); } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { comb[1] = points[a].toJ().mixedAdd(points[b]); comb[2] = points[a].add(points[b].neg()); } else { comb[1] = points[a].toJ().mixedAdd(points[b]); comb[2] = points[a].toJ().mixedAdd(points[b].neg()); } var index = [-3, /* -1 -1 */ -1, /* -1 0 */ -5, /* -1 1 */ -7, /* 0 -1 */ 0, /* 0 0 */ 7, /* 0 1 */ 5, /* 1 -1 */ 1, /* 1 0 */ 3 /* 1 1 */ ]; var jsf = getJSF(coeffs[a], coeffs[b]); max = Math.max(jsf[0].length, max); naf[a] = new Array(max); naf[b] = new Array(max); for (j = 0; j < max; j++) { var ja = jsf[0][j] | 0; var jb = jsf[1][j] | 0; naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; naf[b][j] = 0; wnd[a] = comb; } } var acc = this.jpoint(null, null, null); var tmp = this._wnafT4; for (i = max; i >= 0; i--) { var k = 0; while (i >= 0) { var zero = true; for (j = 0; j < len; j++) { tmp[j] = naf[j][i] | 0; if (tmp[j] !== 0) zero = false; } if (!zero) break; k++; i--; } if (i >= 0) k++; acc = acc.dblp(k); if (i < 0) break; for (j = 0; j < len; j++) { var z = tmp[j]; p; if (z === 0) continue;else if (z > 0) p = wnd[j][z - 1 >> 1];else if (z < 0) p = wnd[j][-z - 1 >> 1].neg(); if (p.type === 'affine') acc = acc.mixedAdd(p);else acc = acc.add(p); } } // Zeroify references for (i = 0; i < len; i++) { wnd[i] = null; } if (jacobianResult) return acc;else return acc.toP(); }; function BasePoint(curve, type) { this.curve = curve; this.type = type; this.precomputed = null; } BaseCurve.BasePoint = BasePoint; BasePoint.prototype.eq = function /*other*/ eq() { throw new Error('Not implemented'); }; BasePoint.prototype.validate = function validate() { return this.curve.validate(this); }; BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { bytes = utils.toArray(bytes, enc); var len = this.p.byteLength(); // uncompressed, hybrid-odd, hybrid-even if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && bytes.length - 1 === 2 * len) { if (bytes[0] === 0x06) assert(bytes[bytes.length - 1] % 2 === 0);else if (bytes[0] === 0x07) assert(bytes[bytes.length - 1] % 2 === 1); var res = this.point(bytes.slice(1, 1 + len), bytes.slice(1 + len, 1 + 2 * len)); return res; } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && bytes.length - 1 === len) { return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); } throw new Error('Unknown point format'); }; BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { return this.encode(enc, true); }; BasePoint.prototype._encode = function _encode(compact) { var len = this.curve.p.byteLength(); var x = this.getX().toArray('be', len); if (compact) return [this.getY().isEven() ? 0x02 : 0x03].concat(x); return [0x04].concat(x, this.getY().toArray('be', len)); }; BasePoint.prototype.encode = function encode(enc, compact) { return utils.encode(this._encode(compact), enc); }; BasePoint.prototype.precompute = function precompute(power) { if (this.precomputed) return this; var precomputed = { doubles: null, naf: null, beta: null }; precomputed.naf = this._getNAFPoints(8); precomputed.doubles = this._getDoubles(4, power); precomputed.beta = this._getBeta(); this.precomputed = precomputed; return this; }; BasePoint.prototype._hasDoubles = function _hasDoubles(k) { if (!this.precomputed) return false; var doubles = this.precomputed.doubles; if (!doubles) return false; return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); }; BasePoint.prototype._getDoubles = function _getDoubles(step, power) { if (this.precomputed && this.precomputed.doubles) return this.precomputed.doubles; var doubles = [this]; var acc = this; for (var i = 0; i < power; i += step) { for (var j = 0; j < step; j++) { acc = acc.dbl(); } doubles.push(acc); } return { step: step, points: doubles }; }; BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { if (this.precomputed && this.precomputed.naf) return this.precomputed.naf; var res = [this]; var max = (1 << wnd) - 1; var dbl = max === 1 ? null : this.dbl(); for (var i = 1; i < max; i++) { res[i] = res[i - 1].add(dbl); } return { wnd: wnd, points: res }; }; BasePoint.prototype._getBeta = function _getBeta() { return null; }; BasePoint.prototype.dblp = function dblp(k) { var r = this; for (var i = 0; i < k; i++) { r = r.dbl(); } return r; }; /***/ }), /***/ 5970: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(7891); var BN = __webpack_require__(6781); var inherits = __webpack_require__(376); var Base = __webpack_require__(9952); var assert = utils.assert; function EdwardsCurve(conf) { // NOTE: Important as we are creating point in Base.call() this.twisted = (conf.a | 0) !== 1; this.mOneA = this.twisted && (conf.a | 0) === -1; this.extended = this.mOneA; Base.call(this, 'edwards', conf); this.a = new BN(conf.a, 16).umod(this.red.m); this.a = this.a.toRed(this.red); this.c = new BN(conf.c, 16).toRed(this.red); this.c2 = this.c.redSqr(); this.d = new BN(conf.d, 16).toRed(this.red); this.dd = this.d.redAdd(this.d); assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); this.oneC = (conf.c | 0) === 1; } inherits(EdwardsCurve, Base); module.exports = EdwardsCurve; EdwardsCurve.prototype._mulA = function _mulA(num) { if (this.mOneA) return num.redNeg();else return this.a.redMul(num); }; EdwardsCurve.prototype._mulC = function _mulC(num) { if (this.oneC) return num;else return this.c.redMul(num); }; // Just for compatibility with Short curve EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { return this.point(x, y, z, t); }; EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { x = new BN(x, 16); if (!x.red) x = x.toRed(this.red); var x2 = x.redSqr(); var rhs = this.c2.redSub(this.a.redMul(x2)); var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); var y2 = rhs.redMul(lhs.redInvm()); var y = y2.redSqrt(); if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) throw new Error('invalid point'); var isOdd = y.fromRed().isOdd(); if (odd && !isOdd || !odd && isOdd) y = y.redNeg(); return this.point(x, y); }; EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { y = new BN(y, 16); if (!y.red) y = y.toRed(this.red); // x^2 = (y^2 - c^2) / (c^2 d y^2 - a) var y2 = y.redSqr(); var lhs = y2.redSub(this.c2); var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); var x2 = lhs.redMul(rhs.redInvm()); if (x2.cmp(this.zero) === 0) { if (odd) throw new Error('invalid point');else return this.point(this.zero, y); } var x = x2.redSqrt(); if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) throw new Error('invalid point'); if (x.fromRed().isOdd() !== odd) x = x.redNeg(); return this.point(x, y); }; EdwardsCurve.prototype.validate = function validate(point) { if (point.isInfinity()) return true; // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) point.normalize(); var x2 = point.x.redSqr(); var y2 = point.y.redSqr(); var lhs = x2.redMul(this.a).redAdd(y2); var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); return lhs.cmp(rhs) === 0; }; function Point(curve, x, y, z, t) { Base.BasePoint.call(this, curve, 'projective'); if (x === null && y === null && z === null) { this.x = this.curve.zero; this.y = this.curve.one; this.z = this.curve.one; this.t = this.curve.zero; this.zOne = true; } else { this.x = new BN(x, 16); this.y = new BN(y, 16); this.z = z ? new BN(z, 16) : this.curve.one; this.t = t && new BN(t, 16); if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.y.red) this.y = this.y.toRed(this.curve.red); if (!this.z.red) this.z = this.z.toRed(this.curve.red); if (this.t && !this.t.red) this.t = this.t.toRed(this.curve.red); this.zOne = this.z === this.curve.one; // Use extended coordinates if (this.curve.extended && !this.t) { this.t = this.x.redMul(this.y); if (!this.zOne) this.t = this.t.redMul(this.z.redInvm()); } } } inherits(Point, Base.BasePoint); EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { return Point.fromJSON(this, obj); }; EdwardsCurve.prototype.point = function point(x, y, z, t) { return new Point(this, x, y, z, t); }; Point.fromJSON = function fromJSON(curve, obj) { return new Point(curve, obj[0], obj[1], obj[2]); }; Point.prototype.inspect = function inspect() { if (this.isInfinity()) return ''; return ''; }; Point.prototype.isInfinity = function isInfinity() { // XXX This code assumes that zero is always zero in red return this.x.cmpn(0) === 0 && (this.y.cmp(this.z) === 0 || this.zOne && this.y.cmp(this.curve.c) === 0); }; Point.prototype._extDbl = function _extDbl() { // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html // #doubling-dbl-2008-hwcd // 4M + 4S // A = X1^2 var a = this.x.redSqr(); // B = Y1^2 var b = this.y.redSqr(); // C = 2 * Z1^2 var c = this.z.redSqr(); c = c.redIAdd(c); // D = a * A var d = this.curve._mulA(a); // E = (X1 + Y1)^2 - A - B var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); // G = D + B var g = d.redAdd(b); // F = G - C var f = g.redSub(c); // H = D - B var h = d.redSub(b); // X3 = E * F var nx = e.redMul(f); // Y3 = G * H var ny = g.redMul(h); // T3 = E * H var nt = e.redMul(h); // Z3 = F * G var nz = f.redMul(g); return this.curve.point(nx, ny, nz, nt); }; Point.prototype._projDbl = function _projDbl() { // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html // #doubling-dbl-2008-bbjlp // #doubling-dbl-2007-bl // and others // Generally 3M + 4S or 2M + 4S // B = (X1 + Y1)^2 var b = this.x.redAdd(this.y).redSqr(); // C = X1^2 var c = this.x.redSqr(); // D = Y1^2 var d = this.y.redSqr(); var nx; var ny; var nz; var e; var h; var j; if (this.curve.twisted) { // E = a * C e = this.curve._mulA(c); // F = E + D var f = e.redAdd(d); if (this.zOne) { // X3 = (B - C - D) * (F - 2) nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); // Y3 = F * (E - D) ny = f.redMul(e.redSub(d)); // Z3 = F^2 - 2 * F nz = f.redSqr().redSub(f).redSub(f); } else { // H = Z1^2 h = this.z.redSqr(); // J = F - 2 * H j = f.redSub(h).redISub(h); // X3 = (B-C-D)*J nx = b.redSub(c).redISub(d).redMul(j); // Y3 = F * (E - D) ny = f.redMul(e.redSub(d)); // Z3 = F * J nz = f.redMul(j); } } else { // E = C + D e = c.redAdd(d); // H = (c * Z1)^2 h = this.curve._mulC(this.z).redSqr(); // J = E - 2 * H j = e.redSub(h).redSub(h); // X3 = c * (B - E) * J nx = this.curve._mulC(b.redISub(e)).redMul(j); // Y3 = c * E * (C - D) ny = this.curve._mulC(e).redMul(c.redISub(d)); // Z3 = E * J nz = e.redMul(j); } return this.curve.point(nx, ny, nz); }; Point.prototype.dbl = function dbl() { if (this.isInfinity()) return this; // Double in extended coordinates if (this.curve.extended) return this._extDbl();else return this._projDbl(); }; Point.prototype._extAdd = function _extAdd(p) { // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html // #addition-add-2008-hwcd-3 // 8M // A = (Y1 - X1) * (Y2 - X2) var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); // B = (Y1 + X1) * (Y2 + X2) var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); // C = T1 * k * T2 var c = this.t.redMul(this.curve.dd).redMul(p.t); // D = Z1 * 2 * Z2 var d = this.z.redMul(p.z.redAdd(p.z)); // E = B - A var e = b.redSub(a); // F = D - C var f = d.redSub(c); // G = D + C var g = d.redAdd(c); // H = B + A var h = b.redAdd(a); // X3 = E * F var nx = e.redMul(f); // Y3 = G * H var ny = g.redMul(h); // T3 = E * H var nt = e.redMul(h); // Z3 = F * G var nz = f.redMul(g); return this.curve.point(nx, ny, nz, nt); }; Point.prototype._projAdd = function _projAdd(p) { // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html // #addition-add-2008-bbjlp // #addition-add-2007-bl // 10M + 1S // A = Z1 * Z2 var a = this.z.redMul(p.z); // B = A^2 var b = a.redSqr(); // C = X1 * X2 var c = this.x.redMul(p.x); // D = Y1 * Y2 var d = this.y.redMul(p.y); // E = d * C * D var e = this.curve.d.redMul(c).redMul(d); // F = B - E var f = b.redSub(e); // G = B + E var g = b.redAdd(e); // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); var nx = a.redMul(f).redMul(tmp); var ny; var nz; if (this.curve.twisted) { // Y3 = A * G * (D - a * C) ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); // Z3 = F * G nz = f.redMul(g); } else { // Y3 = A * G * (D - C) ny = a.redMul(g).redMul(d.redSub(c)); // Z3 = c * F * G nz = this.curve._mulC(f).redMul(g); } return this.curve.point(nx, ny, nz); }; Point.prototype.add = function add(p) { if (this.isInfinity()) return p; if (p.isInfinity()) return this; if (this.curve.extended) return this._extAdd(p);else return this._projAdd(p); }; Point.prototype.mul = function mul(k) { if (this._hasDoubles(k)) return this.curve._fixedNafMul(this, k);else return this.curve._wnafMul(this, k); }; Point.prototype.mulAdd = function mulAdd(k1, p, k2) { return this.curve._wnafMulAdd(1, [this, p], [k1, k2], 2, false); }; Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { return this.curve._wnafMulAdd(1, [this, p], [k1, k2], 2, true); }; Point.prototype.normalize = function normalize() { if (this.zOne) return this; // Normalize coordinates var zi = this.z.redInvm(); this.x = this.x.redMul(zi); this.y = this.y.redMul(zi); if (this.t) this.t = this.t.redMul(zi); this.z = this.curve.one; this.zOne = true; return this; }; Point.prototype.neg = function neg() { return this.curve.point(this.x.redNeg(), this.y, this.z, this.t && this.t.redNeg()); }; Point.prototype.getX = function getX() { this.normalize(); return this.x.fromRed(); }; Point.prototype.getY = function getY() { this.normalize(); return this.y.fromRed(); }; Point.prototype.eq = function eq(other) { return this === other || this.getX().cmp(other.getX()) === 0 && this.getY().cmp(other.getY()) === 0; }; Point.prototype.eqXToP = function eqXToP(x) { var rx = x.toRed(this.curve.red).redMul(this.z); if (this.x.cmp(rx) === 0) return true; var xc = x.clone(); var t = this.curve.redN.redMul(this.z); for (;;) { xc.iadd(this.curve.n); if (xc.cmp(this.curve.p) >= 0) return false; rx.redIAdd(t); if (this.x.cmp(rx) === 0) return true; } }; // Compatibility with BaseCurve Point.prototype.toP = Point.prototype.normalize; Point.prototype.mixedAdd = Point.prototype.add; /***/ }), /***/ 4720: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var curve = exports; curve.base = __webpack_require__(9952); curve["short"] = __webpack_require__(1585); curve.mont = __webpack_require__(6773); curve.edwards = __webpack_require__(5970); /***/ }), /***/ 6773: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var BN = __webpack_require__(6781); var inherits = __webpack_require__(376); var Base = __webpack_require__(9952); var utils = __webpack_require__(7891); function MontCurve(conf) { Base.call(this, 'mont', conf); this.a = new BN(conf.a, 16).toRed(this.red); this.b = new BN(conf.b, 16).toRed(this.red); this.i4 = new BN(4).toRed(this.red).redInvm(); this.two = new BN(2).toRed(this.red); this.a24 = this.i4.redMul(this.a.redAdd(this.two)); } inherits(MontCurve, Base); module.exports = MontCurve; MontCurve.prototype.validate = function validate(point) { var x = point.normalize().x; var x2 = x.redSqr(); var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); var y = rhs.redSqrt(); return y.redSqr().cmp(rhs) === 0; }; function Point(curve, x, z) { Base.BasePoint.call(this, curve, 'projective'); if (x === null && z === null) { this.x = this.curve.one; this.z = this.curve.zero; } else { this.x = new BN(x, 16); this.z = new BN(z, 16); if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.z.red) this.z = this.z.toRed(this.curve.red); } } inherits(Point, Base.BasePoint); MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { return this.point(utils.toArray(bytes, enc), 1); }; MontCurve.prototype.point = function point(x, z) { return new Point(this, x, z); }; MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { return Point.fromJSON(this, obj); }; Point.prototype.precompute = function precompute() {// No-op }; Point.prototype._encode = function _encode() { return this.getX().toArray('be', this.curve.p.byteLength()); }; Point.fromJSON = function fromJSON(curve, obj) { return new Point(curve, obj[0], obj[1] || curve.one); }; Point.prototype.inspect = function inspect() { if (this.isInfinity()) return ''; return ''; }; Point.prototype.isInfinity = function isInfinity() { // XXX This code assumes that zero is always zero in red return this.z.cmpn(0) === 0; }; Point.prototype.dbl = function dbl() { // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 // 2M + 2S + 4A // A = X1 + Z1 var a = this.x.redAdd(this.z); // AA = A^2 var aa = a.redSqr(); // B = X1 - Z1 var b = this.x.redSub(this.z); // BB = B^2 var bb = b.redSqr(); // C = AA - BB var c = aa.redSub(bb); // X3 = AA * BB var nx = aa.redMul(bb); // Z3 = C * (BB + A24 * C) var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); return this.curve.point(nx, nz); }; Point.prototype.add = function add() { throw new Error('Not supported on Montgomery curve'); }; Point.prototype.diffAdd = function diffAdd(p, diff) { // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 // 4M + 2S + 6A // A = X2 + Z2 var a = this.x.redAdd(this.z); // B = X2 - Z2 var b = this.x.redSub(this.z); // C = X3 + Z3 var c = p.x.redAdd(p.z); // D = X3 - Z3 var d = p.x.redSub(p.z); // DA = D * A var da = d.redMul(a); // CB = C * B var cb = c.redMul(b); // X5 = Z1 * (DA + CB)^2 var nx = diff.z.redMul(da.redAdd(cb).redSqr()); // Z5 = X1 * (DA - CB)^2 var nz = diff.x.redMul(da.redISub(cb).redSqr()); return this.curve.point(nx, nz); }; Point.prototype.mul = function mul(k) { var t = k.clone(); var a = this; // (N / 2) * Q + Q var b = this.curve.point(null, null); // (N / 2) * Q var c = this; // Q for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) { bits.push(t.andln(1)); } for (var i = bits.length - 1; i >= 0; i--) { if (bits[i] === 0) { // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q a = a.diffAdd(b, c); // N * Q = 2 * ((N / 2) * Q + Q)) b = b.dbl(); } else { // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) b = a.diffAdd(b, c); // N * Q + Q = 2 * ((N / 2) * Q + Q) a = a.dbl(); } } return b; }; Point.prototype.mulAdd = function mulAdd() { throw new Error('Not supported on Montgomery curve'); }; Point.prototype.jumlAdd = function jumlAdd() { throw new Error('Not supported on Montgomery curve'); }; Point.prototype.eq = function eq(other) { return this.getX().cmp(other.getX()) === 0; }; Point.prototype.normalize = function normalize() { this.x = this.x.redMul(this.z.redInvm()); this.z = this.curve.one; return this; }; Point.prototype.getX = function getX() { // Normalize coordinates this.normalize(); return this.x.fromRed(); }; /***/ }), /***/ 1585: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(7891); var BN = __webpack_require__(6781); var inherits = __webpack_require__(376); var Base = __webpack_require__(9952); var assert = utils.assert; function ShortCurve(conf) { Base.call(this, 'short', conf); this.a = new BN(conf.a, 16).toRed(this.red); this.b = new BN(conf.b, 16).toRed(this.red); this.tinv = this.two.redInvm(); this.zeroA = this.a.fromRed().cmpn(0) === 0; this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; // If the curve is endomorphic, precalculate beta and lambda this.endo = this._getEndomorphism(conf); this._endoWnafT1 = new Array(4); this._endoWnafT2 = new Array(4); } inherits(ShortCurve, Base); module.exports = ShortCurve; ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { // No efficient endomorphism if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) return; // Compute beta and lambda, that lambda * P = (beta * Px; Py) var beta; var lambda; if (conf.beta) { beta = new BN(conf.beta, 16).toRed(this.red); } else { var betas = this._getEndoRoots(this.p); // Choose the smallest beta beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; beta = beta.toRed(this.red); } if (conf.lambda) { lambda = new BN(conf.lambda, 16); } else { // Choose the lambda that is matching selected beta var lambdas = this._getEndoRoots(this.n); if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { lambda = lambdas[0]; } else { lambda = lambdas[1]; assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); } } // Get basis vectors, used for balanced length-two representation var basis; if (conf.basis) { basis = conf.basis.map(function (vec) { return { a: new BN(vec.a, 16), b: new BN(vec.b, 16) }; }); } else { basis = this._getEndoBasis(lambda); } return { beta: beta, lambda: lambda, basis: basis }; }; ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { // Find roots of for x^2 + x + 1 in F // Root = (-1 +- Sqrt(-3)) / 2 // var red = num === this.p ? this.red : BN.mont(num); var tinv = new BN(2).toRed(red).redInvm(); var ntinv = tinv.redNeg(); var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); var l1 = ntinv.redAdd(s).fromRed(); var l2 = ntinv.redSub(s).fromRed(); return [l1, l2]; }; ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { // aprxSqrt >= sqrt(this.n) var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); // 3.74 // Run EGCD, until r(L + 1) < aprxSqrt var u = lambda; var v = this.n.clone(); var x1 = new BN(1); var y1 = new BN(0); var x2 = new BN(0); var y2 = new BN(1); // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) var a0; var b0; // First vector var a1; var b1; // Second vector var a2; var b2; var prevR; var i = 0; var r; var x; while (u.cmpn(0) !== 0) { var q = v.div(u); r = v.sub(q.mul(u)); x = x2.sub(q.mul(x1)); var y = y2.sub(q.mul(y1)); if (!a1 && r.cmp(aprxSqrt) < 0) { a0 = prevR.neg(); b0 = x1; a1 = r.neg(); b1 = x; } else if (a1 && ++i === 2) { break; } prevR = r; v = u; u = r; x2 = x1; x1 = x; y2 = y1; y1 = y; } a2 = r.neg(); b2 = x; var len1 = a1.sqr().add(b1.sqr()); var len2 = a2.sqr().add(b2.sqr()); if (len2.cmp(len1) >= 0) { a2 = a0; b2 = b0; } // Normalize signs if (a1.negative) { a1 = a1.neg(); b1 = b1.neg(); } if (a2.negative) { a2 = a2.neg(); b2 = b2.neg(); } return [{ a: a1, b: b1 }, { a: a2, b: b2 }]; }; ShortCurve.prototype._endoSplit = function _endoSplit(k) { var basis = this.endo.basis; var v1 = basis[0]; var v2 = basis[1]; var c1 = v2.b.mul(k).divRound(this.n); var c2 = v1.b.neg().mul(k).divRound(this.n); var p1 = c1.mul(v1.a); var p2 = c2.mul(v2.a); var q1 = c1.mul(v1.b); var q2 = c2.mul(v2.b); // Calculate answer var k1 = k.sub(p1).sub(p2); var k2 = q1.add(q2).neg(); return { k1: k1, k2: k2 }; }; ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { x = new BN(x, 16); if (!x.red) x = x.toRed(this.red); var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); var y = y2.redSqrt(); if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) throw new Error('invalid point'); // XXX Is there any way to tell if the number is odd without converting it // to non-red form? var isOdd = y.fromRed().isOdd(); if (odd && !isOdd || !odd && isOdd) y = y.redNeg(); return this.point(x, y); }; ShortCurve.prototype.validate = function validate(point) { if (point.inf) return true; var x = point.x; var y = point.y; var ax = this.a.redMul(x); var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); return y.redSqr().redISub(rhs).cmpn(0) === 0; }; ShortCurve.prototype._endoWnafMulAdd = function _endoWnafMulAdd(points, coeffs, jacobianResult) { var npoints = this._endoWnafT1; var ncoeffs = this._endoWnafT2; for (var i = 0; i < points.length; i++) { var split = this._endoSplit(coeffs[i]); var p = points[i]; var beta = p._getBeta(); if (split.k1.negative) { split.k1.ineg(); p = p.neg(true); } if (split.k2.negative) { split.k2.ineg(); beta = beta.neg(true); } npoints[i * 2] = p; npoints[i * 2 + 1] = beta; ncoeffs[i * 2] = split.k1; ncoeffs[i * 2 + 1] = split.k2; } var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); // Clean-up references to points and coefficients for (var j = 0; j < i * 2; j++) { npoints[j] = null; ncoeffs[j] = null; } return res; }; function Point(curve, x, y, isRed) { Base.BasePoint.call(this, curve, 'affine'); if (x === null && y === null) { this.x = null; this.y = null; this.inf = true; } else { this.x = new BN(x, 16); this.y = new BN(y, 16); // Force redgomery representation when loading from JSON if (isRed) { this.x.forceRed(this.curve.red); this.y.forceRed(this.curve.red); } if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.y.red) this.y = this.y.toRed(this.curve.red); this.inf = false; } } inherits(Point, Base.BasePoint); ShortCurve.prototype.point = function point(x, y, isRed) { return new Point(this, x, y, isRed); }; ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { return Point.fromJSON(this, obj, red); }; Point.prototype._getBeta = function _getBeta() { if (!this.curve.endo) return; var pre = this.precomputed; if (pre && pre.beta) return pre.beta; var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); if (pre) { var curve = this.curve; var endoMul = function endoMul(p) { return curve.point(p.x.redMul(curve.endo.beta), p.y); }; pre.beta = beta; beta.precomputed = { beta: null, naf: pre.naf && { wnd: pre.naf.wnd, points: pre.naf.points.map(endoMul) }, doubles: pre.doubles && { step: pre.doubles.step, points: pre.doubles.points.map(endoMul) } }; } return beta; }; Point.prototype.toJSON = function toJSON() { if (!this.precomputed) return [this.x, this.y]; return [this.x, this.y, this.precomputed && { doubles: this.precomputed.doubles && { step: this.precomputed.doubles.step, points: this.precomputed.doubles.points.slice(1) }, naf: this.precomputed.naf && { wnd: this.precomputed.naf.wnd, points: this.precomputed.naf.points.slice(1) } }]; }; Point.fromJSON = function fromJSON(curve, obj, red) { if (typeof obj === 'string') obj = JSON.parse(obj); var res = curve.point(obj[0], obj[1], red); if (!obj[2]) return res; function obj2point(obj) { return curve.point(obj[0], obj[1], red); } var pre = obj[2]; res.precomputed = { beta: null, doubles: pre.doubles && { step: pre.doubles.step, points: [res].concat(pre.doubles.points.map(obj2point)) }, naf: pre.naf && { wnd: pre.naf.wnd, points: [res].concat(pre.naf.points.map(obj2point)) } }; return res; }; Point.prototype.inspect = function inspect() { if (this.isInfinity()) return ''; return ''; }; Point.prototype.isInfinity = function isInfinity() { return this.inf; }; Point.prototype.add = function add(p) { // O + P = P if (this.inf) return p; // P + O = P if (p.inf) return this; // P + P = 2P if (this.eq(p)) return this.dbl(); // P + (-P) = O if (this.neg().eq(p)) return this.curve.point(null, null); // P + Q = O if (this.x.cmp(p.x) === 0) return this.curve.point(null, null); var c = this.y.redSub(p.y); if (c.cmpn(0) !== 0) c = c.redMul(this.x.redSub(p.x).redInvm()); var nx = c.redSqr().redISub(this.x).redISub(p.x); var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); return this.curve.point(nx, ny); }; Point.prototype.dbl = function dbl() { if (this.inf) return this; // 2P = O var ys1 = this.y.redAdd(this.y); if (ys1.cmpn(0) === 0) return this.curve.point(null, null); var a = this.curve.a; var x2 = this.x.redSqr(); var dyinv = ys1.redInvm(); var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); var nx = c.redSqr().redISub(this.x.redAdd(this.x)); var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); return this.curve.point(nx, ny); }; Point.prototype.getX = function getX() { return this.x.fromRed(); }; Point.prototype.getY = function getY() { return this.y.fromRed(); }; Point.prototype.mul = function mul(k) { k = new BN(k, 16); if (this.isInfinity()) return this;else if (this._hasDoubles(k)) return this.curve._fixedNafMul(this, k);else if (this.curve.endo) return this.curve._endoWnafMulAdd([this], [k]);else return this.curve._wnafMul(this, k); }; Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { var points = [this, p2]; var coeffs = [k1, k2]; if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs);else return this.curve._wnafMulAdd(1, points, coeffs, 2); }; Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { var points = [this, p2]; var coeffs = [k1, k2]; if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs, true);else return this.curve._wnafMulAdd(1, points, coeffs, 2, true); }; Point.prototype.eq = function eq(p) { return this === p || this.inf === p.inf && (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); }; Point.prototype.neg = function neg(_precompute) { if (this.inf) return this; var res = this.curve.point(this.x, this.y.redNeg()); if (_precompute && this.precomputed) { var pre = this.precomputed; var negate = function negate(p) { return p.neg(); }; res.precomputed = { naf: pre.naf && { wnd: pre.naf.wnd, points: pre.naf.points.map(negate) }, doubles: pre.doubles && { step: pre.doubles.step, points: pre.doubles.points.map(negate) } }; } return res; }; Point.prototype.toJ = function toJ() { if (this.inf) return this.curve.jpoint(null, null, null); var res = this.curve.jpoint(this.x, this.y, this.curve.one); return res; }; function JPoint(curve, x, y, z) { Base.BasePoint.call(this, curve, 'jacobian'); if (x === null && y === null && z === null) { this.x = this.curve.one; this.y = this.curve.one; this.z = new BN(0); } else { this.x = new BN(x, 16); this.y = new BN(y, 16); this.z = new BN(z, 16); } if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.y.red) this.y = this.y.toRed(this.curve.red); if (!this.z.red) this.z = this.z.toRed(this.curve.red); this.zOne = this.z === this.curve.one; } inherits(JPoint, Base.BasePoint); ShortCurve.prototype.jpoint = function jpoint(x, y, z) { return new JPoint(this, x, y, z); }; JPoint.prototype.toP = function toP() { if (this.isInfinity()) return this.curve.point(null, null); var zinv = this.z.redInvm(); var zinv2 = zinv.redSqr(); var ax = this.x.redMul(zinv2); var ay = this.y.redMul(zinv2).redMul(zinv); return this.curve.point(ax, ay); }; JPoint.prototype.neg = function neg() { return this.curve.jpoint(this.x, this.y.redNeg(), this.z); }; JPoint.prototype.add = function add(p) { // O + P = P if (this.isInfinity()) return p; // P + O = P if (p.isInfinity()) return this; // 12M + 4S + 7A var pz2 = p.z.redSqr(); var z2 = this.z.redSqr(); var u1 = this.x.redMul(pz2); var u2 = p.x.redMul(z2); var s1 = this.y.redMul(pz2.redMul(p.z)); var s2 = p.y.redMul(z2.redMul(this.z)); var h = u1.redSub(u2); var r = s1.redSub(s2); if (h.cmpn(0) === 0) { if (r.cmpn(0) !== 0) return this.curve.jpoint(null, null, null);else return this.dbl(); } var h2 = h.redSqr(); var h3 = h2.redMul(h); var v = u1.redMul(h2); var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); var nz = this.z.redMul(p.z).redMul(h); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.mixedAdd = function mixedAdd(p) { // O + P = P if (this.isInfinity()) return p.toJ(); // P + O = P if (p.isInfinity()) return this; // 8M + 3S + 7A var z2 = this.z.redSqr(); var u1 = this.x; var u2 = p.x.redMul(z2); var s1 = this.y; var s2 = p.y.redMul(z2).redMul(this.z); var h = u1.redSub(u2); var r = s1.redSub(s2); if (h.cmpn(0) === 0) { if (r.cmpn(0) !== 0) return this.curve.jpoint(null, null, null);else return this.dbl(); } var h2 = h.redSqr(); var h3 = h2.redMul(h); var v = u1.redMul(h2); var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); var nz = this.z.redMul(h); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.dblp = function dblp(pow) { if (pow === 0) return this; if (this.isInfinity()) return this; if (!pow) return this.dbl(); var i; if (this.curve.zeroA || this.curve.threeA) { var r = this; for (i = 0; i < pow; i++) { r = r.dbl(); } return r; } // 1M + 2S + 1A + N * (4S + 5M + 8A) // N = 1 => 6M + 6S + 9A var a = this.curve.a; var tinv = this.curve.tinv; var jx = this.x; var jy = this.y; var jz = this.z; var jz4 = jz.redSqr().redSqr(); // Reuse results var jyd = jy.redAdd(jy); for (i = 0; i < pow; i++) { var jx2 = jx.redSqr(); var jyd2 = jyd.redSqr(); var jyd4 = jyd2.redSqr(); var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); var t1 = jx.redMul(jyd2); var nx = c.redSqr().redISub(t1.redAdd(t1)); var t2 = t1.redISub(nx); var dny = c.redMul(t2); dny = dny.redIAdd(dny).redISub(jyd4); var nz = jyd.redMul(jz); if (i + 1 < pow) jz4 = jz4.redMul(jyd4); jx = nx; jz = nz; jyd = dny; } return this.curve.jpoint(jx, jyd.redMul(tinv), jz); }; JPoint.prototype.dbl = function dbl() { if (this.isInfinity()) return this; if (this.curve.zeroA) return this._zeroDbl();else if (this.curve.threeA) return this._threeDbl();else return this._dbl(); }; JPoint.prototype._zeroDbl = function _zeroDbl() { var nx; var ny; var nz; // Z = 1 if (this.zOne) { // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html // #doubling-mdbl-2007-bl // 1M + 5S + 14A // XX = X1^2 var xx = this.x.redSqr(); // YY = Y1^2 var yy = this.y.redSqr(); // YYYY = YY^2 var yyyy = yy.redSqr(); // S = 2 * ((X1 + YY)^2 - XX - YYYY) var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); s = s.redIAdd(s); // M = 3 * XX + a; a = 0 var m = xx.redAdd(xx).redIAdd(xx); // T = M ^ 2 - 2*S var t = m.redSqr().redISub(s).redISub(s); // 8 * YYYY var yyyy8 = yyyy.redIAdd(yyyy); yyyy8 = yyyy8.redIAdd(yyyy8); yyyy8 = yyyy8.redIAdd(yyyy8); // X3 = T nx = t; // Y3 = M * (S - T) - 8 * YYYY ny = m.redMul(s.redISub(t)).redISub(yyyy8); // Z3 = 2*Y1 nz = this.y.redAdd(this.y); } else { // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html // #doubling-dbl-2009-l // 2M + 5S + 13A // A = X1^2 var a = this.x.redSqr(); // B = Y1^2 var b = this.y.redSqr(); // C = B^2 var c = b.redSqr(); // D = 2 * ((X1 + B)^2 - A - C) var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); d = d.redIAdd(d); // E = 3 * A var e = a.redAdd(a).redIAdd(a); // F = E^2 var f = e.redSqr(); // 8 * C var c8 = c.redIAdd(c); c8 = c8.redIAdd(c8); c8 = c8.redIAdd(c8); // X3 = F - 2 * D nx = f.redISub(d).redISub(d); // Y3 = E * (D - X3) - 8 * C ny = e.redMul(d.redISub(nx)).redISub(c8); // Z3 = 2 * Y1 * Z1 nz = this.y.redMul(this.z); nz = nz.redIAdd(nz); } return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype._threeDbl = function _threeDbl() { var nx; var ny; var nz; // Z = 1 if (this.zOne) { // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html // #doubling-mdbl-2007-bl // 1M + 5S + 15A // XX = X1^2 var xx = this.x.redSqr(); // YY = Y1^2 var yy = this.y.redSqr(); // YYYY = YY^2 var yyyy = yy.redSqr(); // S = 2 * ((X1 + YY)^2 - XX - YYYY) var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); s = s.redIAdd(s); // M = 3 * XX + a var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); // T = M^2 - 2 * S var t = m.redSqr().redISub(s).redISub(s); // X3 = T nx = t; // Y3 = M * (S - T) - 8 * YYYY var yyyy8 = yyyy.redIAdd(yyyy); yyyy8 = yyyy8.redIAdd(yyyy8); yyyy8 = yyyy8.redIAdd(yyyy8); ny = m.redMul(s.redISub(t)).redISub(yyyy8); // Z3 = 2 * Y1 nz = this.y.redAdd(this.y); } else { // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b // 3M + 5S // delta = Z1^2 var delta = this.z.redSqr(); // gamma = Y1^2 var gamma = this.y.redSqr(); // beta = X1 * gamma var beta = this.x.redMul(gamma); // alpha = 3 * (X1 - delta) * (X1 + delta) var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); alpha = alpha.redAdd(alpha).redIAdd(alpha); // X3 = alpha^2 - 8 * beta var beta4 = beta.redIAdd(beta); beta4 = beta4.redIAdd(beta4); var beta8 = beta4.redAdd(beta4); nx = alpha.redSqr().redISub(beta8); // Z3 = (Y1 + Z1)^2 - gamma - delta nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 var ggamma8 = gamma.redSqr(); ggamma8 = ggamma8.redIAdd(ggamma8); ggamma8 = ggamma8.redIAdd(ggamma8); ggamma8 = ggamma8.redIAdd(ggamma8); ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); } return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype._dbl = function _dbl() { var a = this.curve.a; // 4M + 6S + 10A var jx = this.x; var jy = this.y; var jz = this.z; var jz4 = jz.redSqr().redSqr(); var jx2 = jx.redSqr(); var jy2 = jy.redSqr(); var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); var jxd4 = jx.redAdd(jx); jxd4 = jxd4.redIAdd(jxd4); var t1 = jxd4.redMul(jy2); var nx = c.redSqr().redISub(t1.redAdd(t1)); var t2 = t1.redISub(nx); var jyd8 = jy2.redSqr(); jyd8 = jyd8.redIAdd(jyd8); jyd8 = jyd8.redIAdd(jyd8); jyd8 = jyd8.redIAdd(jyd8); var ny = c.redMul(t2).redISub(jyd8); var nz = jy.redAdd(jy).redMul(jz); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.trpl = function trpl() { if (!this.curve.zeroA) return this.dbl().add(this); // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl // 5M + 10S + ... // XX = X1^2 var xx = this.x.redSqr(); // YY = Y1^2 var yy = this.y.redSqr(); // ZZ = Z1^2 var zz = this.z.redSqr(); // YYYY = YY^2 var yyyy = yy.redSqr(); // M = 3 * XX + a * ZZ2; a = 0 var m = xx.redAdd(xx).redIAdd(xx); // MM = M^2 var mm = m.redSqr(); // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); e = e.redIAdd(e); e = e.redAdd(e).redIAdd(e); e = e.redISub(mm); // EE = E^2 var ee = e.redSqr(); // T = 16*YYYY var t = yyyy.redIAdd(yyyy); t = t.redIAdd(t); t = t.redIAdd(t); t = t.redIAdd(t); // U = (M + E)^2 - MM - EE - T var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); // X3 = 4 * (X1 * EE - 4 * YY * U) var yyu4 = yy.redMul(u); yyu4 = yyu4.redIAdd(yyu4); yyu4 = yyu4.redIAdd(yyu4); var nx = this.x.redMul(ee).redISub(yyu4); nx = nx.redIAdd(nx); nx = nx.redIAdd(nx); // Y3 = 8 * Y1 * (U * (T - U) - E * EE) var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); ny = ny.redIAdd(ny); ny = ny.redIAdd(ny); ny = ny.redIAdd(ny); // Z3 = (Z1 + E)^2 - ZZ - EE var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.mul = function mul(k, kbase) { k = new BN(k, kbase); return this.curve._wnafMul(this, k); }; JPoint.prototype.eq = function eq(p) { if (p.type === 'affine') return this.eq(p.toJ()); if (this === p) return true; // x1 * z2^2 == x2 * z1^2 var z2 = this.z.redSqr(); var pz2 = p.z.redSqr(); if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) return false; // y1 * z2^3 == y2 * z1^3 var z3 = z2.redMul(this.z); var pz3 = pz2.redMul(p.z); return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; }; JPoint.prototype.eqXToP = function eqXToP(x) { var zs = this.z.redSqr(); var rx = x.toRed(this.curve.red).redMul(zs); if (this.x.cmp(rx) === 0) return true; var xc = x.clone(); var t = this.curve.redN.redMul(zs); for (;;) { xc.iadd(this.curve.n); if (xc.cmp(this.curve.p) >= 0) return false; rx.redIAdd(t); if (this.x.cmp(rx) === 0) return true; } }; JPoint.prototype.inspect = function inspect() { if (this.isInfinity()) return ''; return ''; }; JPoint.prototype.isInfinity = function isInfinity() { // XXX This code assumes that zero is always zero in red return this.z.cmpn(0) === 0; }; /***/ }), /***/ 1478: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var curves = exports; var hash = __webpack_require__(3192); var curve = __webpack_require__(4720); var utils = __webpack_require__(7891); var assert = utils.assert; function PresetCurve(options) { if (options.type === 'short') this.curve = new curve["short"](options);else if (options.type === 'edwards') this.curve = new curve.edwards(options);else this.curve = new curve.mont(options); this.g = this.curve.g; this.n = this.curve.n; this.hash = options.hash; assert(this.g.validate(), 'Invalid curve'); assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); } curves.PresetCurve = PresetCurve; function defineCurve(name, options) { Object.defineProperty(curves, name, { configurable: true, enumerable: true, get: function get() { var curve = new PresetCurve(options); Object.defineProperty(curves, name, { configurable: true, enumerable: true, value: curve }); return curve; } }); } defineCurve('p192', { type: 'short', prime: 'p192', p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', hash: hash.sha256, gRed: false, g: ['188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'] }); defineCurve('p224', { type: 'short', prime: 'p224', p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', hash: hash.sha256, gRed: false, g: ['b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'] }); defineCurve('p256', { type: 'short', prime: null, p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', hash: hash.sha256, gRed: false, g: ['6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'] }); defineCurve('p384', { type: 'short', prime: null, p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'fffffffe ffffffff 00000000 00000000 ffffffff', a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'fffffffe ffffffff 00000000 00000000 fffffffc', b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', hash: hash.sha384, gRed: false, g: ['aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + '5502f25d bf55296c 3a545e38 72760ab7', '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'] }); defineCurve('p521', { type: 'short', prime: null, p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff ffffffff', a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff fffffffc', b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', hash: hash.sha512, gRed: false, g: ['000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + '3fad0761 353c7086 a272c240 88be9476 9fd16650'] }); defineCurve('curve25519', { type: 'mont', prime: 'p25519', p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', a: '76d06', b: '1', n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', hash: hash.sha256, gRed: false, g: ['9'] }); defineCurve('ed25519', { type: 'edwards', prime: 'p25519', p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', a: '-1', c: '1', // -121665 * (121666^(-1)) (mod P) d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', hash: hash.sha256, gRed: false, g: ['216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', // 4/5 '6666666666666666666666666666666666666666666666666666666666666658'] }); var pre; try { pre = __webpack_require__(8948); } catch (e) { pre = undefined; } defineCurve('secp256k1', { type: 'short', prime: 'k256', p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', a: '0', b: '7', n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', h: '1', hash: hash.sha256, // Precomputed endomorphism beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', basis: [{ a: '3086d221a7d46bcde86c90e49284eb15', b: '-e4437ed6010e88286f547fa90abfe4c3' }, { a: '114ca50f7a8e2f3f657c1108d9d44cfd8', b: '3086d221a7d46bcde86c90e49284eb15' }], gRed: false, g: ['79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', pre] }); /***/ }), /***/ 5806: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var BN = __webpack_require__(6781); var HmacDRBG = __webpack_require__(9742); var utils = __webpack_require__(7891); var curves = __webpack_require__(1478); var rand = __webpack_require__(7179); var assert = utils.assert; var KeyPair = __webpack_require__(3598); var Signature = __webpack_require__(5206); function EC(options) { if (!(this instanceof EC)) return new EC(options); // Shortcut `elliptic.ec(curve-name)` if (typeof options === 'string') { assert(Object.prototype.hasOwnProperty.call(curves, options), 'Unknown curve ' + options); options = curves[options]; } // Shortcut for `elliptic.ec(elliptic.curves.curveName)` if (options instanceof curves.PresetCurve) options = { curve: options }; this.curve = options.curve.curve; this.n = this.curve.n; this.nh = this.n.ushrn(1); this.g = this.curve.g; // Point on curve this.g = options.curve.g; this.g.precompute(options.curve.n.bitLength() + 1); // Hash for function for DRBG this.hash = options.hash || options.curve.hash; } module.exports = EC; EC.prototype.keyPair = function keyPair(options) { return new KeyPair(this, options); }; EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { return KeyPair.fromPrivate(this, priv, enc); }; EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { return KeyPair.fromPublic(this, pub, enc); }; EC.prototype.genKeyPair = function genKeyPair(options) { if (!options) options = {}; // Instantiate Hmac_DRBG var drbg = new HmacDRBG({ hash: this.hash, pers: options.pers, persEnc: options.persEnc || 'utf8', entropy: options.entropy || rand(this.hash.hmacStrength), entropyEnc: options.entropy && options.entropyEnc || 'utf8', nonce: this.n.toArray() }); var bytes = this.n.byteLength(); var ns2 = this.n.sub(new BN(2)); for (;;) { var priv = new BN(drbg.generate(bytes)); if (priv.cmp(ns2) > 0) continue; priv.iaddn(1); return this.keyFromPrivate(priv); } }; EC.prototype._truncateToN = function _truncateToN(msg, truncOnly) { var delta = msg.byteLength() * 8 - this.n.bitLength(); if (delta > 0) msg = msg.ushrn(delta); if (!truncOnly && msg.cmp(this.n) >= 0) return msg.sub(this.n);else return msg; }; EC.prototype.sign = function sign(msg, key, enc, options) { if (_typeof(enc) === 'object') { options = enc; enc = null; } if (!options) options = {}; key = this.keyFromPrivate(key, enc); msg = this._truncateToN(new BN(msg, 16)); // Zero-extend key to provide enough entropy var bytes = this.n.byteLength(); var bkey = key.getPrivate().toArray('be', bytes); // Zero-extend nonce to have the same byte size as N var nonce = msg.toArray('be', bytes); // Instantiate Hmac_DRBG var drbg = new HmacDRBG({ hash: this.hash, entropy: bkey, nonce: nonce, pers: options.pers, persEnc: options.persEnc || 'utf8' }); // Number of bytes to generate var ns1 = this.n.sub(new BN(1)); for (var iter = 0;; iter++) { var k = options.k ? options.k(iter) : new BN(drbg.generate(this.n.byteLength())); k = this._truncateToN(k, true); if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) continue; var kp = this.g.mul(k); if (kp.isInfinity()) continue; var kpX = kp.getX(); var r = kpX.umod(this.n); if (r.cmpn(0) === 0) continue; var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); s = s.umod(this.n); if (s.cmpn(0) === 0) continue; var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | (kpX.cmp(r) !== 0 ? 2 : 0); // Use complement of `s`, if it is > `n / 2` if (options.canonical && s.cmp(this.nh) > 0) { s = this.n.sub(s); recoveryParam ^= 1; } return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); } }; EC.prototype.verify = function verify(msg, signature, key, enc) { msg = this._truncateToN(new BN(msg, 16)); key = this.keyFromPublic(key, enc); signature = new Signature(signature, 'hex'); // Perform primitive values validation var r = signature.r; var s = signature.s; if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) return false; if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) return false; // Validate signature var sinv = s.invm(this.n); var u1 = sinv.mul(msg).umod(this.n); var u2 = sinv.mul(r).umod(this.n); var p; if (!this.curve._maxwellTrick) { p = this.g.mulAdd(u1, key.getPublic(), u2); if (p.isInfinity()) return false; return p.getX().umod(this.n).cmp(r) === 0; } // NOTE: Greg Maxwell's trick, inspired by: // https://git.io/vad3K p = this.g.jmulAdd(u1, key.getPublic(), u2); if (p.isInfinity()) return false; // Compare `p.x` of Jacobian point with `r`, // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the // inverse of `p.z^2` return p.eqXToP(r); }; EC.prototype.recoverPubKey = function (msg, signature, j, enc) { assert((3 & j) === j, 'The recovery param is more than two bits'); signature = new Signature(signature, enc); var n = this.n; var e = new BN(msg); var r = signature.r; var s = signature.s; // A set LSB signifies that the y-coordinate is odd var isYOdd = j & 1; var isSecondKey = j >> 1; if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) throw new Error('Unable to find sencond key candinate'); // 1.1. Let x = r + jn. if (isSecondKey) r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);else r = this.curve.pointFromX(r, isYOdd); var rInv = signature.r.invm(n); var s1 = n.sub(e).mul(rInv).umod(n); var s2 = s.mul(rInv).umod(n); // 1.6.1 Compute Q = r^-1 (sR - eG) // Q = r^-1 (sR + -eG) return this.g.mulAdd(s1, r, s2); }; EC.prototype.getKeyRecoveryParam = function (e, signature, Q, enc) { signature = new Signature(signature, enc); if (signature.recoveryParam !== null) return signature.recoveryParam; for (var i = 0; i < 4; i++) { var Qprime; try { Qprime = this.recoverPubKey(e, signature, i); } catch (e) { continue; } if (Qprime.eq(Q)) return i; } throw new Error('Unable to find valid recovery factor'); }; /***/ }), /***/ 3598: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var BN = __webpack_require__(6781); var utils = __webpack_require__(7891); var assert = utils.assert; function KeyPair(ec, options) { this.ec = ec; this.priv = null; this.pub = null; // KeyPair(ec, { priv: ..., pub: ... }) if (options.priv) this._importPrivate(options.priv, options.privEnc); if (options.pub) this._importPublic(options.pub, options.pubEnc); } module.exports = KeyPair; KeyPair.fromPublic = function fromPublic(ec, pub, enc) { if (pub instanceof KeyPair) return pub; return new KeyPair(ec, { pub: pub, pubEnc: enc }); }; KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { if (priv instanceof KeyPair) return priv; return new KeyPair(ec, { priv: priv, privEnc: enc }); }; KeyPair.prototype.validate = function validate() { var pub = this.getPublic(); if (pub.isInfinity()) return { result: false, reason: 'Invalid public key' }; if (!pub.validate()) return { result: false, reason: 'Public key is not a point' }; if (!pub.mul(this.ec.curve.n).isInfinity()) return { result: false, reason: 'Public key * N != O' }; return { result: true, reason: null }; }; KeyPair.prototype.getPublic = function getPublic(compact, enc) { // compact is optional argument if (typeof compact === 'string') { enc = compact; compact = null; } if (!this.pub) this.pub = this.ec.g.mul(this.priv); if (!enc) return this.pub; return this.pub.encode(enc, compact); }; KeyPair.prototype.getPrivate = function getPrivate(enc) { if (enc === 'hex') return this.priv.toString(16, 2);else return this.priv; }; KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { this.priv = new BN(key, enc || 16); // Ensure that the priv won't be bigger than n, otherwise we may fail // in fixed multiplication method this.priv = this.priv.umod(this.ec.curve.n); }; KeyPair.prototype._importPublic = function _importPublic(key, enc) { if (key.x || key.y) { // Montgomery points only have an `x` coordinate. // Weierstrass/Edwards points on the other hand have both `x` and // `y` coordinates. if (this.ec.curve.type === 'mont') { assert(key.x, 'Need x coordinate'); } else if (this.ec.curve.type === 'short' || this.ec.curve.type === 'edwards') { assert(key.x && key.y, 'Need both x and y coordinate'); } this.pub = this.ec.curve.point(key.x, key.y); return; } this.pub = this.ec.curve.decodePoint(key, enc); }; // ECDH KeyPair.prototype.derive = function derive(pub) { if (!pub.validate()) { assert(pub.validate(), 'public point not validated'); } return pub.mul(this.priv).getX(); }; // ECDSA KeyPair.prototype.sign = function sign(msg, enc, options) { return this.ec.sign(msg, this, enc, options); }; KeyPair.prototype.verify = function verify(msg, signature) { return this.ec.verify(msg, signature, this); }; KeyPair.prototype.inspect = function inspect() { return ''; }; /***/ }), /***/ 5206: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var BN = __webpack_require__(6781); var utils = __webpack_require__(7891); var assert = utils.assert; function Signature(options, enc) { if (options instanceof Signature) return options; if (this._importDER(options, enc)) return; assert(options.r && options.s, 'Signature without r or s'); this.r = new BN(options.r, 16); this.s = new BN(options.s, 16); if (options.recoveryParam === undefined) this.recoveryParam = null;else this.recoveryParam = options.recoveryParam; } module.exports = Signature; function Position() { this.place = 0; } function getLength(buf, p) { var initial = buf[p.place++]; if (!(initial & 0x80)) { return initial; } var octetLen = initial & 0xf; // Indefinite length or overflow if (octetLen === 0 || octetLen > 4) { return false; } var val = 0; for (var i = 0, off = p.place; i < octetLen; i++, off++) { val <<= 8; val |= buf[off]; val >>>= 0; } // Leading zeroes if (val <= 0x7f) { return false; } p.place = off; return val; } function rmPadding(buf) { var i = 0; var len = buf.length - 1; while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { i++; } if (i === 0) { return buf; } return buf.slice(i); } Signature.prototype._importDER = function _importDER(data, enc) { data = utils.toArray(data, enc); var p = new Position(); if (data[p.place++] !== 0x30) { return false; } var len = getLength(data, p); if (len === false) { return false; } if (len + p.place !== data.length) { return false; } if (data[p.place++] !== 0x02) { return false; } var rlen = getLength(data, p); if (rlen === false) { return false; } var r = data.slice(p.place, rlen + p.place); p.place += rlen; if (data[p.place++] !== 0x02) { return false; } var slen = getLength(data, p); if (slen === false) { return false; } if (data.length !== slen + p.place) { return false; } var s = data.slice(p.place, slen + p.place); if (r[0] === 0) { if (r[1] & 0x80) { r = r.slice(1); } else { // Leading zeroes return false; } } if (s[0] === 0) { if (s[1] & 0x80) { s = s.slice(1); } else { // Leading zeroes return false; } } this.r = new BN(r); this.s = new BN(s); this.recoveryParam = null; return true; }; function constructLength(arr, len) { if (len < 0x80) { arr.push(len); return; } var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); arr.push(octets | 0x80); while (--octets) { arr.push(len >>> (octets << 3) & 0xff); } arr.push(len); } Signature.prototype.toDER = function toDER(enc) { var r = this.r.toArray(); var s = this.s.toArray(); // Pad values if (r[0] & 0x80) r = [0].concat(r); // Pad values if (s[0] & 0x80) s = [0].concat(s); r = rmPadding(r); s = rmPadding(s); while (!s[0] && !(s[1] & 0x80)) { s = s.slice(1); } var arr = [0x02]; constructLength(arr, r.length); arr = arr.concat(r); arr.push(0x02); constructLength(arr, s.length); var backHalf = arr.concat(s); var res = [0x30]; constructLength(res, backHalf.length); res = res.concat(backHalf); return utils.encode(res, enc); }; /***/ }), /***/ 8318: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var hash = __webpack_require__(3192); var curves = __webpack_require__(1478); var utils = __webpack_require__(7891); var assert = utils.assert; var parseBytes = utils.parseBytes; var KeyPair = __webpack_require__(9371); var Signature = __webpack_require__(2214); function EDDSA(curve) { assert(curve === 'ed25519', 'only tested with ed25519 so far'); if (!(this instanceof EDDSA)) return new EDDSA(curve); curve = curves[curve].curve; this.curve = curve; this.g = curve.g; this.g.precompute(curve.n.bitLength() + 1); this.pointClass = curve.point().constructor; this.encodingLength = Math.ceil(curve.n.bitLength() / 8); this.hash = hash.sha512; } module.exports = EDDSA; /** * @param {Array|String} message - message bytes * @param {Array|String|KeyPair} secret - secret bytes or a keypair * @returns {Signature} - signature */ EDDSA.prototype.sign = function sign(message, secret) { message = parseBytes(message); var key = this.keyFromSecret(secret); var r = this.hashInt(key.messagePrefix(), message); var R = this.g.mul(r); var Rencoded = this.encodePoint(R); var s_ = this.hashInt(Rencoded, key.pubBytes(), message).mul(key.priv()); var S = r.add(s_).umod(this.curve.n); return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); }; /** * @param {Array} message - message bytes * @param {Array|String|Signature} sig - sig bytes * @param {Array|String|Point|KeyPair} pub - public key * @returns {Boolean} - true if public key matches sig of message */ EDDSA.prototype.verify = function verify(message, sig, pub) { message = parseBytes(message); sig = this.makeSignature(sig); var key = this.keyFromPublic(pub); var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); var SG = this.g.mul(sig.S()); var RplusAh = sig.R().add(key.pub().mul(h)); return RplusAh.eq(SG); }; EDDSA.prototype.hashInt = function hashInt() { var hash = this.hash(); for (var i = 0; i < arguments.length; i++) { hash.update(arguments[i]); } return utils.intFromLE(hash.digest()).umod(this.curve.n); }; EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { return KeyPair.fromPublic(this, pub); }; EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { return KeyPair.fromSecret(this, secret); }; EDDSA.prototype.makeSignature = function makeSignature(sig) { if (sig instanceof Signature) return sig; return new Signature(this, sig); }; /** * * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 * * EDDSA defines methods for encoding and decoding points and integers. These are * helper convenience methods, that pass along to utility functions implied * parameters. * */ EDDSA.prototype.encodePoint = function encodePoint(point) { var enc = point.getY().toArray('le', this.encodingLength); enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; return enc; }; EDDSA.prototype.decodePoint = function decodePoint(bytes) { bytes = utils.parseBytes(bytes); var lastIx = bytes.length - 1; var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); var xIsOdd = (bytes[lastIx] & 0x80) !== 0; var y = utils.intFromLE(normed); return this.curve.pointFromY(y, xIsOdd); }; EDDSA.prototype.encodeInt = function encodeInt(num) { return num.toArray('le', this.encodingLength); }; EDDSA.prototype.decodeInt = function decodeInt(bytes) { return utils.intFromLE(bytes); }; EDDSA.prototype.isPoint = function isPoint(val) { return val instanceof this.pointClass; }; /***/ }), /***/ 9371: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(7891); var assert = utils.assert; var parseBytes = utils.parseBytes; var cachedProperty = utils.cachedProperty; /** * @param {EDDSA} eddsa - instance * @param {Object} params - public/private key parameters * * @param {Array} [params.secret] - secret seed bytes * @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) * @param {Array} [params.pub] - public key point encoded as bytes * */ function KeyPair(eddsa, params) { this.eddsa = eddsa; this._secret = parseBytes(params.secret); if (eddsa.isPoint(params.pub)) this._pub = params.pub;else this._pubBytes = parseBytes(params.pub); } KeyPair.fromPublic = function fromPublic(eddsa, pub) { if (pub instanceof KeyPair) return pub; return new KeyPair(eddsa, { pub: pub }); }; KeyPair.fromSecret = function fromSecret(eddsa, secret) { if (secret instanceof KeyPair) return secret; return new KeyPair(eddsa, { secret: secret }); }; KeyPair.prototype.secret = function secret() { return this._secret; }; cachedProperty(KeyPair, 'pubBytes', function pubBytes() { return this.eddsa.encodePoint(this.pub()); }); cachedProperty(KeyPair, 'pub', function pub() { if (this._pubBytes) return this.eddsa.decodePoint(this._pubBytes); return this.eddsa.g.mul(this.priv()); }); cachedProperty(KeyPair, 'privBytes', function privBytes() { var eddsa = this.eddsa; var hash = this.hash(); var lastIx = eddsa.encodingLength - 1; var a = hash.slice(0, eddsa.encodingLength); a[0] &= 248; a[lastIx] &= 127; a[lastIx] |= 64; return a; }); cachedProperty(KeyPair, 'priv', function priv() { return this.eddsa.decodeInt(this.privBytes()); }); cachedProperty(KeyPair, 'hash', function hash() { return this.eddsa.hash().update(this.secret()).digest(); }); cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() { return this.hash().slice(this.eddsa.encodingLength); }); KeyPair.prototype.sign = function sign(message) { assert(this._secret, 'KeyPair can only verify'); return this.eddsa.sign(message, this); }; KeyPair.prototype.verify = function verify(message, sig) { return this.eddsa.verify(message, sig, this); }; KeyPair.prototype.getSecret = function getSecret(enc) { assert(this._secret, 'KeyPair is public only'); return utils.encode(this.secret(), enc); }; KeyPair.prototype.getPublic = function getPublic(enc) { return utils.encode(this.pubBytes(), enc); }; module.exports = KeyPair; /***/ }), /***/ 2214: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var BN = __webpack_require__(6781); var utils = __webpack_require__(7891); var assert = utils.assert; var cachedProperty = utils.cachedProperty; var parseBytes = utils.parseBytes; /** * @param {EDDSA} eddsa - eddsa instance * @param {Array|Object} sig - * @param {Array|Point} [sig.R] - R point as Point or bytes * @param {Array|bn} [sig.S] - S scalar as bn or bytes * @param {Array} [sig.Rencoded] - R point encoded * @param {Array} [sig.Sencoded] - S scalar encoded */ function Signature(eddsa, sig) { this.eddsa = eddsa; if (_typeof(sig) !== 'object') sig = parseBytes(sig); if (Array.isArray(sig)) { sig = { R: sig.slice(0, eddsa.encodingLength), S: sig.slice(eddsa.encodingLength) }; } assert(sig.R && sig.S, 'Signature without R or S'); if (eddsa.isPoint(sig.R)) this._R = sig.R; if (sig.S instanceof BN) this._S = sig.S; this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; } cachedProperty(Signature, 'S', function S() { return this.eddsa.decodeInt(this.Sencoded()); }); cachedProperty(Signature, 'R', function R() { return this.eddsa.decodePoint(this.Rencoded()); }); cachedProperty(Signature, 'Rencoded', function Rencoded() { return this.eddsa.encodePoint(this.R()); }); cachedProperty(Signature, 'Sencoded', function Sencoded() { return this.eddsa.encodeInt(this.S()); }); Signature.prototype.toBytes = function toBytes() { return this.Rencoded().concat(this.Sencoded()); }; Signature.prototype.toHex = function toHex() { return utils.encode(this.toBytes(), 'hex').toUpperCase(); }; module.exports = Signature; /***/ }), /***/ 8948: /***/ ((module) => { module.exports = { doubles: { step: 4, points: [['e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'], ['8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'], ['175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'], ['363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'], ['8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'], ['723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'], ['eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'], ['100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'], ['e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'], ['feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'], ['da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'], ['53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'], ['8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'], ['385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'], ['6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'], ['3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'], ['85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'], ['948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'], ['6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'], ['e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'], ['e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'], ['213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'], ['4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'], ['fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'], ['76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'], ['c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'], ['d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'], ['b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'], ['e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'], ['a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'], ['90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'], ['8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'], ['e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'], ['8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'], ['e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'], ['b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'], ['d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'], ['324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'], ['4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'], ['9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'], ['6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'], ['a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'], ['7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'], ['928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'], ['85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'], ['ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'], ['827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'], ['eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'], ['e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'], ['1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'], ['146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'], ['fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'], ['da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'], ['a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'], ['174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'], ['959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'], ['d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'], ['64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'], ['8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'], ['13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'], ['bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'], ['8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'], ['8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'], ['dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'], ['f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82']] }, naf: { wnd: 7, points: [['f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'], ['2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'], ['5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'], ['acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'], ['774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'], ['f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'], ['d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'], ['defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'], ['2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'], ['352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'], ['2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'], ['9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'], ['daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'], ['c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'], ['6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'], ['1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'], ['605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'], ['62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'], ['80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'], ['7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'], ['d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'], ['49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'], ['77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'], ['f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'], ['463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'], ['f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'], ['caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'], ['2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'], ['7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'], ['754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'], ['e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'], ['186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'], ['df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'], ['5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'], ['290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'], ['af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'], ['766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'], ['59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'], ['f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'], ['7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'], ['948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'], ['7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'], ['3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'], ['d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'], ['1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'], ['733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'], ['15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'], ['a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'], ['e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'], ['311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'], ['34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'], ['f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'], ['d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'], ['32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'], ['7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'], ['ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'], ['16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'], ['eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'], ['78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'], ['494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'], ['a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'], ['c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'], ['841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'], ['5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'], ['36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'], ['336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'], ['8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'], ['1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'], ['85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'], ['29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'], ['a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'], ['4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'], ['d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'], ['ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'], ['af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'], ['e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'], ['591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'], ['11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'], ['3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'], ['cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'], ['c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'], ['c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'], ['a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'], ['347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'], ['da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'], ['c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'], ['4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'], ['3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'], ['cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'], ['b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'], ['d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'], ['48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'], ['dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'], ['6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'], ['e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'], ['eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'], ['13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'], ['ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'], ['b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'], ['ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'], ['8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'], ['52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'], ['e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'], ['7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'], ['5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'], ['32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'], ['e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'], ['8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'], ['4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'], ['3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'], ['674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'], ['d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'], ['30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'], ['be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'], ['93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'], ['b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'], ['d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'], ['d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'], ['463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'], ['7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'], ['74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'], ['30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'], ['9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'], ['176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'], ['75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'], ['809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'], ['1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9']] } }; /***/ }), /***/ 7891: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var utils = exports; var BN = __webpack_require__(6781); var minAssert = __webpack_require__(1130); var minUtils = __webpack_require__(5522); utils.assert = minAssert; utils.toArray = minUtils.toArray; utils.zero2 = minUtils.zero2; utils.toHex = minUtils.toHex; utils.encode = minUtils.encode; // Represent num in a w-NAF form function getNAF(num, w, bits) { var naf = new Array(Math.max(num.bitLength(), bits) + 1); naf.fill(0); var ws = 1 << w + 1; var k = num.clone(); for (var i = 0; i < naf.length; i++) { var z; var mod = k.andln(ws - 1); if (k.isOdd()) { if (mod > (ws >> 1) - 1) z = (ws >> 1) - mod;else z = mod; k.isubn(z); } else { z = 0; } naf[i] = z; k.iushrn(1); } return naf; } utils.getNAF = getNAF; // Represent k1, k2 in a Joint Sparse Form function getJSF(k1, k2) { var jsf = [[], []]; k1 = k1.clone(); k2 = k2.clone(); var d1 = 0; var d2 = 0; var m8; while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { // First phase var m14 = k1.andln(3) + d1 & 3; var m24 = k2.andln(3) + d2 & 3; if (m14 === 3) m14 = -1; if (m24 === 3) m24 = -1; var u1; if ((m14 & 1) === 0) { u1 = 0; } else { m8 = k1.andln(7) + d1 & 7; if ((m8 === 3 || m8 === 5) && m24 === 2) u1 = -m14;else u1 = m14; } jsf[0].push(u1); var u2; if ((m24 & 1) === 0) { u2 = 0; } else { m8 = k2.andln(7) + d2 & 7; if ((m8 === 3 || m8 === 5) && m14 === 2) u2 = -m24;else u2 = m24; } jsf[1].push(u2); // Second phase if (2 * d1 === u1 + 1) d1 = 1 - d1; if (2 * d2 === u2 + 1) d2 = 1 - d2; k1.iushrn(1); k2.iushrn(1); } return jsf; } utils.getJSF = getJSF; function cachedProperty(obj, name, computer) { var key = '_' + name; obj.prototype[name] = function cachedProperty() { return this[key] !== undefined ? this[key] : this[key] = computer.call(this); }; } utils.cachedProperty = cachedProperty; function parseBytes(bytes) { return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : bytes; } utils.parseBytes = parseBytes; function intFromLE(bytes) { return new BN(bytes, 'hex', 'le'); } utils.intFromLE = intFromLE; /***/ }), /***/ 8028: /***/ ((module) => { "use strict"; /** * Code refactored from Mozilla Developer Network: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign */ function assign(target, firstSource) { if (target === undefined || target === null) { throw new TypeError('Cannot convert first argument to object'); } var to = Object(target); for (var i = 1; i < arguments.length; i++) { var nextSource = arguments[i]; if (nextSource === undefined || nextSource === null) { continue; } var keysArray = Object.keys(Object(nextSource)); for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) { var nextKey = keysArray[nextIndex]; var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey); if (desc !== undefined && desc.enumerable) { to[nextKey] = nextSource[nextKey]; } } } return to; } function polyfill() { if (!Object.assign) { Object.defineProperty(Object, 'assign', { enumerable: false, configurable: true, writable: true, value: assign }); } } module.exports = { assign: assign, polyfill: polyfill }; /***/ }), /***/ 9620: /***/ ((module) => { "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. function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var R = (typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === 'object' ? Reflect : null; var ReflectApply = R && typeof R.apply === 'function' ? R.apply : function ReflectApply(target, receiver, args) { return Function.prototype.apply.call(target, receiver, args); }; var ReflectOwnKeys; if (R && typeof R.ownKeys === 'function') { ReflectOwnKeys = R.ownKeys; } else if (Object.getOwnPropertySymbols) { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); }; } else { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target); }; } function ProcessEmitWarning(warning) { if (console && console.warn) console.warn(warning); } var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { return value !== value; }; function EventEmitter() { EventEmitter.init.call(this); } module.exports = EventEmitter; module.exports.once = once; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._eventsCount = 0; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. var defaultMaxListeners = 10; function checkListener(listener) { if (typeof listener !== 'function') { throw new TypeError('The "listener" argument must be of type Function. Received type ' + _typeof(listener)); } } Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function get() { return defaultMaxListeners; }, set: function set(arg) { if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); } defaultMaxListeners = arg; } }); EventEmitter.init = function () { if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) { this._events = Object.create(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); } this._maxListeners = n; return this; }; function _getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return _getMaxListeners(this); }; EventEmitter.prototype.emit = function emit(type) { var args = []; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); } var doError = type === 'error'; var events = this._events; if (events !== undefined) doError = doError && events.error === undefined;else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { var er; if (args.length > 0) er = args[0]; if (er instanceof Error) { // Note: The comments on the `throw` lines are intentional, they show // up in Node's output if this results in an unhandled exception. throw er; // Unhandled 'error' event } // At least give some kind of context to the user var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); err.context = er; throw err; // Unhandled 'error' event } var handler = events[type]; if (handler === undefined) return false; if (typeof handler === 'function') { ReflectApply(handler, this, args); } else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) { ReflectApply(listeners[i], this, args); } } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; checkListener(listener); events = target._events; if (events === undefined) { events = target._events = Object.create(null); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener !== undefined) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (existing === undefined) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; // If we've already got an array, just append. } else if (prepend) { existing.unshift(listener); } else { existing.push(listener); } // Check for listener leak m = _getMaxListeners(target); if (m > 0 && existing.length > m && !existing.warned) { existing.warned = true; // No error code for this since it is a Warning // eslint-disable-next-line no-restricted-syntax var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + String(type) + ' listeners ' + 'added. Use emitter.setMaxListeners() to ' + 'increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; ProcessEmitWarning(w); } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; if (arguments.length === 0) return this.listener.call(this.target); return this.listener.apply(this.target, arguments); } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = onceWrapper.bind(state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once(type, listener) { checkListener(listener); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { checkListener(listener); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // Emits a 'removeListener' event if and only if the listener was removed. EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; checkListener(listener); events = this._events; if (events === undefined) return this; list = events[type]; if (list === undefined) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = Object.create(null);else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (position === 0) list.shift();else { spliceOne(list, position); } if (list.length === 1) events[type] = list[0]; if (events.removeListener !== undefined) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; events = this._events; if (events === undefined) return this; // not listening for removeListener, no need to emit if (events.removeListener === undefined) { if (arguments.length === 0) { this._events = Object.create(null); this._eventsCount = 0; } else if (events[type] !== undefined) { if (--this._eventsCount === 0) this._events = Object.create(null);else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = Object.keys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = Object.create(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners !== undefined) { // LIFO order for (i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return this; }; function _listeners(target, type, unwrap) { var events = target._events; if (events === undefined) return []; var evlistener = events[type]; if (evlistener === undefined) return []; if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; EventEmitter.listenerCount = function (emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events !== undefined) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener !== undefined) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; }; function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) { copy[i] = arr[i]; } return copy; } function spliceOne(list, index) { for (; index + 1 < list.length; index++) { list[index] = list[index + 1]; } list.pop(); } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function once(emitter, name) { return new Promise(function (resolve, reject) { function errorListener(err) { emitter.removeListener(name, resolver); reject(err); } function resolver() { if (typeof emitter.removeListener === 'function') { emitter.removeListener('error', errorListener); } resolve([].slice.call(arguments)); } ; eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); if (name !== 'error') { addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); } }); } function addErrorHandlerIfEventEmitter(emitter, handler, flags) { if (typeof emitter.on === 'function') { eventTargetAgnosticAddListener(emitter, 'error', handler, flags); } } function eventTargetAgnosticAddListener(emitter, name, listener, flags) { if (typeof emitter.on === 'function') { if (flags.once) { emitter.once(name, listener); } else { emitter.on(name, listener); } } else if (typeof emitter.addEventListener === 'function') { // EventTarget does not have `error` event semantics like Node // EventEmitters, we do not listen for `error` events here. emitter.addEventListener(name, function wrapListener(arg) { // IE does not have builtin `{ once: true }` support so we // have to do it manually. if (flags.once) { emitter.removeEventListener(name, wrapListener); } listener(arg); }); } else { throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + _typeof(emitter)); } } /***/ }), /***/ 1248: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var Buffer = (__webpack_require__(9047).Buffer); var MD5 = __webpack_require__(722); /* eslint-disable camelcase */ function EVP_BytesToKey(password, salt, keyBits, ivLen) { if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary'); if (salt) { if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary'); if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length'); } var keyLen = keyBits / 8; var key = Buffer.alloc(keyLen); var iv = Buffer.alloc(ivLen || 0); var tmp = Buffer.alloc(0); while (keyLen > 0 || ivLen > 0) { var hash = new MD5(); hash.update(tmp); hash.update(password); if (salt) hash.update(salt); tmp = hash.digest(); var used = 0; if (keyLen > 0) { var keyStart = key.length - keyLen; used = Math.min(keyLen, tmp.length); tmp.copy(key, keyStart, 0, used); keyLen -= used; } if (used < tmp.length && ivLen > 0) { var ivStart = iv.length - ivLen; var length = Math.min(ivLen, tmp.length - used); tmp.copy(iv, ivStart, used, used + length); ivLen -= length; } } tmp.fill(0); return { key: key, iv: iv }; } module.exports = EVP_BytesToKey; /***/ }), /***/ 5337: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isCallable = __webpack_require__(8625); var toStr = Object.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; var forEachArray = function forEachArray(array, iterator, receiver) { for (var i = 0, len = array.length; i < len; i++) { if (hasOwnProperty.call(array, i)) { if (receiver == null) { iterator(array[i], i, array); } else { iterator.call(receiver, array[i], i, array); } } } }; var forEachString = function forEachString(string, iterator, receiver) { for (var i = 0, len = string.length; i < len; i++) { // no such thing as a sparse string. if (receiver == null) { iterator(string.charAt(i), i, string); } else { iterator.call(receiver, string.charAt(i), i, string); } } }; var forEachObject = function forEachObject(object, iterator, receiver) { for (var k in object) { if (hasOwnProperty.call(object, k)) { if (receiver == null) { iterator(object[k], k, object); } else { iterator.call(receiver, object[k], k, object); } } } }; var forEach = function forEach(list, iterator, thisArg) { if (!isCallable(iterator)) { throw new TypeError('iterator must be a function'); } var receiver; if (arguments.length >= 3) { receiver = thisArg; } if (toStr.call(list) === '[object Array]') { forEachArray(list, iterator, receiver); } else if (typeof list === 'string') { forEachString(list, iterator, receiver); } else { forEachObject(list, iterator, receiver); } }; module.exports = forEach; /***/ }), /***/ 5929: /***/ ((module) => { "use strict"; /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var slice = Array.prototype.slice; var toStr = Object.prototype.toString; var funcType = '[object Function]'; module.exports = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.call(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slice.call(arguments, 1); var bound; var binder = function binder() { if (this instanceof bound) { var result = target.apply(this, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return this; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; var boundLength = Math.max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push('$' + i); } bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; /***/ }), /***/ 5246: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var implementation = __webpack_require__(5929); module.exports = Function.prototype.bind || implementation; /***/ }), /***/ 6893: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var undefined; var $SyntaxError = SyntaxError; var $Function = Function; var $TypeError = TypeError; // eslint-disable-next-line consistent-return var getEvalledConstructor = function getEvalledConstructor(expressionSyntax) { try { return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); } catch (e) {} }; var $gOPD = Object.getOwnPropertyDescriptor; if ($gOPD) { try { $gOPD({}, ''); } catch (e) { $gOPD = null; // this is IE 8, which has a broken gOPD } } var throwTypeError = function throwTypeError() { throw new $TypeError(); }; var ThrowTypeError = $gOPD ? function () { try { // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties arguments.callee; // IE 8 does not throw here return throwTypeError; } catch (calleeThrows) { try { // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') return $gOPD(arguments, 'callee').get; } catch (gOPDthrows) { return throwTypeError; } } }() : throwTypeError; var hasSymbols = __webpack_require__(5990)(); var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto var needsEval = {}; var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); var INTRINSICS = { '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, '%Array%': Array, '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, '%AsyncFromSyncIteratorPrototype%': undefined, '%AsyncFunction%': needsEval, '%AsyncGenerator%': needsEval, '%AsyncGeneratorFunction%': needsEval, '%AsyncIteratorPrototype%': needsEval, '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, '%Boolean%': Boolean, '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, '%Date%': Date, '%decodeURI%': decodeURI, '%decodeURIComponent%': decodeURIComponent, '%encodeURI%': encodeURI, '%encodeURIComponent%': encodeURIComponent, '%Error%': Error, '%eval%': eval, // eslint-disable-line no-eval '%EvalError%': EvalError, '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, '%Function%': $Function, '%GeneratorFunction%': needsEval, '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, '%isFinite%': isFinite, '%isNaN%': isNaN, '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, '%JSON%': (typeof JSON === "undefined" ? "undefined" : _typeof(JSON)) === 'object' ? JSON : undefined, '%Map%': typeof Map === 'undefined' ? undefined : Map, '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), '%Math%': Math, '%Number%': Number, '%Object%': Object, '%parseFloat%': parseFloat, '%parseInt%': parseInt, '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, '%RangeError%': RangeError, '%ReferenceError%': ReferenceError, '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, '%RegExp%': RegExp, '%Set%': typeof Set === 'undefined' ? undefined : Set, '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, '%String%': String, '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, '%Symbol%': hasSymbols ? Symbol : undefined, '%SyntaxError%': $SyntaxError, '%ThrowTypeError%': ThrowTypeError, '%TypedArray%': TypedArray, '%TypeError%': $TypeError, '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, '%URIError%': URIError, '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet }; var doEval = function doEval(name) { var value; if (name === '%AsyncFunction%') { value = getEvalledConstructor('async function () {}'); } else if (name === '%GeneratorFunction%') { value = getEvalledConstructor('function* () {}'); } else if (name === '%AsyncGeneratorFunction%') { value = getEvalledConstructor('async function* () {}'); } else if (name === '%AsyncGenerator%') { var fn = doEval('%AsyncGeneratorFunction%'); if (fn) { value = fn.prototype; } } else if (name === '%AsyncIteratorPrototype%') { var gen = doEval('%AsyncGenerator%'); if (gen) { value = getProto(gen.prototype); } } INTRINSICS[name] = value; return value; }; var LEGACY_ALIASES = { '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], '%ArrayPrototype%': ['Array', 'prototype'], '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], '%ArrayProto_values%': ['Array', 'prototype', 'values'], '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], '%BooleanPrototype%': ['Boolean', 'prototype'], '%DataViewPrototype%': ['DataView', 'prototype'], '%DatePrototype%': ['Date', 'prototype'], '%ErrorPrototype%': ['Error', 'prototype'], '%EvalErrorPrototype%': ['EvalError', 'prototype'], '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], '%FunctionPrototype%': ['Function', 'prototype'], '%Generator%': ['GeneratorFunction', 'prototype'], '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], '%JSONParse%': ['JSON', 'parse'], '%JSONStringify%': ['JSON', 'stringify'], '%MapPrototype%': ['Map', 'prototype'], '%NumberPrototype%': ['Number', 'prototype'], '%ObjectPrototype%': ['Object', 'prototype'], '%ObjProto_toString%': ['Object', 'prototype', 'toString'], '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], '%PromisePrototype%': ['Promise', 'prototype'], '%PromiseProto_then%': ['Promise', 'prototype', 'then'], '%Promise_all%': ['Promise', 'all'], '%Promise_reject%': ['Promise', 'reject'], '%Promise_resolve%': ['Promise', 'resolve'], '%RangeErrorPrototype%': ['RangeError', 'prototype'], '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], '%RegExpPrototype%': ['RegExp', 'prototype'], '%SetPrototype%': ['Set', 'prototype'], '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], '%StringPrototype%': ['String', 'prototype'], '%SymbolPrototype%': ['Symbol', 'prototype'], '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], '%TypedArrayPrototype%': ['TypedArray', 'prototype'], '%TypeErrorPrototype%': ['TypeError', 'prototype'], '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], '%URIErrorPrototype%': ['URIError', 'prototype'], '%WeakMapPrototype%': ['WeakMap', 'prototype'], '%WeakSetPrototype%': ['WeakSet', 'prototype'] }; var bind = __webpack_require__(5246); var hasOwn = __webpack_require__(7751); var $concat = bind.call(Function.call, Array.prototype.concat); var $spliceApply = bind.call(Function.apply, Array.prototype.splice); var $replace = bind.call(Function.call, String.prototype.replace); var $strSlice = bind.call(Function.call, String.prototype.slice); var $exec = bind.call(Function.call, RegExp.prototype.exec); /* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ var stringToPath = function stringToPath(string) { var first = $strSlice(string, 0, 1); var last = $strSlice(string, -1); if (first === '%' && last !== '%') { throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); } else if (last === '%' && first !== '%') { throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); } var result = []; $replace(string, rePropName, function (match, number, quote, subString) { result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; }); return result; }; /* end adaptation */ var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { var intrinsicName = name; var alias; if (hasOwn(LEGACY_ALIASES, intrinsicName)) { alias = LEGACY_ALIASES[intrinsicName]; intrinsicName = '%' + alias[0] + '%'; } if (hasOwn(INTRINSICS, intrinsicName)) { var value = INTRINSICS[intrinsicName]; if (value === needsEval) { value = doEval(intrinsicName); } if (typeof value === 'undefined' && !allowMissing) { throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); } return { alias: alias, name: intrinsicName, value: value }; } throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); }; module.exports = function GetIntrinsic(name, allowMissing) { if (typeof name !== 'string' || name.length === 0) { throw new $TypeError('intrinsic name must be a non-empty string'); } if (arguments.length > 1 && typeof allowMissing !== 'boolean') { throw new $TypeError('"allowMissing" argument must be a boolean'); } if ($exec(/^%?[^%]*%?$/g, name) === null) { throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); } var parts = stringToPath(name); var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); var intrinsicRealName = intrinsic.name; var value = intrinsic.value; var skipFurtherCaching = false; var alias = intrinsic.alias; if (alias) { intrinsicBaseName = alias[0]; $spliceApply(parts, $concat([0, 1], alias)); } for (var i = 1, isOwn = true; i < parts.length; i += 1) { var part = parts[i]; var first = $strSlice(part, 0, 1); var last = $strSlice(part, -1); if ((first === '"' || first === "'" || first === '`' || last === '"' || last === "'" || last === '`') && first !== last) { throw new $SyntaxError('property names with quotes must have matching quotes'); } if (part === 'constructor' || !isOwn) { skipFurtherCaching = true; } intrinsicBaseName += '.' + part; intrinsicRealName = '%' + intrinsicBaseName + '%'; if (hasOwn(INTRINSICS, intrinsicRealName)) { value = INTRINSICS[intrinsicRealName]; } else if (value != null) { if (!(part in value)) { if (!allowMissing) { throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); } return void undefined; } if ($gOPD && i + 1 >= parts.length) { var desc = $gOPD(value, part); isOwn = !!desc; // By convention, when a data property is converted to an accessor // property to emulate a data property that does not suffer from // the override mistake, that accessor's getter is marked with // an `originalValue` property. Here, when we detect this, we // uphold the illusion by pretending to see that original data // property, i.e., returning the value rather than the getter // itself. if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { value = desc.get; } else { value = value[part]; } } else { isOwn = hasOwn(value, part); value = value[part]; } if (isOwn && !skipFurtherCaching) { INTRINSICS[intrinsicRealName] = value; } } } return value; }; /***/ }), /***/ 2579: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var GetIntrinsic = __webpack_require__(6893); var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); var hasPropertyDescriptors = function hasPropertyDescriptors() { if ($defineProperty) { try { $defineProperty({}, 'a', { value: 1 }); return true; } catch (e) { // IE 8 has a broken defineProperty return false; } } return false; }; hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { // node v0.6 has a bug where array lengths can be Set but not Defined if (!hasPropertyDescriptors()) { return null; } try { return $defineProperty([], 'length', { value: 1 }).length !== 1; } catch (e) { // In Firefox 4-22, defining length on an array throws an exception. return true; } }; module.exports = hasPropertyDescriptors; /***/ }), /***/ 5990: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var origSymbol = typeof Symbol !== 'undefined' && Symbol; var hasSymbolSham = __webpack_require__(3031); module.exports = function hasNativeSymbols() { if (typeof origSymbol !== 'function') { return false; } if (typeof Symbol !== 'function') { return false; } if (_typeof(origSymbol('foo')) !== 'symbol') { return false; } if (_typeof(Symbol('bar')) !== 'symbol') { return false; } return hasSymbolSham(); }; /***/ }), /***/ 3031: /***/ ((module) => { "use strict"; /* eslint complexity: [2, 18], max-statements: [2, 33] */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } module.exports = function hasSymbols() { if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } if (_typeof(Symbol.iterator) === 'symbol') { return true; } var obj = {}; var sym = Symbol('test'); var symObj = Object(sym); if (typeof sym === 'string') { return false; } if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } // temp disabled per https://github.com/ljharb/object.assign/issues/17 // if (sym instanceof Symbol) { return false; } // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 // if (!(symObj instanceof Symbol)) { return false; } // if (typeof Symbol.prototype.toString !== 'function') { return false; } // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } var symVal = 42; obj[sym] = symVal; for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } var syms = Object.getOwnPropertySymbols(obj); if (syms.length !== 1 || syms[0] !== sym) { return false; } if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } if (typeof Object.getOwnPropertyDescriptor === 'function') { var descriptor = Object.getOwnPropertyDescriptor(obj, sym); if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } } return true; }; /***/ }), /***/ 5994: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var hasSymbols = __webpack_require__(3031); module.exports = function hasToStringTagShams() { return hasSymbols() && !!Symbol.toStringTag; }; /***/ }), /***/ 7751: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var bind = __webpack_require__(5246); module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); /***/ }), /***/ 5125: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Buffer = (__webpack_require__(1066).Buffer); var Transform = (__webpack_require__(8237).Transform); var inherits = __webpack_require__(376); function throwIfNotStringOrBuffer(val, prefix) { if (!Buffer.isBuffer(val) && typeof val !== 'string') { throw new TypeError(prefix + ' must be a string or a buffer'); } } function HashBase(blockSize) { Transform.call(this); this._block = Buffer.allocUnsafe(blockSize); this._blockSize = blockSize; this._blockOffset = 0; this._length = [0, 0, 0, 0]; this._finalized = false; } inherits(HashBase, Transform); HashBase.prototype._transform = function (chunk, encoding, callback) { var error = null; try { this.update(chunk, encoding); } catch (err) { error = err; } callback(error); }; HashBase.prototype._flush = function (callback) { var error = null; try { this.push(this.digest()); } catch (err) { error = err; } callback(error); }; HashBase.prototype.update = function (data, encoding) { throwIfNotStringOrBuffer(data, 'Data'); if (this._finalized) throw new Error('Digest already called'); if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding); // consume data var block = this._block; var offset = 0; while (this._blockOffset + data.length - offset >= this._blockSize) { for (var i = this._blockOffset; i < this._blockSize;) { block[i++] = data[offset++]; } this._update(); this._blockOffset = 0; } while (offset < data.length) { block[this._blockOffset++] = data[offset++]; } // update length for (var j = 0, carry = data.length * 8; carry > 0; ++j) { this._length[j] += carry; carry = this._length[j] / 0x0100000000 | 0; if (carry > 0) this._length[j] -= 0x0100000000 * carry; } return this; }; HashBase.prototype._update = function () { throw new Error('_update is not implemented'); }; HashBase.prototype.digest = function (encoding) { if (this._finalized) throw new Error('Digest already called'); this._finalized = true; var digest = this._digest(); if (encoding !== undefined) digest = digest.toString(encoding); // reset state this._block.fill(0); this._blockOffset = 0; for (var i = 0; i < 4; ++i) { this._length[i] = 0; } return digest; }; HashBase.prototype._digest = function () { throw new Error('_digest is not implemented'); }; module.exports = HashBase; /***/ }), /***/ 1066: /***/ ((module, exports, __webpack_require__) => { /*! safe-buffer. MIT License. Feross Aboukhadijeh */ /* eslint-disable node/no-deprecated-api */ var buffer = __webpack_require__(365); var Buffer = buffer.Buffer; // alternative to using Object.keys for old browsers function copyProps(src, dst) { for (var key in src) { dst[key] = src[key]; } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer; } else { // Copy properties from require('buffer') copyProps(buffer, exports); exports.Buffer = SafeBuffer; } function SafeBuffer(arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length); } SafeBuffer.prototype = Object.create(Buffer.prototype); // Copy static methods from Buffer copyProps(Buffer, SafeBuffer); SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number'); } return Buffer(arg, encodingOrOffset, length); }; SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number'); } var buf = Buffer(size); if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding); } else { buf.fill(fill); } } else { buf.fill(0); } return buf; }; SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number'); } return Buffer(size); }; SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number'); } return buffer.SlowBuffer(size); }; /***/ }), /***/ 3192: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var hash = exports; hash.utils = __webpack_require__(8244); hash.common = __webpack_require__(5386); hash.sha = __webpack_require__(2507); hash.ripemd = __webpack_require__(9993); hash.hmac = __webpack_require__(8534); // Proxy hash functions to the main object hash.sha1 = hash.sha.sha1; hash.sha256 = hash.sha.sha256; hash.sha224 = hash.sha.sha224; hash.sha384 = hash.sha.sha384; hash.sha512 = hash.sha.sha512; hash.ripemd160 = hash.ripemd.ripemd160; /***/ }), /***/ 5386: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(8244); var assert = __webpack_require__(1130); function BlockHash() { this.pending = null; this.pendingTotal = 0; this.blockSize = this.constructor.blockSize; this.outSize = this.constructor.outSize; this.hmacStrength = this.constructor.hmacStrength; this.padLength = this.constructor.padLength / 8; this.endian = 'big'; this._delta8 = this.blockSize / 8; this._delta32 = this.blockSize / 32; } exports.BlockHash = BlockHash; BlockHash.prototype.update = function update(msg, enc) { // Convert message to array, pad it, and join into 32bit blocks msg = utils.toArray(msg, enc); if (!this.pending) this.pending = msg;else this.pending = this.pending.concat(msg); this.pendingTotal += msg.length; // Enough data, try updating if (this.pending.length >= this._delta8) { msg = this.pending; // Process pending data in blocks var r = msg.length % this._delta8; this.pending = msg.slice(msg.length - r, msg.length); if (this.pending.length === 0) this.pending = null; msg = utils.join32(msg, 0, msg.length - r, this.endian); for (var i = 0; i < msg.length; i += this._delta32) { this._update(msg, i, i + this._delta32); } } return this; }; BlockHash.prototype.digest = function digest(enc) { this.update(this._pad()); assert(this.pending === null); return this._digest(enc); }; BlockHash.prototype._pad = function pad() { var len = this.pendingTotal; var bytes = this._delta8; var k = bytes - (len + this.padLength) % bytes; var res = new Array(k + this.padLength); res[0] = 0x80; for (var i = 1; i < k; i++) { res[i] = 0; } // Append length len <<= 3; if (this.endian === 'big') { for (var t = 8; t < this.padLength; t++) { res[i++] = 0; } res[i++] = 0; res[i++] = 0; res[i++] = 0; res[i++] = 0; res[i++] = len >>> 24 & 0xff; res[i++] = len >>> 16 & 0xff; res[i++] = len >>> 8 & 0xff; res[i++] = len & 0xff; } else { res[i++] = len & 0xff; res[i++] = len >>> 8 & 0xff; res[i++] = len >>> 16 & 0xff; res[i++] = len >>> 24 & 0xff; res[i++] = 0; res[i++] = 0; res[i++] = 0; res[i++] = 0; for (t = 8; t < this.padLength; t++) { res[i++] = 0; } } return res; }; /***/ }), /***/ 8534: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(8244); var assert = __webpack_require__(1130); function Hmac(hash, key, enc) { if (!(this instanceof Hmac)) return new Hmac(hash, key, enc); this.Hash = hash; this.blockSize = hash.blockSize / 8; this.outSize = hash.outSize / 8; this.inner = null; this.outer = null; this._init(utils.toArray(key, enc)); } module.exports = Hmac; Hmac.prototype._init = function init(key) { // Shorten key, if needed if (key.length > this.blockSize) key = new this.Hash().update(key).digest(); assert(key.length <= this.blockSize); // Add padding to key for (var i = key.length; i < this.blockSize; i++) { key.push(0); } for (i = 0; i < key.length; i++) { key[i] ^= 0x36; } this.inner = new this.Hash().update(key); // 0x36 ^ 0x5c = 0x6a for (i = 0; i < key.length; i++) { key[i] ^= 0x6a; } this.outer = new this.Hash().update(key); }; Hmac.prototype.update = function update(msg, enc) { this.inner.update(msg, enc); return this; }; Hmac.prototype.digest = function digest(enc) { this.outer.update(this.inner.digest()); return this.outer.digest(enc); }; /***/ }), /***/ 9993: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(8244); var common = __webpack_require__(5386); var rotl32 = utils.rotl32; var sum32 = utils.sum32; var sum32_3 = utils.sum32_3; var sum32_4 = utils.sum32_4; var BlockHash = common.BlockHash; function RIPEMD160() { if (!(this instanceof RIPEMD160)) return new RIPEMD160(); BlockHash.call(this); this.h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; this.endian = 'little'; } utils.inherits(RIPEMD160, BlockHash); exports.ripemd160 = RIPEMD160; RIPEMD160.blockSize = 512; RIPEMD160.outSize = 160; RIPEMD160.hmacStrength = 192; RIPEMD160.padLength = 64; RIPEMD160.prototype._update = function update(msg, start) { var A = this.h[0]; var B = this.h[1]; var C = this.h[2]; var D = this.h[3]; var E = this.h[4]; var Ah = A; var Bh = B; var Ch = C; var Dh = D; var Eh = E; for (var j = 0; j < 80; j++) { var T = sum32(rotl32(sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), s[j]), E); A = E; E = D; D = rotl32(C, 10); C = B; B = T; T = sum32(rotl32(sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), sh[j]), Eh); Ah = Eh; Eh = Dh; Dh = rotl32(Ch, 10); Ch = Bh; Bh = T; } T = sum32_3(this.h[1], C, Dh); this.h[1] = sum32_3(this.h[2], D, Eh); this.h[2] = sum32_3(this.h[3], E, Ah); this.h[3] = sum32_3(this.h[4], A, Bh); this.h[4] = sum32_3(this.h[0], B, Ch); this.h[0] = T; }; RIPEMD160.prototype._digest = function digest(enc) { if (enc === 'hex') return utils.toHex32(this.h, 'little');else return utils.split32(this.h, 'little'); }; function f(j, x, y, z) { if (j <= 15) return x ^ y ^ z;else if (j <= 31) return x & y | ~x & z;else if (j <= 47) return (x | ~y) ^ z;else if (j <= 63) return x & z | y & ~z;else return x ^ (y | ~z); } function K(j) { if (j <= 15) return 0x00000000;else if (j <= 31) return 0x5a827999;else if (j <= 47) return 0x6ed9eba1;else if (j <= 63) return 0x8f1bbcdc;else return 0xa953fd4e; } function Kh(j) { if (j <= 15) return 0x50a28be6;else if (j <= 31) return 0x5c4dd124;else if (j <= 47) return 0x6d703ef3;else if (j <= 63) return 0x7a6d76e9;else return 0x00000000; } var r = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]; var rh = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]; var s = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6]; var sh = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11]; /***/ }), /***/ 2507: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.sha1 = __webpack_require__(9382); exports.sha224 = __webpack_require__(5123); exports.sha256 = __webpack_require__(4032); exports.sha384 = __webpack_require__(1364); exports.sha512 = __webpack_require__(2161); /***/ }), /***/ 9382: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(8244); var common = __webpack_require__(5386); var shaCommon = __webpack_require__(8355); var rotl32 = utils.rotl32; var sum32 = utils.sum32; var sum32_5 = utils.sum32_5; var ft_1 = shaCommon.ft_1; var BlockHash = common.BlockHash; var sha1_K = [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6]; function SHA1() { if (!(this instanceof SHA1)) return new SHA1(); BlockHash.call(this); this.h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; this.W = new Array(80); } utils.inherits(SHA1, BlockHash); module.exports = SHA1; SHA1.blockSize = 512; SHA1.outSize = 160; SHA1.hmacStrength = 80; SHA1.padLength = 64; SHA1.prototype._update = function _update(msg, start) { var W = this.W; for (var i = 0; i < 16; i++) { W[i] = msg[start + i]; } for (; i < W.length; i++) { W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); } var a = this.h[0]; var b = this.h[1]; var c = this.h[2]; var d = this.h[3]; var e = this.h[4]; for (i = 0; i < W.length; i++) { var s = ~~(i / 20); var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); e = d; d = c; c = rotl32(b, 30); b = a; a = t; } this.h[0] = sum32(this.h[0], a); this.h[1] = sum32(this.h[1], b); this.h[2] = sum32(this.h[2], c); this.h[3] = sum32(this.h[3], d); this.h[4] = sum32(this.h[4], e); }; SHA1.prototype._digest = function digest(enc) { if (enc === 'hex') return utils.toHex32(this.h, 'big');else return utils.split32(this.h, 'big'); }; /***/ }), /***/ 5123: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(8244); var SHA256 = __webpack_require__(4032); function SHA224() { if (!(this instanceof SHA224)) return new SHA224(); SHA256.call(this); this.h = [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4]; } utils.inherits(SHA224, SHA256); module.exports = SHA224; SHA224.blockSize = 512; SHA224.outSize = 224; SHA224.hmacStrength = 192; SHA224.padLength = 64; SHA224.prototype._digest = function digest(enc) { // Just truncate output if (enc === 'hex') return utils.toHex32(this.h.slice(0, 7), 'big');else return utils.split32(this.h.slice(0, 7), 'big'); }; /***/ }), /***/ 4032: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(8244); var common = __webpack_require__(5386); var shaCommon = __webpack_require__(8355); var assert = __webpack_require__(1130); var sum32 = utils.sum32; var sum32_4 = utils.sum32_4; var sum32_5 = utils.sum32_5; var ch32 = shaCommon.ch32; var maj32 = shaCommon.maj32; var s0_256 = shaCommon.s0_256; var s1_256 = shaCommon.s1_256; var g0_256 = shaCommon.g0_256; var g1_256 = shaCommon.g1_256; var BlockHash = common.BlockHash; var sha256_K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]; function SHA256() { if (!(this instanceof SHA256)) return new SHA256(); BlockHash.call(this); this.h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]; this.k = sha256_K; this.W = new Array(64); } utils.inherits(SHA256, BlockHash); module.exports = SHA256; SHA256.blockSize = 512; SHA256.outSize = 256; SHA256.hmacStrength = 192; SHA256.padLength = 64; SHA256.prototype._update = function _update(msg, start) { var W = this.W; for (var i = 0; i < 16; i++) { W[i] = msg[start + i]; } for (; i < W.length; i++) { W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); } var a = this.h[0]; var b = this.h[1]; var c = this.h[2]; var d = this.h[3]; var e = this.h[4]; var f = this.h[5]; var g = this.h[6]; var h = this.h[7]; assert(this.k.length === W.length); for (i = 0; i < W.length; i++) { var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); var T2 = sum32(s0_256(a), maj32(a, b, c)); h = g; g = f; f = e; e = sum32(d, T1); d = c; c = b; b = a; a = sum32(T1, T2); } this.h[0] = sum32(this.h[0], a); this.h[1] = sum32(this.h[1], b); this.h[2] = sum32(this.h[2], c); this.h[3] = sum32(this.h[3], d); this.h[4] = sum32(this.h[4], e); this.h[5] = sum32(this.h[5], f); this.h[6] = sum32(this.h[6], g); this.h[7] = sum32(this.h[7], h); }; SHA256.prototype._digest = function digest(enc) { if (enc === 'hex') return utils.toHex32(this.h, 'big');else return utils.split32(this.h, 'big'); }; /***/ }), /***/ 1364: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(8244); var SHA512 = __webpack_require__(2161); function SHA384() { if (!(this instanceof SHA384)) return new SHA384(); SHA512.call(this); this.h = [0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939, 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4]; } utils.inherits(SHA384, SHA512); module.exports = SHA384; SHA384.blockSize = 1024; SHA384.outSize = 384; SHA384.hmacStrength = 192; SHA384.padLength = 128; SHA384.prototype._digest = function digest(enc) { if (enc === 'hex') return utils.toHex32(this.h.slice(0, 12), 'big');else return utils.split32(this.h.slice(0, 12), 'big'); }; /***/ }), /***/ 2161: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(8244); var common = __webpack_require__(5386); var assert = __webpack_require__(1130); var rotr64_hi = utils.rotr64_hi; var rotr64_lo = utils.rotr64_lo; var shr64_hi = utils.shr64_hi; var shr64_lo = utils.shr64_lo; var sum64 = utils.sum64; var sum64_hi = utils.sum64_hi; var sum64_lo = utils.sum64_lo; var sum64_4_hi = utils.sum64_4_hi; var sum64_4_lo = utils.sum64_4_lo; var sum64_5_hi = utils.sum64_5_hi; var sum64_5_lo = utils.sum64_5_lo; var BlockHash = common.BlockHash; var sha512_K = [0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817]; function SHA512() { if (!(this instanceof SHA512)) return new SHA512(); BlockHash.call(this); this.h = [0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179]; this.k = sha512_K; this.W = new Array(160); } utils.inherits(SHA512, BlockHash); module.exports = SHA512; SHA512.blockSize = 1024; SHA512.outSize = 512; SHA512.hmacStrength = 192; SHA512.padLength = 128; SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { var W = this.W; // 32 x 32bit words for (var i = 0; i < 32; i++) { W[i] = msg[start + i]; } for (; i < W.length; i += 2) { var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); var c1_hi = W[i - 14]; // i - 7 var c1_lo = W[i - 13]; var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); var c3_hi = W[i - 32]; // i - 16 var c3_lo = W[i - 31]; W[i] = sum64_4_hi(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo); W[i + 1] = sum64_4_lo(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo); } }; SHA512.prototype._update = function _update(msg, start) { this._prepareBlock(msg, start); var W = this.W; var ah = this.h[0]; var al = this.h[1]; var bh = this.h[2]; var bl = this.h[3]; var ch = this.h[4]; var cl = this.h[5]; var dh = this.h[6]; var dl = this.h[7]; var eh = this.h[8]; var el = this.h[9]; var fh = this.h[10]; var fl = this.h[11]; var gh = this.h[12]; var gl = this.h[13]; var hh = this.h[14]; var hl = this.h[15]; assert(this.k.length === W.length); for (var i = 0; i < W.length; i += 2) { var c0_hi = hh; var c0_lo = hl; var c1_hi = s1_512_hi(eh, el); var c1_lo = s1_512_lo(eh, el); var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); var c3_hi = this.k[i]; var c3_lo = this.k[i + 1]; var c4_hi = W[i]; var c4_lo = W[i + 1]; var T1_hi = sum64_5_hi(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo); var T1_lo = sum64_5_lo(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo); c0_hi = s0_512_hi(ah, al); c0_lo = s0_512_lo(ah, al); c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; eh = sum64_hi(dh, dl, T1_hi, T1_lo); el = sum64_lo(dl, dl, T1_hi, T1_lo); dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); } sum64(this.h, 0, ah, al); sum64(this.h, 2, bh, bl); sum64(this.h, 4, ch, cl); sum64(this.h, 6, dh, dl); sum64(this.h, 8, eh, el); sum64(this.h, 10, fh, fl); sum64(this.h, 12, gh, gl); sum64(this.h, 14, hh, hl); }; SHA512.prototype._digest = function digest(enc) { if (enc === 'hex') return utils.toHex32(this.h, 'big');else return utils.split32(this.h, 'big'); }; function ch64_hi(xh, xl, yh, yl, zh) { var r = xh & yh ^ ~xh & zh; if (r < 0) r += 0x100000000; return r; } function ch64_lo(xh, xl, yh, yl, zh, zl) { var r = xl & yl ^ ~xl & zl; if (r < 0) r += 0x100000000; return r; } function maj64_hi(xh, xl, yh, yl, zh) { var r = xh & yh ^ xh & zh ^ yh & zh; if (r < 0) r += 0x100000000; return r; } function maj64_lo(xh, xl, yh, yl, zh, zl) { var r = xl & yl ^ xl & zl ^ yl & zl; if (r < 0) r += 0x100000000; return r; } function s0_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 28); var c1_hi = rotr64_hi(xl, xh, 2); // 34 var c2_hi = rotr64_hi(xl, xh, 7); // 39 var r = c0_hi ^ c1_hi ^ c2_hi; if (r < 0) r += 0x100000000; return r; } function s0_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 28); var c1_lo = rotr64_lo(xl, xh, 2); // 34 var c2_lo = rotr64_lo(xl, xh, 7); // 39 var r = c0_lo ^ c1_lo ^ c2_lo; if (r < 0) r += 0x100000000; return r; } function s1_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 14); var c1_hi = rotr64_hi(xh, xl, 18); var c2_hi = rotr64_hi(xl, xh, 9); // 41 var r = c0_hi ^ c1_hi ^ c2_hi; if (r < 0) r += 0x100000000; return r; } function s1_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 14); var c1_lo = rotr64_lo(xh, xl, 18); var c2_lo = rotr64_lo(xl, xh, 9); // 41 var r = c0_lo ^ c1_lo ^ c2_lo; if (r < 0) r += 0x100000000; return r; } function g0_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 1); var c1_hi = rotr64_hi(xh, xl, 8); var c2_hi = shr64_hi(xh, xl, 7); var r = c0_hi ^ c1_hi ^ c2_hi; if (r < 0) r += 0x100000000; return r; } function g0_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 1); var c1_lo = rotr64_lo(xh, xl, 8); var c2_lo = shr64_lo(xh, xl, 7); var r = c0_lo ^ c1_lo ^ c2_lo; if (r < 0) r += 0x100000000; return r; } function g1_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 19); var c1_hi = rotr64_hi(xl, xh, 29); // 61 var c2_hi = shr64_hi(xh, xl, 6); var r = c0_hi ^ c1_hi ^ c2_hi; if (r < 0) r += 0x100000000; return r; } function g1_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 19); var c1_lo = rotr64_lo(xl, xh, 29); // 61 var c2_lo = shr64_lo(xh, xl, 6); var r = c0_lo ^ c1_lo ^ c2_lo; if (r < 0) r += 0x100000000; return r; } /***/ }), /***/ 8355: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(8244); var rotr32 = utils.rotr32; function ft_1(s, x, y, z) { if (s === 0) return ch32(x, y, z); if (s === 1 || s === 3) return p32(x, y, z); if (s === 2) return maj32(x, y, z); } exports.ft_1 = ft_1; function ch32(x, y, z) { return x & y ^ ~x & z; } exports.ch32 = ch32; function maj32(x, y, z) { return x & y ^ x & z ^ y & z; } exports.maj32 = maj32; function p32(x, y, z) { return x ^ y ^ z; } exports.p32 = p32; function s0_256(x) { return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); } exports.s0_256 = s0_256; function s1_256(x) { return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); } exports.s1_256 = s1_256; function g0_256(x) { return rotr32(x, 7) ^ rotr32(x, 18) ^ x >>> 3; } exports.g0_256 = g0_256; function g1_256(x) { return rotr32(x, 17) ^ rotr32(x, 19) ^ x >>> 10; } exports.g1_256 = g1_256; /***/ }), /***/ 8244: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var assert = __webpack_require__(1130); var inherits = __webpack_require__(376); exports.inherits = inherits; function isSurrogatePair(msg, i) { if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { return false; } if (i < 0 || i + 1 >= msg.length) { return false; } return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00; } function toArray(msg, enc) { if (Array.isArray(msg)) return msg.slice(); if (!msg) return []; var res = []; if (typeof msg === 'string') { if (!enc) { // Inspired by stringToUtf8ByteArray() in closure-library by Google // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143 // Apache License 2.0 // https://github.com/google/closure-library/blob/master/LICENSE var p = 0; for (var i = 0; i < msg.length; i++) { var c = msg.charCodeAt(i); if (c < 128) { res[p++] = c; } else if (c < 2048) { res[p++] = c >> 6 | 192; res[p++] = c & 63 | 128; } else if (isSurrogatePair(msg, i)) { c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF); res[p++] = c >> 18 | 240; res[p++] = c >> 12 & 63 | 128; res[p++] = c >> 6 & 63 | 128; res[p++] = c & 63 | 128; } else { res[p++] = c >> 12 | 224; res[p++] = c >> 6 & 63 | 128; res[p++] = c & 63 | 128; } } } else if (enc === 'hex') { msg = msg.replace(/[^a-z0-9]+/ig, ''); if (msg.length % 2 !== 0) msg = '0' + msg; for (i = 0; i < msg.length; i += 2) { res.push(parseInt(msg[i] + msg[i + 1], 16)); } } } else { for (i = 0; i < msg.length; i++) { res[i] = msg[i] | 0; } } return res; } exports.toArray = toArray; function toHex(msg) { var res = ''; for (var i = 0; i < msg.length; i++) { res += zero2(msg[i].toString(16)); } return res; } exports.toHex = toHex; function htonl(w) { var res = w >>> 24 | w >>> 8 & 0xff00 | w << 8 & 0xff0000 | (w & 0xff) << 24; return res >>> 0; } exports.htonl = htonl; function toHex32(msg, endian) { var res = ''; for (var i = 0; i < msg.length; i++) { var w = msg[i]; if (endian === 'little') w = htonl(w); res += zero8(w.toString(16)); } return res; } exports.toHex32 = toHex32; function zero2(word) { if (word.length === 1) return '0' + word;else return word; } exports.zero2 = zero2; function zero8(word) { if (word.length === 7) return '0' + word;else if (word.length === 6) return '00' + word;else if (word.length === 5) return '000' + word;else if (word.length === 4) return '0000' + word;else if (word.length === 3) return '00000' + word;else if (word.length === 2) return '000000' + word;else if (word.length === 1) return '0000000' + word;else return word; } exports.zero8 = zero8; function join32(msg, start, end, endian) { var len = end - start; assert(len % 4 === 0); var res = new Array(len / 4); for (var i = 0, k = start; i < res.length; i++, k += 4) { var w; if (endian === 'big') w = msg[k] << 24 | msg[k + 1] << 16 | msg[k + 2] << 8 | msg[k + 3];else w = msg[k + 3] << 24 | msg[k + 2] << 16 | msg[k + 1] << 8 | msg[k]; res[i] = w >>> 0; } return res; } exports.join32 = join32; function split32(msg, endian) { var res = new Array(msg.length * 4); for (var i = 0, k = 0; i < msg.length; i++, k += 4) { var m = msg[i]; if (endian === 'big') { res[k] = m >>> 24; res[k + 1] = m >>> 16 & 0xff; res[k + 2] = m >>> 8 & 0xff; res[k + 3] = m & 0xff; } else { res[k + 3] = m >>> 24; res[k + 2] = m >>> 16 & 0xff; res[k + 1] = m >>> 8 & 0xff; res[k] = m & 0xff; } } return res; } exports.split32 = split32; function rotr32(w, b) { return w >>> b | w << 32 - b; } exports.rotr32 = rotr32; function rotl32(w, b) { return w << b | w >>> 32 - b; } exports.rotl32 = rotl32; function sum32(a, b) { return a + b >>> 0; } exports.sum32 = sum32; function sum32_3(a, b, c) { return a + b + c >>> 0; } exports.sum32_3 = sum32_3; function sum32_4(a, b, c, d) { return a + b + c + d >>> 0; } exports.sum32_4 = sum32_4; function sum32_5(a, b, c, d, e) { return a + b + c + d + e >>> 0; } exports.sum32_5 = sum32_5; function sum64(buf, pos, ah, al) { var bh = buf[pos]; var bl = buf[pos + 1]; var lo = al + bl >>> 0; var hi = (lo < al ? 1 : 0) + ah + bh; buf[pos] = hi >>> 0; buf[pos + 1] = lo; } exports.sum64 = sum64; function sum64_hi(ah, al, bh, bl) { var lo = al + bl >>> 0; var hi = (lo < al ? 1 : 0) + ah + bh; return hi >>> 0; } exports.sum64_hi = sum64_hi; function sum64_lo(ah, al, bh, bl) { var lo = al + bl; return lo >>> 0; } exports.sum64_lo = sum64_lo; function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { var carry = 0; var lo = al; lo = lo + bl >>> 0; carry += lo < al ? 1 : 0; lo = lo + cl >>> 0; carry += lo < cl ? 1 : 0; lo = lo + dl >>> 0; carry += lo < dl ? 1 : 0; var hi = ah + bh + ch + dh + carry; return hi >>> 0; } exports.sum64_4_hi = sum64_4_hi; function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { var lo = al + bl + cl + dl; return lo >>> 0; } exports.sum64_4_lo = sum64_4_lo; function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { var carry = 0; var lo = al; lo = lo + bl >>> 0; carry += lo < al ? 1 : 0; lo = lo + cl >>> 0; carry += lo < cl ? 1 : 0; lo = lo + dl >>> 0; carry += lo < dl ? 1 : 0; lo = lo + el >>> 0; carry += lo < el ? 1 : 0; var hi = ah + bh + ch + dh + eh + carry; return hi >>> 0; } exports.sum64_5_hi = sum64_5_hi; function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { var lo = al + bl + cl + dl + el; return lo >>> 0; } exports.sum64_5_lo = sum64_5_lo; function rotr64_hi(ah, al, num) { var r = al << 32 - num | ah >>> num; return r >>> 0; } exports.rotr64_hi = rotr64_hi; function rotr64_lo(ah, al, num) { var r = ah << 32 - num | al >>> num; return r >>> 0; } exports.rotr64_lo = rotr64_lo; function shr64_hi(ah, al, num) { return ah >>> num; } exports.shr64_hi = shr64_hi; function shr64_lo(ah, al, num) { var r = ah << 32 - num | al >>> num; return r >>> 0; } exports.shr64_lo = shr64_lo; /***/ }), /***/ 9742: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var hash = __webpack_require__(3192); var utils = __webpack_require__(5522); var assert = __webpack_require__(1130); function HmacDRBG(options) { if (!(this instanceof HmacDRBG)) return new HmacDRBG(options); this.hash = options.hash; this.predResist = !!options.predResist; this.outLen = this.hash.outSize; this.minEntropy = options.minEntropy || this.hash.hmacStrength; this._reseed = null; this.reseedInterval = null; this.K = null; this.V = null; var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex'); var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex'); var pers = utils.toArray(options.pers, options.persEnc || 'hex'); assert(entropy.length >= this.minEntropy / 8, 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); this._init(entropy, nonce, pers); } module.exports = HmacDRBG; HmacDRBG.prototype._init = function init(entropy, nonce, pers) { var seed = entropy.concat(nonce).concat(pers); this.K = new Array(this.outLen / 8); this.V = new Array(this.outLen / 8); for (var i = 0; i < this.V.length; i++) { this.K[i] = 0x00; this.V[i] = 0x01; } this._update(seed); this._reseed = 1; this.reseedInterval = 0x1000000000000; // 2^48 }; HmacDRBG.prototype._hmac = function hmac() { return new hash.hmac(this.hash, this.K); }; HmacDRBG.prototype._update = function update(seed) { var kmac = this._hmac().update(this.V).update([0x00]); if (seed) kmac = kmac.update(seed); this.K = kmac.digest(); this.V = this._hmac().update(this.V).digest(); if (!seed) return; this.K = this._hmac().update(this.V).update([0x01]).update(seed).digest(); this.V = this._hmac().update(this.V).digest(); }; HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { // Optional entropy enc if (typeof entropyEnc !== 'string') { addEnc = add; add = entropyEnc; entropyEnc = null; } entropy = utils.toArray(entropy, entropyEnc); add = utils.toArray(add, addEnc); assert(entropy.length >= this.minEntropy / 8, 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); this._update(entropy.concat(add || [])); this._reseed = 1; }; HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { if (this._reseed > this.reseedInterval) throw new Error('Reseed is required'); // Optional encoding if (typeof enc !== 'string') { addEnc = add; add = enc; enc = null; } // Optional additional data if (add) { add = utils.toArray(add, addEnc || 'hex'); this._update(add); } var temp = []; while (temp.length < len) { this.V = this._hmac().update(this.V).digest(); temp = temp.concat(this.V); } var res = temp.slice(0, len); this._update(add); this._reseed++; return utils.encode(res, enc); }; /***/ }), /***/ 8405: /***/ ((__unused_webpack_module, exports) => { /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var nBits = -7; var i = isLE ? nBytes - 1 : 0; var d = isLE ? -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.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c; 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 = isLE ? 0 : nBytes - 1; var d = isLE ? 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) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = e << mLen | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128; }; /***/ }), /***/ 376: /***/ ((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() {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } }; } /***/ }), /***/ 2755: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var hasToStringTag = __webpack_require__(5994)(); var callBound = __webpack_require__(8780); var $toString = callBound('Object.prototype.toString'); var isStandardArguments = function isArguments(value) { if (hasToStringTag && value && _typeof(value) === 'object' && Symbol.toStringTag in value) { return false; } return $toString(value) === '[object Arguments]'; }; var isLegacyArguments = function isArguments(value) { if (isStandardArguments(value)) { return true; } return value !== null && _typeof(value) === 'object' && typeof value.length === 'number' && value.length >= 0 && $toString(value) !== '[object Array]' && $toString(value.callee) === '[object Function]'; }; var supportsStandardArguments = function () { return isStandardArguments(arguments); }(); isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; /***/ }), /***/ 8625: /***/ ((module) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var fnToStr = Function.prototype.toString; var reflectApply = (typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === 'object' && Reflect !== null && Reflect.apply; var badArrayLike; var isCallableMarker; if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') { try { badArrayLike = Object.defineProperty({}, 'length', { get: function get() { throw isCallableMarker; } }); isCallableMarker = {}; // eslint-disable-next-line no-throw-literal reflectApply(function () { throw 42; }, null, badArrayLike); } catch (_) { if (_ !== isCallableMarker) { reflectApply = null; } } } else { reflectApply = null; } var constructorRegex = /^\s*class\b/; var isES6ClassFn = function isES6ClassFunction(value) { try { var fnStr = fnToStr.call(value); return constructorRegex.test(fnStr); } catch (e) { return false; // not a function } }; var tryFunctionObject = function tryFunctionToStr(value) { try { if (isES6ClassFn(value)) { return false; } fnToStr.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var fnClass = '[object Function]'; var genClass = '[object GeneratorFunction]'; var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag` /* globals document: false */ var documentDotAll = (typeof document === "undefined" ? "undefined" : _typeof(document)) === 'object' && typeof document.all === 'undefined' && document.all !== undefined ? document.all : {}; module.exports = reflectApply ? function isCallable(value) { if (value === documentDotAll) { return true; } if (!value) { return false; } if (typeof value !== 'function' && _typeof(value) !== 'object') { return false; } if (typeof value === 'function' && !value.prototype) { return true; } try { reflectApply(value, null, badArrayLike); } catch (e) { if (e !== isCallableMarker) { return false; } } return !isES6ClassFn(value); } : function isCallable(value) { if (value === documentDotAll) { return true; } if (!value) { return false; } if (typeof value !== 'function' && _typeof(value) !== 'object') { return false; } if (typeof value === 'function' && !value.prototype) { return true; } if (hasToStringTag) { return tryFunctionObject(value); } if (isES6ClassFn(value)) { return false; } var strClass = toStr.call(value); return strClass === fnClass || strClass === genClass; }; /***/ }), /***/ 6738: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var toStr = Object.prototype.toString; var fnToStr = Function.prototype.toString; var isFnRegex = /^\s*(?:function)?\*/; var hasToStringTag = __webpack_require__(5994)(); var getProto = Object.getPrototypeOf; var getGeneratorFunc = function getGeneratorFunc() { // eslint-disable-line consistent-return if (!hasToStringTag) { return false; } try { return Function('return function*() {}')(); } catch (e) {} }; var GeneratorFunction; module.exports = function isGeneratorFunction(fn) { if (typeof fn !== 'function') { return false; } if (isFnRegex.test(fnToStr.call(fn))) { return true; } if (!hasToStringTag) { var str = toStr.call(fn); return str === '[object GeneratorFunction]'; } if (!getProto) { return false; } if (typeof GeneratorFunction === 'undefined') { var generatorFunc = getGeneratorFunc(); GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; } return getProto(fn) === GeneratorFunction; }; /***/ }), /***/ 2703: /***/ ((module) => { "use strict"; /* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ module.exports = function isNaN(value) { return value !== value; }; /***/ }), /***/ 2191: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var callBind = __webpack_require__(3862); var define = __webpack_require__(7921); var implementation = __webpack_require__(2703); var getPolyfill = __webpack_require__(4828); var shim = __webpack_require__(2568); var polyfill = callBind(getPolyfill(), Number); /* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ define(polyfill, { getPolyfill: getPolyfill, implementation: implementation, shim: shim }); module.exports = polyfill; /***/ }), /***/ 4828: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var implementation = __webpack_require__(2703); module.exports = function getPolyfill() { if (Number.isNaN && Number.isNaN(NaN) && !Number.isNaN('a')) { return Number.isNaN; } return implementation; }; /***/ }), /***/ 2568: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var define = __webpack_require__(7921); var getPolyfill = __webpack_require__(4828); /* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ module.exports = function shimNumberIsNaN() { var polyfill = getPolyfill(); define(Number, { isNaN: polyfill }, { isNaN: function testIsNaN() { return Number.isNaN !== polyfill; } }); return polyfill; }; /***/ }), /***/ 7913: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var forEach = __webpack_require__(5337); var availableTypedArrays = __webpack_require__(6461); var callBound = __webpack_require__(8780); var $toString = callBound('Object.prototype.toString'); var hasToStringTag = __webpack_require__(5994)(); var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; var typedArrays = availableTypedArrays(); var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { for (var i = 0; i < array.length; i += 1) { if (array[i] === value) { return i; } } return -1; }; var $slice = callBound('String.prototype.slice'); var toStrTags = {}; var gOPD = __webpack_require__(3999); var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); if (hasToStringTag && gOPD && getPrototypeOf) { forEach(typedArrays, function (typedArray) { var arr = new g[typedArray](); if (Symbol.toStringTag in arr) { var proto = getPrototypeOf(arr); var descriptor = gOPD(proto, Symbol.toStringTag); if (!descriptor) { var superProto = getPrototypeOf(proto); descriptor = gOPD(superProto, Symbol.toStringTag); } toStrTags[typedArray] = descriptor.get; } }); } var tryTypedArrays = function tryAllTypedArrays(value) { var anyTrue = false; forEach(toStrTags, function (getter, typedArray) { if (!anyTrue) { try { anyTrue = getter.call(value) === typedArray; } catch (e) { /**/ } } }); return anyTrue; }; module.exports = function isTypedArray(value) { if (!value || _typeof(value) !== 'object') { return false; } if (!hasToStringTag || !(Symbol.toStringTag in value)) { var tag = $slice($toString(value), 8, -1); return $indexOf(typedArrays, tag) > -1; } if (!gOPD) { return false; } return tryTypedArrays(value); }; /***/ }), /***/ 3138: /***/ ((module) => { "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function Kareem() { this._pres = new Map(); this._posts = new Map(); } Kareem.skipWrappedFunction = function skipWrappedFunction() { if (!(this instanceof Kareem.skipWrappedFunction)) { return _construct(Kareem.skipWrappedFunction, Array.prototype.slice.call(arguments)); } this.args = Array.prototype.slice.call(arguments); }; Kareem.overwriteResult = function overwriteResult() { if (!(this instanceof Kareem.overwriteResult)) { return _construct(Kareem.overwriteResult, Array.prototype.slice.call(arguments)); } this.args = Array.prototype.slice.call(arguments); }; Kareem.prototype.execPre = function (name, context, args, callback) { if (arguments.length === 3) { callback = args; args = []; } var pres = this._pres.get(name) || []; var numPres = pres.length; var numAsyncPres = pres.numAsync || 0; var currentPre = 0; var asyncPresLeft = numAsyncPres; var done = false; var $args = args; var shouldSkipWrappedFunction = null; if (!numPres) { return nextTick(function () { callback(null); }); } var next = function next() { if (currentPre >= numPres) { return; } var pre = pres[currentPre]; if (pre.isAsync) { var args = [decorateNextFn(_next), decorateNextFn(function (error) { if (error) { if (done) { return; } if (error instanceof Kareem.skipWrappedFunction) { shouldSkipWrappedFunction = error; } else { done = true; return callback(error); } } if (--asyncPresLeft === 0 && currentPre >= numPres) { return callback(shouldSkipWrappedFunction); } })]; 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 { var maybePromiseLike = null; try { maybePromiseLike = pre.fn.call(context); } catch (err) { if (err != null) { return callback(err); } } if (isPromiseLike(maybePromiseLike)) { maybePromiseLike.then(function () { return _next(); }, function (err) { return _next(err); }); } else { if (++currentPre >= numPres) { if (asyncPresLeft > 0) { // Leave parallel hooks to run return; } else { return nextTick(function () { callback(shouldSkipWrappedFunction); }); } } next(); } } }; next.apply(null, [null].concat(args)); function _next(error) { if (error) { if (done) { return; } if (error instanceof Kareem.skipWrappedFunction) { shouldSkipWrappedFunction = error; } else { done = true; return callback(error); } } if (++currentPre >= numPres) { if (asyncPresLeft > 0) { // Leave parallel hooks to run return; } else { return callback(shouldSkipWrappedFunction); } } next.apply(context, arguments); } }; Kareem.prototype.execPreSync = function (name, context, args) { var pres = this._pres.get(name) || []; var numPres = pres.length; for (var i = 0; i < numPres; ++i) { pres[i].fn.apply(context, args || []); } }; Kareem.prototype.execPost = function (name, context, args, options, callback) { if (arguments.length < 5) { callback = options; options = null; } var posts = this._posts.get(name) || []; var numPosts = posts.length; var currentPost = 0; var firstError = null; if (options && options.error) { firstError = options.error; } if (!numPosts) { return nextTick(function () { callback.apply(null, [firstError].concat(args)); }); } var next = function next() { 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]); } } if (firstError) { if (post.length === numArgs + 2) { var _cb = decorateNextFn(function (error) { if (error) { if (error instanceof Kareem.overwriteResult) { args = error.args; if (++currentPost >= numPosts) { return callback.call(null, firstError); } return next(); } firstError = error; } if (++currentPost >= numPosts) { return callback.call(null, firstError); } next(); }); callMiddlewareFunction(post, context, [firstError].concat(newArgs).concat([_cb]), _cb); } else { if (++currentPost >= numPosts) { return callback.call(null, firstError); } next(); } } else { var _cb2 = decorateNextFn(function (error) { if (error) { if (error instanceof Kareem.overwriteResult) { args = error.args; if (++currentPost >= numPosts) { return callback.apply(null, [null].concat(args)); } return next(); } firstError = error; return next(); } if (++currentPost >= numPosts) { return callback.apply(null, [null].concat(args)); } next(); }); 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([_cb2]), _cb2); } else { var error; var maybePromiseLike; try { maybePromiseLike = post.apply(context, newArgs); } catch (err) { error = err; firstError = err; } if (isPromiseLike(maybePromiseLike)) { return maybePromiseLike.then(function (res) { _cb2(res instanceof Kareem.overwriteResult ? res : null); }, function (err) { return _cb2(err); }); } if (maybePromiseLike instanceof Kareem.overwriteResult) { args = maybePromiseLike.args; } if (++currentPost >= numPosts) { return callback.apply(null, [error].concat(args)); } next(); } } }; next(); }; Kareem.prototype.execPostSync = function (name, context, args) { var posts = this._posts.get(name) || []; var numPosts = posts.length; for (var i = 0; i < numPosts; ++i) { var res = posts[i].fn.apply(context, args || []); if (res instanceof Kareem.overwriteResult) { args = res.args; } } return args; }; Kareem.prototype.createWrapperSync = function (name, fn) { var kareem = this; return function syncWrapper() { kareem.execPreSync(name, this, arguments); var toReturn = fn.apply(this, arguments); var result = kareem.execPostSync(name, this, [toReturn]); return result[0]; }; }; function _handleWrapError(instance, error, name, context, args, options, callback) { if (options.useErrorHandlers) { return instance.execPost(name, context, args, { error: error }, function (error) { return typeof callback === 'function' && callback(error); }); } else { return typeof callback === 'function' && callback(error); } } Kareem.prototype.wrap = function (name, fn, context, args, options) { var lastArg = args.length > 0 ? args[args.length - 1] : null; var argsWithoutCb = Array.from(args); typeof lastArg === 'function' && argsWithoutCb.pop(); var _this = this; options = options || {}; var checkForPromise = options.checkForPromise; this.execPre(name, context, args, function (error) { if (error && !(error instanceof Kareem.skipWrappedFunction)) { var numCallbackParams = options.numCallbackParams || 0; var errorArgs = options.contextParameter ? [context] : []; for (var i = errorArgs.length; i < numCallbackParams; ++i) { errorArgs.push(null); } return _handleWrapError(_this, error, name, context, errorArgs, options, lastArg); } var numParameters = fn.length; var ret; if (error instanceof Kareem.skipWrappedFunction) { ret = error.args[0]; return _cb.apply(void 0, [null].concat(_toConsumableArray(error.args))); } else { try { ret = fn.apply(context, argsWithoutCb.concat(_cb)); } catch (err) { return _cb(err); } } if (checkForPromise) { if (isPromiseLike(ret)) { // Thenable, use it return ret.then(function (res) { return _cb(null, res); }, function (err) { return _cb(err); }); } // If `fn()` doesn't have a callback argument and doesn't return a // promise, assume it is sync if (numParameters < argsWithoutCb.length + 1) { return _cb(null, ret); } } function _cb() { var argsWithoutError = Array.from(arguments); argsWithoutError.shift(); 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 (lastArg === null) { return; } arguments[0] ? lastArg(arguments[0]) : lastArg.apply(context, arguments); }); } } }); }; Kareem.prototype.filter = function (fn) { var _this2 = this; var clone = this.clone(); var pres = Array.from(clone._pres.keys()); var _loop = function _loop() { var name = _pres[_i]; var hooks = _this2._pres.get(name).map(function (h) { return Object.assign({}, h, { name: name }); }).filter(fn); if (hooks.length === 0) { clone._pres["delete"](name); return "continue"; } hooks.numAsync = hooks.filter(function (h) { return h.isAsync; }).length; clone._pres.set(name, hooks); }; for (var _i = 0, _pres = pres; _i < _pres.length; _i++) { var _ret = _loop(); if (_ret === "continue") continue; } var posts = Array.from(clone._posts.keys()); var _loop2 = function _loop2() { var name = _posts[_i2]; var hooks = _this2._posts.get(name).map(function (h) { return Object.assign({}, h, { name: name }); }).filter(fn); if (hooks.length === 0) { clone._posts["delete"](name); return "continue"; } clone._posts.set(name, hooks); }; for (var _i2 = 0, _posts = posts; _i2 < _posts.length; _i2++) { var _ret2 = _loop2(); if (_ret2 === "continue") continue; } return clone; }; Kareem.prototype.hasHooks = function (name) { return this._pres.has(name) || this._posts.has(name); }; 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 () { var _arguments = arguments, _this3 = this; nextTick(function () { return fn.apply(_this3, _arguments); }); }; } return function () { var _context = context || this; _this.wrap(name, fn, _context, Array.from(arguments), options); }; }; Kareem.prototype.pre = function (name, isAsync, fn, error, unshift) { var options = {}; if (_typeof(isAsync) === 'object' && isAsync !== null) { options = isAsync; isAsync = options.isAsync; } else if (typeof arguments[1] !== 'boolean') { fn = isAsync; isAsync = false; } var pres = this._pres.get(name) || []; this._pres.set(name, pres); if (isAsync) { pres.numAsync = pres.numAsync || 0; ++pres.numAsync; } if (typeof fn !== 'function') { throw new Error('pre() requires a function, got "' + _typeof(fn) + '"'); } if (unshift) { pres.unshift(Object.assign({}, options, { fn: fn, isAsync: isAsync })); } else { pres.push(Object.assign({}, options, { fn: fn, isAsync: isAsync })); } return this; }; Kareem.prototype.post = function (name, options, fn, unshift) { var hooks = this._posts.get(name) || []; if (typeof options === 'function') { unshift = !!fn; fn = options; options = {}; } if (typeof fn !== 'function') { throw new Error('post() requires a function, got "' + _typeof(fn) + '"'); } 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 () { var n = new Kareem(); var _iterator = _createForOfIteratorHelper(this._pres.keys()), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var key = _step.value; var clone = this._pres.get(key).slice(); clone.numAsync = this._pres.get(key).numAsync; n._pres.set(key, clone); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } var _iterator2 = _createForOfIteratorHelper(this._posts.keys()), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var _key = _step2.value; n._posts.set(_key, this._posts.get(_key).slice()); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return n; }; Kareem.prototype.merge = function (other, clone) { clone = arguments.length === 1 ? true : clone; var ret = clone ? this.clone() : this; var _iterator3 = _createForOfIteratorHelper(other._pres.keys()), _step3; try { var _loop3 = function _loop3() { var key = _step3.value; var sourcePres = ret._pres.get(key) || []; var deduplicated = other._pres.get(key). // Deduplicate based on `fn` filter(function (p) { return sourcePres.map(function (_p) { return _p.fn; }).indexOf(p.fn) === -1; }); var combined = sourcePres.concat(deduplicated); combined.numAsync = sourcePres.numAsync || 0; combined.numAsync += deduplicated.filter(function (p) { return p.isAsync; }).length; ret._pres.set(key, combined); }; for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { _loop3(); } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } var _iterator4 = _createForOfIteratorHelper(other._posts.keys()), _step4; try { var _loop4 = function _loop4() { var key = _step4.value; var sourcePosts = ret._posts.get(key) || []; var deduplicated = other._posts.get(key).filter(function (p) { return sourcePosts.indexOf(p) === -1; }); ret._posts.set(key, sourcePosts.concat(deduplicated)); }; for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { _loop4(); } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } return ret; }; function callMiddlewareFunction(fn, context, args, next) { var maybePromiseLike; try { maybePromiseLike = fn.apply(context, args); } catch (error) { return next(error); } if (isPromiseLike(maybePromiseLike)) { maybePromiseLike.then(function () { return next(); }, function (err) { return next(err); }); } } function isPromiseLike(v) { return _typeof(v) === 'object' && v !== null && typeof v.then === 'function'; } function decorateNextFn(fn) { var called = false; var _this = this; return function () { var _arguments2 = arguments; // 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 nextTick(function () { return fn.apply(_this, _arguments2); }); }; } var nextTick = (typeof ({env:{}}) === "undefined" ? "undefined" : _typeof(({env:{}}))) === 'object' && ({env:{}}) !== null && ({env:{}}).nextTick || function nextTick(cb) { setTimeout(cb, 0); }; module.exports = Kareem; /***/ }), /***/ 722: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var inherits = __webpack_require__(376); var HashBase = __webpack_require__(5125); var Buffer = (__webpack_require__(9047).Buffer); var ARRAY16 = new Array(16); function MD5() { HashBase.call(this, 64); // state this._a = 0x67452301; this._b = 0xefcdab89; this._c = 0x98badcfe; this._d = 0x10325476; } inherits(MD5, HashBase); MD5.prototype._update = function () { var M = ARRAY16; for (var i = 0; i < 16; ++i) { M[i] = this._block.readInt32LE(i * 4); } var a = this._a; var b = this._b; var c = this._c; var d = this._d; a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); c = fnF(c, d, a, b, M[2], 0x242070db, 17); b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); c = fnF(c, d, a, b, M[6], 0xa8304613, 17); b = fnF(b, c, d, a, M[7], 0xfd469501, 22); a = fnF(a, b, c, d, M[8], 0x698098d8, 7); d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); a = fnF(a, b, c, d, M[12], 0x6b901122, 7); d = fnF(d, a, b, c, M[13], 0xfd987193, 12); c = fnF(c, d, a, b, M[14], 0xa679438e, 17); b = fnF(b, c, d, a, M[15], 0x49b40821, 22); a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); d = fnG(d, a, b, c, M[6], 0xc040b340, 9); c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); d = fnG(d, a, b, c, M[10], 0x02441453, 9); c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); d = fnH(d, a, b, c, M[8], 0x8771f681, 11); c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); b = fnH(b, c, d, a, M[6], 0x04881d05, 23); a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); a = fnI(a, b, c, d, M[0], 0xf4292244, 6); d = fnI(d, a, b, c, M[7], 0x432aff97, 10); c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); c = fnI(c, d, a, b, M[6], 0xa3014314, 15); b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); this._a = this._a + a | 0; this._b = this._b + b | 0; this._c = this._c + c | 0; this._d = this._d + d | 0; }; MD5.prototype._digest = function () { // create padding and handle blocks this._block[this._blockOffset++] = 0x80; if (this._blockOffset > 56) { this._block.fill(0, this._blockOffset, 64); this._update(); this._blockOffset = 0; } this._block.fill(0, this._blockOffset, 56); this._block.writeUInt32LE(this._length[0], 56); this._block.writeUInt32LE(this._length[1], 60); this._update(); // produce result var buffer = Buffer.allocUnsafe(16); buffer.writeInt32LE(this._a, 0); buffer.writeInt32LE(this._b, 4); buffer.writeInt32LE(this._c, 8); buffer.writeInt32LE(this._d, 12); return buffer; }; function rotl(x, n) { return x << n | x >>> 32 - n; } function fnF(a, b, c, d, m, k, s) { return rotl(a + (b & c | ~b & d) + m + k | 0, s) + b | 0; } function fnG(a, b, c, d, m, k, s) { return rotl(a + (b & d | c & ~d) + m + k | 0, s) + b | 0; } function fnH(a, b, c, d, m, k, s) { return rotl(a + (b ^ c ^ d) + m + k | 0, s) + b | 0; } function fnI(a, b, c, d, m, k, s) { return rotl(a + (c ^ (b | ~d)) + m + k | 0, s) + b | 0; } module.exports = MD5; /***/ }), /***/ 9318: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var bn = __webpack_require__(6781); var brorand = __webpack_require__(7179); function MillerRabin(rand) { this.rand = rand || new brorand.Rand(); } module.exports = MillerRabin; MillerRabin.create = function create(rand) { return new MillerRabin(rand); }; MillerRabin.prototype._randbelow = function _randbelow(n) { var len = n.bitLength(); var min_bytes = Math.ceil(len / 8); // Generage random bytes until a number less than n is found. // This ensures that 0..n-1 have an equal probability of being selected. do { var a = new bn(this.rand.generate(min_bytes)); } while (a.cmp(n) >= 0); return a; }; MillerRabin.prototype._randrange = function _randrange(start, stop) { // Generate a random number greater than or equal to start and less than stop. var size = stop.sub(start); return start.add(this._randbelow(size)); }; MillerRabin.prototype.test = function test(n, k, cb) { var len = n.bitLength(); var red = bn.mont(n); var rone = new bn(1).toRed(red); if (!k) k = Math.max(1, len / 48 | 0); // Find d and s, (n - 1) = (2 ^ s) * d; var n1 = n.subn(1); for (var s = 0; !n1.testn(s); s++) {} var d = n.shrn(s); var rn1 = n1.toRed(red); var prime = true; for (; k > 0; k--) { var a = this._randrange(new bn(2), n1); if (cb) cb(a); var x = a.toRed(red).redPow(d); if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) continue; for (var i = 1; i < s; i++) { x = x.redSqr(); if (x.cmp(rone) === 0) return false; if (x.cmp(rn1) === 0) break; } if (i === s) return false; } return prime; }; MillerRabin.prototype.getDivisor = function getDivisor(n, k) { var len = n.bitLength(); var red = bn.mont(n); var rone = new bn(1).toRed(red); if (!k) k = Math.max(1, len / 48 | 0); // Find d and s, (n - 1) = (2 ^ s) * d; var n1 = n.subn(1); for (var s = 0; !n1.testn(s); s++) {} var d = n.shrn(s); var rn1 = n1.toRed(red); for (; k > 0; k--) { var a = this._randrange(new bn(2), n1); var g = n.gcd(a); if (g.cmpn(1) !== 0) return g; var x = a.toRed(red).redPow(d); if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) continue; for (var i = 1; i < s; i++) { x = x.redSqr(); if (x.cmp(rone) === 0) return x.fromRed().subn(1).gcd(n); if (x.cmp(rn1) === 0) break; } if (i === s) { x = x.redSqr(); return x.fromRed().subn(1).gcd(n); } } return false; }; /***/ }), /***/ 1130: /***/ ((module) => { module.exports = assert; function assert(val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } assert.equal = function assertEqual(l, r, msg) { if (l != r) throw new Error(msg || 'Assertion failed: ' + l + ' != ' + r); }; /***/ }), /***/ 5522: /***/ ((__unused_webpack_module, exports) => { "use strict"; var utils = exports; function toArray(msg, enc) { if (Array.isArray(msg)) return msg.slice(); if (!msg) return []; var res = []; if (typeof msg !== 'string') { for (var i = 0; i < msg.length; i++) { res[i] = msg[i] | 0; } return res; } if (enc === 'hex') { msg = msg.replace(/[^a-z0-9]+/ig, ''); if (msg.length % 2 !== 0) msg = '0' + msg; for (var i = 0; i < msg.length; i += 2) { res.push(parseInt(msg[i] + msg[i + 1], 16)); } } else { for (var i = 0; i < msg.length; i++) { var c = msg.charCodeAt(i); var hi = c >> 8; var lo = c & 0xff; if (hi) res.push(hi, lo);else res.push(lo); } } return res; } utils.toArray = toArray; function zero2(word) { if (word.length === 1) return '0' + word;else return word; } utils.zero2 = zero2; function toHex(msg) { var res = ''; for (var i = 0; i < msg.length; i++) { res += zero2(msg[i].toString(16)); } return res; } utils.toHex = toHex; utils.encode = function encode(arr, enc) { if (enc === 'hex') return toHex(arr);else return arr; }; /***/ }), /***/ 3564: /***/ ((module, exports, __webpack_require__) => { "use strict"; module.exports = exports = __webpack_require__(8424); /***/ }), /***/ 8424: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } /* eslint strict:off */ /* eslint no-var: off */ /* eslint no-redeclare: off */ var stringToParts = __webpack_require__(7355); // 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; } } map || (map = K); var parts = 'string' == typeof path ? stringToParts(path) : path; if (!Array.isArray(parts)) { throw new TypeError('Invalid `path`. Must be either string or array'); } var obj = o, part; 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])); } if (Array.isArray(obj) && !/^\d+$/.test(part)) { // reading a property from the array items var paths = parts.slice(i); // 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); }); } if (lookup) { obj = lookup(obj, part); } else { var _from = special && obj[special] ? obj[special] : obj; obj = _from instanceof Map ? _from.get(part) : _from[part]; } if (!obj) return map(obj); } return map(obj); }; /** * 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; if (!Array.isArray(parts)) { throw new TypeError('Invalid `path`. Must be either string or array'); } 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]]; } return true; }; /** * Deletes the last piece of `path` * * @param {String} path * @param {Object} o */ exports.unset = function (path, o) { var parts = typeof path === 'string' ? stringToParts(path) : path; if (!Array.isArray(parts)) { throw new TypeError('Invalid `path`. Must be either string or array'); } 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]]; } 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. */ 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; } } map || (map = K); var parts = 'string' == typeof path ? stringToParts(path) : path; if (!Array.isArray(parts)) { throw new TypeError('Invalid `path`. Must be either string or array'); } if (null == o) return; 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; } } // 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; } } 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 (lookup) { obj = lookup(obj, part); } else { var _to = special && obj[special] ? obj[special] : obj; obj = _to instanceof Map ? _to.get(part) : _to[part]; } if (!obj) return; } // process the last property of the path part = parts[len]; // use the special property if exists if (special && obj[special]) { obj = obj[special]; } // 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); } } }; /*! * Split a string path into components delimited by '.' or * '[\d+]' * * #### Example: * stringToParts('foo[0].bar.1'); // ['foo', '0', 'bar', '1'] */ exports.stringToParts = stringToParts; /*! * 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]); } } } } /*! * Returns the value passed to it. */ function K(v) { return v; } /***/ }), /***/ 7355: /***/ ((module) => { "use strict"; module.exports = function stringToParts(str) { var result = []; var curPropertyName = ''; var state = 'DEFAULT'; for (var 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); } 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]; } } if (state !== 'IMMEDIATELY_AFTER_SQUARE_BRACKETS') { result.push(curPropertyName); } return result; }; /***/ }), /***/ 3231: /***/ ((module, exports) => { "use strict"; /** * methods a collection must implement */ var methods = ['find', 'findOne', 'update', 'updateMany', 'updateOne', 'replaceOne', 'remove', 'count', 'distinct', 'findOneAndDelete', 'findOneAndUpdate', 'aggregate', 'findCursor', 'deleteOne', 'deleteMany']; /** * Collection base class from which implementations inherit */ function Collection() {} for (var i = 0, len = methods.length; i < len; ++i) { var method = methods[i]; Collection.prototype[method] = notImplemented(method); } module.exports = exports = Collection; Collection.methods = methods; /** * creates a function which throws an implementation error */ function notImplemented(method) { return function () { throw new Error('collection.' + method + ' not implemented'); }; } /***/ }), /***/ 8514: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var env = __webpack_require__(3669); if ('unknown' == env.type) { throw new Error('Unknown environment'); } module.exports = env.isNode ? __webpack_require__(1186) : env.isMongo ? __webpack_require__(3231) : __webpack_require__(3231); /***/ }), /***/ 1186: /***/ ((module, exports, __webpack_require__) => { "use strict"; /** * Module dependencies */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var Collection = __webpack_require__(3231); var NodeCollection = /*#__PURE__*/function (_Collection) { _inherits(NodeCollection, _Collection); var _super = _createSuper(NodeCollection); function NodeCollection(col) { var _this; _classCallCheck(this, NodeCollection); _this = _super.call(this); _this.collection = col; _this.collectionName = col.collectionName; return _this; } /** * find(match, options, function(err, docs)) */ _createClass(NodeCollection, [{ key: "find", value: function find(match, options, cb) { var cursor = this.collection.find(match, options); try { cursor.toArray(cb); } catch (error) { cb(error); } } /** * findOne(match, options, function(err, doc)) */ }, { key: "findOne", value: function findOne(match, options, cb) { this.collection.findOne(match, options, cb); } /** * count(match, options, function(err, count)) */ }, { key: "count", value: function count(match, options, cb) { this.collection.count(match, options, cb); } /** * distinct(prop, match, options, function(err, count)) */ }, { key: "distinct", value: function distinct(prop, match, options, cb) { this.collection.distinct(prop, match, options, cb); } /** * update(match, update, options, function(err[, result])) */ }, { key: "update", value: function update(match, _update, options, cb) { this.collection.update(match, _update, options, cb); } /** * update(match, update, options, function(err[, result])) */ }, { key: "updateMany", value: function updateMany(match, update, options, cb) { this.collection.updateMany(match, update, options, cb); } /** * update(match, update, options, function(err[, result])) */ }, { key: "updateOne", value: function updateOne(match, update, options, cb) { this.collection.updateOne(match, update, options, cb); } /** * replaceOne(match, update, options, function(err[, result])) */ }, { key: "replaceOne", value: function replaceOne(match, update, options, cb) { this.collection.replaceOne(match, update, options, cb); } /** * deleteOne(match, options, function(err[, result]) */ }, { key: "deleteOne", value: function deleteOne(match, options, cb) { this.collection.deleteOne(match, options, cb); } /** * deleteMany(match, options, function(err[, result]) */ }, { key: "deleteMany", value: function deleteMany(match, options, cb) { this.collection.deleteMany(match, options, cb); } /** * remove(match, options, function(err[, result]) */ }, { key: "remove", value: function remove(match, options, cb) { this.collection.remove(match, options, cb); } /** * findOneAndDelete(match, options, function(err[, result]) */ }, { key: "findOneAndDelete", value: function findOneAndDelete(match, options, cb) { this.collection.findOneAndDelete(match, options, cb); } /** * findOneAndUpdate(match, update, options, function(err[, result]) */ }, { key: "findOneAndUpdate", value: function findOneAndUpdate(match, update, options, cb) { this.collection.findOneAndUpdate(match, update, options, cb); } /** * var cursor = findCursor(match, options) */ }, { key: "findCursor", value: function findCursor(match, options) { return this.collection.find(match, options); } /** * aggregation(operators..., function(err, doc)) * TODO */ }]); return NodeCollection; }(Collection); /** * Expose */ module.exports = exports = NodeCollection; /***/ }), /***/ 3669: /***/ ((module, exports, __webpack_require__) => { "use strict"; /* module decorator */ module = __webpack_require__.nmd(module); /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } exports.isNode = 'undefined' != typeof ({env:{}}) && 'object' == ( false ? 0 : _typeof(module)) && 'object' == (typeof __webpack_require__.g === "undefined" ? "undefined" : _typeof(__webpack_require__.g)) && 'function' == typeof Buffer && ({env:{}}).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'; /***/ }), /***/ 5417: /***/ ((module, exports, __webpack_require__) => { "use strict"; /** * Dependencies */ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var assert = __webpack_require__(9373); var util = __webpack_require__(161); var utils = __webpack_require__(728); var debug = __webpack_require__(8801)('mquery'); /** * 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 */ function Query(criteria, options) { if (!(this instanceof Query)) return new Query(criteria, options); var proto = this.constructor.prototype; this.op = proto.op || undefined; this.options = Object.assign({}, proto.options); this._conditions = proto._conditions ? utils.clone(proto._conditions) : {}; this._fields = proto._fields ? utils.clone(proto._fields) : undefined; this._update = proto._update ? utils.clone(proto._update) : undefined; this._path = proto._path || undefined; this._distinct = proto._distinct || undefined; this._collection = proto._collection || undefined; this._traceFunction = proto._traceFunction || undefined; if (options) { this.setOptions(options); } 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 */ var $withinCmd = '$geoWithin'; Object.defineProperty(Query, 'use$geoWithin', { get: function get() { return $withinCmd == '$geoWithin'; }, set: function set(v) { if (true === v) { // mongodb >= 2.4 $withinCmd = '$geoWithin'; } else { $withinCmd = '$within'; } } }); /** * 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; }; /** * 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); var 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 = Array.isArray(options[method]) ? options[method] : [options[method]]; this[method].apply(this, args); } else { this.options[method] = options[method]; } } return this; }; /** * Sets this Querys collection. * * @param {Collection} coll * @return {Query} this */ Query.prototype.collection = function collection(coll) { this._collection = new Query.Collection(coll); return this; }; /** * 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; }; /** * 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; }; /** * 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]; } return this; } if ('object' == type && !Array.isArray(arguments[0])) { return this.merge(arguments[0]); } throw new TypeError('path must be a string or object'); }; /** * 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; }; /** * 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; }; /** * 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 (!Array.isArray(array)) array = [array]; or.push.apply(or, array); return this; }; /** * 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 (!Array.isArray(array)) array = [array]; nor.push.apply(nor, array); return this; }; /** * 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; }; /** * 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]; } var conds = this._conditions[path] === null || _typeof(this._conditions[path]) === 'object' ? this._conditions[path] : this._conditions[path] = {}; conds['$' + $conditional] = val; 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 && !Array.isArray(arguments[1])) { this._ensurePath('mod'); val = [arguments[0], arguments[1]]; path = this._path; } else if (3 === arguments.length) { val = [arguments[1], arguments[2]]; path = arguments[0]; } else { val = arguments[1]; path = arguments[0]; } var conds = this._conditions[path] || (this._conditions[path] = {}); conds.$mod = val; return 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]; } var conds = this._conditions[path] || (this._conditions[path] = {}); conds.$exists = val; return this; }; /** * 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'); } if (fn) { criteria = new Query(); fn(criteria); criteria = criteria._conditions; } var conds = this._conditions[path] || (this._conditions[path] = {}); conds.$elemMatch = criteria; return this; }; // 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; } if (2 === arguments.length) { return this.box.apply(this, arguments); } else if (2 < arguments.length) { return this.polygon.apply(this, arguments); } var area = arguments[0]; if (!area) throw new TypeError('Invalid argument'); if (area.center) return this.circle(area); if (area.box) return this.box.apply(this, area.box); if (area.polygon) return this.polygon.apply(this, area.polygon); if (area.type && area.coordinates) return this.geometry(area); throw new TypeError('Invalid argument'); }; /** * 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'); } var conds = this._conditions[path] || (this._conditions[path] = {}); conds[this._geoComparison || $withinCmd] = { $box: box }; return this; }; /** * 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', [],[],[]) val = Array.from(arguments); path = val.shift(); } else { // polygon([],[],[]) this._ensurePath('polygon'); path = this._path; val = Array.from(arguments); } var conds = this._conditions[path] || (this._conditions[path] = {}); conds[this._geoComparison || $withinCmd] = { $polygon: val }; 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 (!('radius' in val && val.center)) throw new Error('center and radius are required'); var conds = this._conditions[path] || (this._conditions[path] = {}); var type = val.spherical ? '$centerSphere' : '$center'; var wKey = this._geoComparison || $withinCmd; conds[wKey] = {}; conds[wKey][type] = [val.center, val.radius]; if ('unique' in val) conds[wKey].$uniqueDocs = !!val.unique; 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 */ 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'); } if (!val.center) { throw new Error('center is required'); } var conds = this._conditions[path] || (this._conditions[path] = {}); var type = val.spherical ? '$nearSphere' : '$near'; // center could be a GeoJSON object or an Array if (Array.isArray(val.center)) { conds[type] = val.center; var radius = 'maxDistance' in val ? val.maxDistance : null; 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 }; // 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; } } 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; } var area = arguments[0]; if (null != area && area.type && area.coordinates) return this.geometry(area); throw new TypeError('Invalid argument'); }; /** * 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()'); } var val, path; if (1 === arguments.length) { this._ensurePath('geometry'); path = this._path; val = arguments[0]; } else { throw new TypeError('Invalid argument'); } if (!(val.type && Array.isArray(val.coordinates))) { throw new TypeError('Invalid argument'); } var conds = this._conditions[path] || (this._conditions[path] = {}); conds[this._geoComparison] = { $geometry: val }; return this; }; // 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; 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 this; } if (utils.isObject(arg)) { var keys = utils.keys(arg); for (i = 0; i < keys.length; ++i) { fields[keys[i]] = arg[keys[i]]; } return this; } throw new TypeError('Invalid select() argument. Must be string or object.'); }; /** * 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 = [arguments[0], arguments[1]]; } else { path = arguments[0]; val = arguments[1]; } } else if (3 === arguments.length) { path = arguments[0]; val = [arguments[1], arguments[2]]; } var myFields = this._fields || (this._fields = {}); myFields[path] = { $slice: val }; return this; }; /** * 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; } // .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); } return this; } // .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]); } return this; } 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.'); }; /*! * @ignore */ var _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 })`'); } var s; if (value && value.$meta) { s = opts.sort || (opts.sort = {}); s[field] = { $meta: value.$meta }; return; } s = opts.sort || (opts.sort = {}); var val = String(value || 1).toLowerCase(); val = _validSortValue[val]; if (!val) throw new TypeError('Invalid sort value: { ' + field + ': ' + value + ' }'); s[field] = val; } 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 })`'); } var val = String(value || 1).toLowerCase(); val = _validSortValue[val]; if (!val) throw new TypeError('Invalid sort value: [ ' + field + ', ' + value + ' ]'); 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) { var val = String(value || 1).toLowerCase(); val = _validSortValue[val]; if (!val) throw new TypeError('Invalid sort value: < ' + key + ': ' + value + ' >'); opts.sort.set(key, val); }); } /** * 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; }; }); /** * 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; }; /** * 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; return this; }; /** * 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]; } return this; } if (typeof arg === 'string') { this.options.hint = arg; return this; } throw new TypeError('Invalid hint. ' + arg); }; /** * 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; }; /** * 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; }; /** * 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; }; /** * 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. * * * 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 */ 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; 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()` * - `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 */ 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 */ Query.prototype.merge = function (source) { if (!source) return this; if (!Query.canMerge(source)) throw new TypeError('Invalid argument. Expected instanceof mquery or plain object'); if (source instanceof Query) { // if source has a feature, apply it to ourselves if (source._conditions) { utils.merge(this._conditions, source._conditions); } if (source._fields) { this._fields || (this._fields = {}); utils.merge(this._fields, source._fields); } if (source.options) { this.options || (this.options = {}); utils.merge(this.options, source.options); } if (source._update) { this._update || (this._update = {}); utils.mergeClone(this._update, source._update); } if (source._distinct) { this._distinct = source._distinct; } return this; } // plain object utils.merge(this._conditions, source); return this; }; /** * 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); } if (!callback) return this; var conds = this._conditions; var options = this._optionsForExec(); if (this.$useProjection) { options.projection = this._fieldsForExec(); } else { options.fields = this._fieldsForExec(); } debug('find', this._collection.collectionName, conds, options); callback = this._wrapCallback('find', callback, { conditions: conds, options: options }); this._collection.find(conds, options, utils.tick(callback)); return this; }; /** * 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); } var conds = this._conditions; var options = this._optionsForExec(); if (this.$useProjection) { options.projection = this._fieldsForExec(); } else { options.fields = this._fieldsForExec(); } debug('findCursor', this._collection.collectionName, conds, options); return this._collection.findCursor(conds, options); }; /** * 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); } if (!callback) return this; var conds = this._conditions; var options = this._optionsForExec(); if (this.$useProjection) { options.projection = this._fieldsForExec(); } else { options.fields = this._fieldsForExec(); } debug('findOne', this._collection.collectionName, conds, options); callback = this._wrapCallback('findOne', callback, { conditions: conds, options: options }); this._collection.findOne(conds, options, utils.tick(callback)); 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 */ 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); } if (!callback) return this; var conds = this._conditions, options = this._optionsForExec(); debug('count', this._collection.collectionName, conds, options); callback = this._wrapCallback('count', callback, { conditions: conds, options: options }); this._collection.count(conds, options, utils.tick(callback)); return this; }; /** * 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; } } if ('string' == typeof field) { this._distinct = field; } if (Query.canMerge(criteria)) { this.merge(criteria); } if (!callback) { return this; } if (!this._distinct) { throw new Error('No value for `distinct` has been declared'); } var conds = this._conditions, options = this._optionsForExec(); debug('distinct', this._collection.collectionName, conds, options); callback = this._wrapCallback('distinct', callback, { conditions: conds, options: options }); this._collection.distinct(this._distinct, conds, options, utils.tick(callback)); return this; }; /** * 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; } } return _update(this, 'update', criteria, doc, options, force, callback); }; /** * 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; } } return _update(this, 'updateMany', criteria, doc, options, force, callback); }; /** * 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; } } return _update(this, 'updateOne', criteria, doc, options, force, callback); }; /** * 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; } } this.setOptions({ overwrite: true }); return _update(this, 'replaceOne', criteria, doc, options, force, callback); }; /*! * Internal helper for update, updateMany, updateOne */ function _update(query, op, criteria, doc, options, force, callback) { query.op = op; if (Query.canMerge(criteria)) { query.merge(criteria); } if (doc) { query._mergeUpdate(doc); } if (utils.isObject(options)) { // { overwrite: true } query.setOptions(options); } // we are done if we don't have callback and they are // not forcing an unsafe write. if (!(force || callback)) { return query; } if (!query._update || !query.options.overwrite && 0 === utils.keys(query._update).length) { callback && utils.soon(callback.bind(null, null, 0)); return query; } options = query._optionsForExec(); if (!callback) options.safe = false; criteria = query._conditions; doc = query._updateForExec(); debug('update', query._collection.collectionName, criteria, doc, options); callback = query._wrapCallback(op, callback, { conditions: criteria, doc: doc, options: options }); 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; } if (!(force || callback)) return this; var options = this._optionsForExec(); if (!callback) options.safe = false; var conds = this._conditions; debug('remove', this._collection.collectionName, conds, options); callback = this._wrapCallback('remove', callback, { conditions: conds, options: options }); 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; } if (!(force || callback)) return this; var options = this._optionsForExec(); if (!callback) options.safe = false; delete options.justOne; 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)); return this; }; /** * 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; } if (!(force || callback)) return this; var options = this._optionsForExec(); if (!callback) options.safe = false; delete options.justOne; var conds = this._conditions; 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; } } if (Query.canMerge(criteria)) { this.merge(criteria); } // apply doc if (doc) { this._mergeUpdate(doc); } options && this.setOptions(options); if (!callback) return this; var conds = this._conditions; var update = this._updateForExec(); options = this._optionsForExec(); return this._collection.findOneAndUpdate(conds, update, options, utils.tick(callback)); }; /** * 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; } // apply conditions if (Query.canMerge(conditions)) { this.merge(conditions); } // apply options options && this.setOptions(options); if (!callback) return this; options = this._optionsForExec(); var conds = this._conditions; return this._collection.findOneAndDelete(conds, options, utils.tick(callback)); }; /** * 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; var traceCallback = traceFunction && traceFunction.call(null, method, queryInfo, this); var startTime = new Date().getTime(); return function wrapperCallback(err, result) { if (traceCallback) { var millis = new Date().getTime() - startTime; traceCallback.call(null, err, result, millis); } if (callback) { callback.apply(null, arguments); } }; } return callback; }; /** * 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; }; /** * 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; } assert.ok(this.op, 'Missing query type: (find, update, etc)'); if ('update' == this.op || 'remove' == this.op) { callback || (callback = true); } var _this = this; 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; }); }); } }; /** * 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); }; }; /** * 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); }; /** * Returns a cursor for the given `find` query. * * @throws Error if operation is not a find * @returns {Cursor} MongoDB driver cursor */ Query.prototype.cursor = function () { if ('find' != this.op) throw new Error('cursor() is only available for find'); var conds = this._conditions; var options = this._optionsForExec(); if (this.$useProjection) { options.projection = this._fieldsForExec(); } else { options.fields = this._fieldsForExec(); } debug('cursor', this._collection.collectionName, conds, options); return this._collection.findCursor(conds, options); }; /** * 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); }; /** * 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; } } return true; }; /** * Determines if exclusive field selection has been made. * * query.selectedExlusively() // false * query.select('-name') * query.selectedExlusively() // true * query.selectedInclusively() // false * * @returns {Boolean} */ Query.prototype.selectedExclusively = function selectedExclusively() { 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 true; } return false; }; /** * 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); } }; /** * Returns default options. * * @return {Object} * @api private */ Query.prototype._optionsForExec = function () { var options = utils.clone(this.options); return options; }; /** * Returns fields selection for this query. * * @return {Object} * @api private */ Query.prototype._fieldsForExec = function () { return utils.clone(this._fields); }; /** * Return an update document with corrected $set operations. * * @api private */ Query.prototype._updateForExec = function () { var update = utils.clone(this._update); var ops = utils.keys(update); var ret = {}; var _iterator = _createForOfIteratorHelper(ops), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var op = _step.value; 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]; if (!~ops.indexOf('$set')) ops.push('$set'); } else if ('$set' === op) { if (!ret.$set) { ret[op] = update[op]; } } else { ret[op] = update[op]; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } this._compiledUpdate = ret; return ret; }; /** * Make sure _path is set. * * @parmam {String} method */ 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); } }; /*! * Permissions */ Query.permissions = __webpack_require__(6477); Query._isPermitted = function (a, b) { var denied = Query.permissions[b]; if (!denied) return true; return true !== denied[a]; }; Query.prototype._validate = function (action) { var fail; var validator; if (undefined === action) { validator = Query.permissions[this.op]; if ('function' != typeof validator) return true; fail = validator(this); } else if (!Query._isPermitted(action, this.op)) { fail = action; } if (fail) { throw new Error(fail + ' cannot be used with ' + this.op); } }; /** * Determines if `conds` can be merged using `mquery().merge()` * * @param {Object} conds * @return {Boolean} */ 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. */ Query.utils = utils; Query.env = __webpack_require__(3669); Query.Collection = __webpack_require__(8514); Query.BaseCollection = __webpack_require__(3231); Query.Promise = Promise; module.exports = exports = Query; // TODO // test utils /***/ }), /***/ 6477: /***/ ((__unused_webpack_module, exports) => { "use strict"; var denied = exports; denied.distinct = function (self) { if (self._fields && Object.keys(self._fields).length > 0) { return 'field selection and slice'; } var keys = Object.keys(denied.distinct); var err; 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.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 err; }; denied.findOneAndUpdate.limit = denied.findOneAndUpdate.skip = denied.findOneAndUpdate.batchSize = denied.findOneAndUpdate.maxScan = denied.findOneAndUpdate.snapshot = denied.findOneAndUpdate.tailable = 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 err; }; denied.count.slice = denied.count.batchSize = denied.count.maxScan = denied.count.snapshot = denied.count.tailable = true; /***/ }), /***/ 728: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /* provided dependency */ var Buffer = __webpack_require__(365)["Buffer"]; /*! * Module dependencies. */ 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)); } 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 ('Date' === obj.constructor.name || 'Function' === obj.constructor.name) return new obj.constructor(+obj); if ('RegExp' === obj.constructor.name) return new RegExp(obj); if ('Buffer' === obj.constructor.name) return Buffer.from(obj); } if (isObject(obj)) return exports.cloneObject(obj, options); if (obj.valueOf) return obj.valueOf(); }; /*! * ignore */ exports.cloneObject = function cloneObject(obj, options) { var minimize = options && options.minimize, ret = {}, keys = Object.keys(obj), len = keys.length; var hasKeys = false, val, k = '', i = 0; for (i = 0; i < len; ++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; } val = clone(obj[k], options); if (!minimize || 'undefined' !== typeof val) { hasKeys || (hasKeys = true); ret[k] = val; } } return minimize ? hasKeys && ret : ret; }; exports.cloneArray = function cloneArray(arr, options) { var ret = [], l = arr.length; var i = 0; for (; i < l; i++) { ret.push(clone(arr[i], options)); } return ret; }; /** * 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); }); }; }; /** * 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); for (var _i = 0, _keys = keys; _i < _keys.length; _i++) { var 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]; } } } }; /** * 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); for (var _i2 = 0, _keys2 = keys; _i2 < _keys2.length; _i2++) { var key = _keys2[_i2]; 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]); } } } }; /** * 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; } return pref; }; /** * 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; }; /** * Object.prototype.toString.call helper */ var _toString = Object.prototype.toString; exports.toString = function (arg) { return _toString.call(arg); }; /** * Determines if `arg` is an object. * * @param {Object|Array|String|Function|RegExp|any} arg * @return {Boolean} */ var isObject = exports.isObject = function (arg) { return '[object Object]' == exports.toString(arg); }; /** * Object.keys helper */ exports.keys = Object.keys; /** * Basic Object.create polyfill. * Only one argument is supported. * * Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create */ exports.create = 'function' == typeof Object.create ? Object.create : create; function create(proto) { if (arguments.length > 1) { throw new Error('Adding properties is not supported'); } function F() {} F.prototype = proto; return new F(); } /** * inheritance */ 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 */ var soon = exports.soon = 'function' == typeof setImmediate ? setImmediate : ({env:{}}).nextTick; /** * Check if this object is an arguments object * * @param {Any} v * @return {Boolean} */ exports.isArgumentsObject = function (v) { return Object.prototype.toString.call(v) === '[object Arguments]'; }; /***/ }), /***/ 2068: /***/ ((module) => { function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } /** * 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)); }; /** * 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; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ 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 */ 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' : ''); } /***/ }), /***/ 692: /***/ ((module) => { "use strict"; var numberIsNaN = function numberIsNaN(value) { return value !== value; }; module.exports = function is(a, b) { if (a === 0 && b === 0) { return 1 / a === 1 / b; } if (a === b) { return true; } if (numberIsNaN(a) && numberIsNaN(b)) { return true; } return false; }; /***/ }), /***/ 4710: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var define = __webpack_require__(7921); var callBind = __webpack_require__(3862); var implementation = __webpack_require__(692); var getPolyfill = __webpack_require__(9292); var shim = __webpack_require__(9228); var polyfill = callBind(getPolyfill(), Object); define(polyfill, { getPolyfill: getPolyfill, implementation: implementation, shim: shim }); module.exports = polyfill; /***/ }), /***/ 9292: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var implementation = __webpack_require__(692); module.exports = function getPolyfill() { return typeof Object.is === 'function' ? Object.is : implementation; }; /***/ }), /***/ 9228: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var getPolyfill = __webpack_require__(9292); var define = __webpack_require__(7921); module.exports = function shimObjectIs() { var polyfill = getPolyfill(); define(Object, { is: polyfill }, { is: function testObjectIs() { return Object.is !== polyfill; } }); return polyfill; }; /***/ }), /***/ 6164: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var keysShim; if (!Object.keys) { // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var isArgs = __webpack_require__(5184); // eslint-disable-line global-require var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor']; var equalsConstructorPrototype = function equalsConstructorPrototype(o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $applicationCache: true, $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $onmozfullscreenchange: true, $onmozfullscreenerror: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && _typeof(window[k]) === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }(); var equalsConstructorPrototypeIfNotBuggy = function equalsConstructorPrototypeIfNotBuggy(o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; keysShim = function keys(object) { var isObject = object !== null && _typeof(object) === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; } module.exports = keysShim; /***/ }), /***/ 3818: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var slice = Array.prototype.slice; var isArgs = __webpack_require__(5184); var origKeys = Object.keys; var keysShim = origKeys ? function keys(o) { return origKeys(o); } : __webpack_require__(6164); var originalKeys = Object.keys; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = function () { // Safari 5.0 bug var args = Object.keys(arguments); return args && args.length === arguments.length; }(1, 2); if (!keysWorksWithArguments) { Object.keys = function keys(object) { // eslint-disable-line func-name-matching if (isArgs(object)) { return originalKeys(slice.call(object)); } return originalKeys(object); }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; module.exports = keysShim; /***/ }), /***/ 5184: /***/ ((module) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && _typeof(value) === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; /***/ }), /***/ 7061: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js // Fedor, you are amazing. var asn1 = __webpack_require__(7406); exports.certificate = __webpack_require__(458); var RSAPrivateKey = asn1.define('RSAPrivateKey', function () { this.seq().obj(this.key('version')["int"](), this.key('modulus')["int"](), this.key('publicExponent')["int"](), this.key('privateExponent')["int"](), this.key('prime1')["int"](), this.key('prime2')["int"](), this.key('exponent1')["int"](), this.key('exponent2')["int"](), this.key('coefficient')["int"]()); }); exports.RSAPrivateKey = RSAPrivateKey; var RSAPublicKey = asn1.define('RSAPublicKey', function () { this.seq().obj(this.key('modulus')["int"](), this.key('publicExponent')["int"]()); }); exports.RSAPublicKey = RSAPublicKey; var PublicKey = asn1.define('SubjectPublicKeyInfo', function () { this.seq().obj(this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPublicKey').bitstr()); }); exports.PublicKey = PublicKey; var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () { this.seq().obj(this.key('algorithm').objid(), this.key('none').null_().optional(), this.key('curve').objid().optional(), this.key('params').seq().obj(this.key('p')["int"](), this.key('q')["int"](), this.key('g')["int"]()).optional()); }); var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () { this.seq().obj(this.key('version')["int"](), this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPrivateKey').octstr()); }); exports.PrivateKey = PrivateKeyInfo; var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () { this.seq().obj(this.key('algorithm').seq().obj(this.key('id').objid(), this.key('decrypt').seq().obj(this.key('kde').seq().obj(this.key('id').objid(), this.key('kdeparams').seq().obj(this.key('salt').octstr(), this.key('iters')["int"]())), this.key('cipher').seq().obj(this.key('algo').objid(), this.key('iv').octstr()))), this.key('subjectPrivateKey').octstr()); }); exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo; var DSAPrivateKey = asn1.define('DSAPrivateKey', function () { this.seq().obj(this.key('version')["int"](), this.key('p')["int"](), this.key('q')["int"](), this.key('g')["int"](), this.key('pub_key')["int"](), this.key('priv_key')["int"]()); }); exports.DSAPrivateKey = DSAPrivateKey; exports.DSAparam = asn1.define('DSAparam', function () { this["int"](); }); var ECPrivateKey = asn1.define('ECPrivateKey', function () { this.seq().obj(this.key('version')["int"](), this.key('privateKey').octstr(), this.key('parameters').optional().explicit(0).use(ECParameters), this.key('publicKey').optional().explicit(1).bitstr()); }); exports.ECPrivateKey = ECPrivateKey; var ECParameters = asn1.define('ECParameters', function () { this.choice({ namedCurve: this.objid() }); }); exports.signature = asn1.define('signature', function () { this.seq().obj(this.key('r')["int"](), this.key('s')["int"]()); }); /***/ }), /***/ 458: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js // thanks to @Rantanen var asn = __webpack_require__(7406); var Time = asn.define('Time', function () { this.choice({ utcTime: this.utctime(), generalTime: this.gentime() }); }); var AttributeTypeValue = asn.define('AttributeTypeValue', function () { this.seq().obj(this.key('type').objid(), this.key('value').any()); }); var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () { this.seq().obj(this.key('algorithm').objid(), this.key('parameters').optional(), this.key('curve').objid().optional()); }); var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () { this.seq().obj(this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPublicKey').bitstr()); }); var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () { this.setof(AttributeTypeValue); }); var RDNSequence = asn.define('RDNSequence', function () { this.seqof(RelativeDistinguishedName); }); var Name = asn.define('Name', function () { this.choice({ rdnSequence: this.use(RDNSequence) }); }); var Validity = asn.define('Validity', function () { this.seq().obj(this.key('notBefore').use(Time), this.key('notAfter').use(Time)); }); var Extension = asn.define('Extension', function () { this.seq().obj(this.key('extnID').objid(), this.key('critical').bool().def(false), this.key('extnValue').octstr()); }); var TBSCertificate = asn.define('TBSCertificate', function () { this.seq().obj(this.key('version').explicit(0)["int"]().optional(), this.key('serialNumber')["int"](), this.key('signature').use(AlgorithmIdentifier), this.key('issuer').use(Name), this.key('validity').use(Validity), this.key('subject').use(Name), this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), this.key('issuerUniqueID').implicit(1).bitstr().optional(), this.key('subjectUniqueID').implicit(2).bitstr().optional(), this.key('extensions').explicit(3).seqof(Extension).optional()); }); var X509Certificate = asn.define('X509Certificate', function () { this.seq().obj(this.key('tbsCertificate').use(TBSCertificate), this.key('signatureAlgorithm').use(AlgorithmIdentifier), this.key('signatureValue').bitstr()); }); module.exports = X509Certificate; /***/ }), /***/ 1120: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // adapted from https://github.com/apatil/pemstrip var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m; var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m; var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m; var evp = __webpack_require__(1248); var ciphers = __webpack_require__(4881); var Buffer = (__webpack_require__(9047).Buffer); module.exports = function (okey, password) { var key = okey.toString(); var match = key.match(findProc); var decrypted; if (!match) { var match2 = key.match(fullRegex); decrypted = Buffer.from(match2[2].replace(/[\r\n]/g, ''), 'base64'); } else { var suite = 'aes' + match[1]; var iv = Buffer.from(match[2], 'hex'); var cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ''), 'base64'); var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key; var out = []; var cipher = ciphers.createDecipheriv(suite, cipherKey, iv); out.push(cipher.update(cipherText)); out.push(cipher["final"]()); decrypted = Buffer.concat(out); } var tag = key.match(startRegex)[1]; return { tag: tag, data: decrypted }; }; /***/ }), /***/ 2914: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var asn1 = __webpack_require__(7061); var aesid = __webpack_require__(2562); var fixProc = __webpack_require__(1120); var ciphers = __webpack_require__(4881); var compat = __webpack_require__(9379); var Buffer = (__webpack_require__(9047).Buffer); module.exports = parseKeys; function parseKeys(buffer) { var password; if (_typeof(buffer) === 'object' && !Buffer.isBuffer(buffer)) { password = buffer.passphrase; buffer = buffer.key; } if (typeof buffer === 'string') { buffer = Buffer.from(buffer); } var stripped = fixProc(buffer, password); var type = stripped.tag; var data = stripped.data; var subtype, ndata; switch (type) { case 'CERTIFICATE': ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo; // falls through case 'PUBLIC KEY': if (!ndata) { ndata = asn1.PublicKey.decode(data, 'der'); } subtype = ndata.algorithm.algorithm.join('.'); switch (subtype) { case '1.2.840.113549.1.1.1': return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der'); case '1.2.840.10045.2.1': ndata.subjectPrivateKey = ndata.subjectPublicKey; return { type: 'ec', data: ndata }; case '1.2.840.10040.4.1': ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der'); return { type: 'dsa', data: ndata.algorithm.params }; default: throw new Error('unknown key id ' + subtype); } // throw new Error('unknown key type ' + type) case 'ENCRYPTED PRIVATE KEY': data = asn1.EncryptedPrivateKey.decode(data, 'der'); data = decrypt(data, password); // falls through case 'PRIVATE KEY': ndata = asn1.PrivateKey.decode(data, 'der'); subtype = ndata.algorithm.algorithm.join('.'); switch (subtype) { case '1.2.840.113549.1.1.1': return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der'); case '1.2.840.10045.2.1': return { curve: ndata.algorithm.curve, privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey }; case '1.2.840.10040.4.1': ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der'); return { type: 'dsa', params: ndata.algorithm.params }; default: throw new Error('unknown key id ' + subtype); } // throw new Error('unknown key type ' + type) case 'RSA PUBLIC KEY': return asn1.RSAPublicKey.decode(data, 'der'); case 'RSA PRIVATE KEY': return asn1.RSAPrivateKey.decode(data, 'der'); case 'DSA PRIVATE KEY': return { type: 'dsa', params: asn1.DSAPrivateKey.decode(data, 'der') }; case 'EC PRIVATE KEY': data = asn1.ECPrivateKey.decode(data, 'der'); return { curve: data.parameters.value, privateKey: data.privateKey }; default: throw new Error('unknown key type ' + type); } } parseKeys.signature = asn1.signature; function decrypt(data, password) { var salt = data.algorithm.decrypt.kde.kdeparams.salt; var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10); var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]; var iv = data.algorithm.decrypt.cipher.iv; var cipherText = data.subjectPrivateKey; var keylen = parseInt(algo.split('-')[1], 10) / 8; var key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1'); var cipher = ciphers.createDecipheriv(algo, key, iv); var out = []; out.push(cipher.update(cipherText)); out.push(cipher["final"]()); return Buffer.concat(out); } /***/ }), /***/ 9379: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { exports.pbkdf2 = __webpack_require__(8099); exports.pbkdf2Sync = __webpack_require__(3180); /***/ }), /***/ 8099: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var Buffer = (__webpack_require__(9047).Buffer); var checkParameters = __webpack_require__(2042); var defaultEncoding = __webpack_require__(8994); var sync = __webpack_require__(3180); var toBuffer = __webpack_require__(7238); var ZERO_BUF; var subtle = __webpack_require__.g.crypto && __webpack_require__.g.crypto.subtle; var toBrowser = { sha: 'SHA-1', 'sha-1': 'SHA-1', sha1: 'SHA-1', sha256: 'SHA-256', 'sha-256': 'SHA-256', sha384: 'SHA-384', 'sha-384': 'SHA-384', 'sha-512': 'SHA-512', sha512: 'SHA-512' }; var checks = []; function checkNative(algo) { if (__webpack_require__.g.process && !__webpack_require__.g.process.browser) { return Promise.resolve(false); } if (!subtle || !subtle.importKey || !subtle.deriveBits) { return Promise.resolve(false); } if (checks[algo] !== undefined) { return checks[algo]; } ZERO_BUF = ZERO_BUF || Buffer.alloc(8); var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo).then(function () { return true; })["catch"](function () { return false; }); checks[algo] = prom; return prom; } var nextTick; function getNextTick() { if (nextTick) { return nextTick; } if (__webpack_require__.g.process && __webpack_require__.g.process.nextTick) { nextTick = __webpack_require__.g.process.nextTick; } else if (__webpack_require__.g.queueMicrotask) { nextTick = __webpack_require__.g.queueMicrotask; } else if (__webpack_require__.g.setImmediate) { nextTick = __webpack_require__.g.setImmediate; } else { nextTick = __webpack_require__.g.setTimeout; } return nextTick; } function browserPbkdf2(password, salt, iterations, length, algo) { return subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveBits']).then(function (key) { return subtle.deriveBits({ name: 'PBKDF2', salt: salt, iterations: iterations, hash: { name: algo } }, key, length << 3); }).then(function (res) { return Buffer.from(res); }); } function resolvePromise(promise, callback) { promise.then(function (out) { getNextTick()(function () { callback(null, out); }); }, function (e) { getNextTick()(function () { callback(e); }); }); } module.exports = function (password, salt, iterations, keylen, digest, callback) { if (typeof digest === 'function') { callback = digest; digest = undefined; } digest = digest || 'sha1'; var algo = toBrowser[digest.toLowerCase()]; if (!algo || typeof __webpack_require__.g.Promise !== 'function') { getNextTick()(function () { var out; try { out = sync(password, salt, iterations, keylen, digest); } catch (e) { return callback(e); } callback(null, out); }); return; } checkParameters(iterations, keylen); password = toBuffer(password, defaultEncoding, 'Password'); salt = toBuffer(salt, defaultEncoding, 'Salt'); if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2'); resolvePromise(checkNative(algo).then(function (resp) { if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo); return sync(password, salt, iterations, keylen, digest); }), callback); }; /***/ }), /***/ 8994: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var defaultEncoding; /* istanbul ignore next */ if (__webpack_require__.g.process && __webpack_require__.g.process.browser) { defaultEncoding = 'utf-8'; } else if (__webpack_require__.g.process && __webpack_require__.g.process.version) { var pVersionMajor = parseInt(({env:{}}).version.split('.')[0].slice(1), 10); defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'; } else { defaultEncoding = 'utf-8'; } module.exports = defaultEncoding; /***/ }), /***/ 2042: /***/ ((module) => { var MAX_ALLOC = Math.pow(2, 30) - 1; // default in iojs module.exports = function (iterations, keylen) { if (typeof iterations !== 'number') { throw new TypeError('Iterations not a number'); } if (iterations < 0) { throw new TypeError('Bad iterations'); } if (typeof keylen !== 'number') { throw new TypeError('Key length not a number'); } if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ throw new TypeError('Bad key length'); } }; /***/ }), /***/ 3180: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var md5 = __webpack_require__(3277); var RIPEMD160 = __webpack_require__(8100); var sha = __webpack_require__(1806); var Buffer = (__webpack_require__(9047).Buffer); var checkParameters = __webpack_require__(2042); var defaultEncoding = __webpack_require__(8994); var toBuffer = __webpack_require__(7238); var ZEROS = Buffer.alloc(128); var sizes = { md5: 16, sha1: 20, sha224: 28, sha256: 32, sha384: 48, sha512: 64, rmd160: 20, ripemd160: 20 }; function Hmac(alg, key, saltLen) { var hash = getDigest(alg); var blocksize = alg === 'sha512' || alg === 'sha384' ? 128 : 64; if (key.length > blocksize) { key = hash(key); } else if (key.length < blocksize) { key = Buffer.concat([key, ZEROS], blocksize); } var ipad = Buffer.allocUnsafe(blocksize + sizes[alg]); var opad = Buffer.allocUnsafe(blocksize + sizes[alg]); for (var i = 0; i < blocksize; i++) { ipad[i] = key[i] ^ 0x36; opad[i] = key[i] ^ 0x5C; } var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4); ipad.copy(ipad1, 0, 0, blocksize); this.ipad1 = ipad1; this.ipad2 = ipad; this.opad = opad; this.alg = alg; this.blocksize = blocksize; this.hash = hash; this.size = sizes[alg]; } Hmac.prototype.run = function (data, ipad) { data.copy(ipad, this.blocksize); var h = this.hash(ipad); h.copy(this.opad, this.blocksize); return this.hash(this.opad); }; function getDigest(alg) { function shaFunc(data) { return sha(alg).update(data).digest(); } function rmd160Func(data) { return new RIPEMD160().update(data).digest(); } if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func; if (alg === 'md5') return md5; return shaFunc; } function pbkdf2(password, salt, iterations, keylen, digest) { checkParameters(iterations, keylen); password = toBuffer(password, defaultEncoding, 'Password'); salt = toBuffer(salt, defaultEncoding, 'Salt'); digest = digest || 'sha1'; var hmac = new Hmac(digest, password, salt.length); var DK = Buffer.allocUnsafe(keylen); var block1 = Buffer.allocUnsafe(salt.length + 4); salt.copy(block1, 0, 0, salt.length); var destPos = 0; var hLen = sizes[digest]; var l = Math.ceil(keylen / hLen); for (var i = 1; i <= l; i++) { block1.writeUInt32BE(i, salt.length); var T = hmac.run(block1, hmac.ipad1); var U = T; for (var j = 1; j < iterations; j++) { U = hmac.run(U, hmac.ipad2); for (var k = 0; k < hLen; k++) { T[k] ^= U[k]; } } T.copy(DK, destPos); destPos += hLen; } return DK; } module.exports = pbkdf2; /***/ }), /***/ 7238: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var Buffer = (__webpack_require__(9047).Buffer); module.exports = function (thing, encoding, name) { if (Buffer.isBuffer(thing)) { return thing; } else if (typeof thing === 'string') { return Buffer.from(thing, encoding); } else if (ArrayBuffer.isView(thing)) { return Buffer.from(thing.buffer); } else { throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView'); } }; /***/ }), /***/ 2368: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { exports.publicEncrypt = __webpack_require__(2385); exports.privateDecrypt = __webpack_require__(8752); exports.privateEncrypt = function privateEncrypt(key, buf) { return exports.publicEncrypt(key, buf, true); }; exports.publicDecrypt = function publicDecrypt(key, buf) { return exports.privateDecrypt(key, buf, true); }; /***/ }), /***/ 4075: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var createHash = __webpack_require__(8339); var Buffer = (__webpack_require__(9047).Buffer); module.exports = function (seed, len) { var t = Buffer.alloc(0); var i = 0; var c; while (t.length < len) { c = i2ops(i++); t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]); } return t.slice(0, len); }; function i2ops(c) { var out = Buffer.allocUnsafe(4); out.writeUInt32BE(c, 0); return out; } /***/ }), /***/ 8752: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var parseKeys = __webpack_require__(2914); var mgf = __webpack_require__(4075); var xor = __webpack_require__(782); var BN = __webpack_require__(6781); var crt = __webpack_require__(4364); var createHash = __webpack_require__(8339); var withPublic = __webpack_require__(1675); var Buffer = (__webpack_require__(9047).Buffer); module.exports = function privateDecrypt(privateKey, enc, reverse) { var padding; if (privateKey.padding) { padding = privateKey.padding; } else if (reverse) { padding = 1; } else { padding = 4; } var key = parseKeys(privateKey); var k = key.modulus.byteLength(); if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) { throw new Error('decryption error'); } var msg; if (reverse) { msg = withPublic(new BN(enc), key); } else { msg = crt(enc, key); } var zBuffer = Buffer.alloc(k - msg.length); msg = Buffer.concat([zBuffer, msg], k); if (padding === 4) { return oaep(key, msg); } else if (padding === 1) { return pkcs1(key, msg, reverse); } else if (padding === 3) { return msg; } else { throw new Error('unknown padding'); } }; function oaep(key, msg) { var k = key.modulus.byteLength(); var iHash = createHash('sha1').update(Buffer.alloc(0)).digest(); var hLen = iHash.length; if (msg[0] !== 0) { throw new Error('decryption error'); } var maskedSeed = msg.slice(1, hLen + 1); var maskedDb = msg.slice(hLen + 1); var seed = xor(maskedSeed, mgf(maskedDb, hLen)); var db = xor(maskedDb, mgf(seed, k - hLen - 1)); if (compare(iHash, db.slice(0, hLen))) { throw new Error('decryption error'); } var i = hLen; while (db[i] === 0) { i++; } if (db[i++] !== 1) { throw new Error('decryption error'); } return db.slice(i); } function pkcs1(key, msg, reverse) { var p1 = msg.slice(0, 2); var i = 2; var status = 0; while (msg[i++] !== 0) { if (i >= msg.length) { status++; break; } } var ps = msg.slice(2, i - 1); if (p1.toString('hex') !== '0002' && !reverse || p1.toString('hex') !== '0001' && reverse) { status++; } if (ps.length < 8) { status++; } if (status) { throw new Error('decryption error'); } return msg.slice(i); } function compare(a, b) { a = Buffer.from(a); b = Buffer.from(b); var dif = 0; var len = a.length; if (a.length !== b.length) { dif++; len = Math.min(a.length, b.length); } var i = -1; while (++i < len) { dif += a[i] ^ b[i]; } return dif; } /***/ }), /***/ 2385: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var parseKeys = __webpack_require__(2914); var randomBytes = __webpack_require__(5760); var createHash = __webpack_require__(8339); var mgf = __webpack_require__(4075); var xor = __webpack_require__(782); var BN = __webpack_require__(6781); var withPublic = __webpack_require__(1675); var crt = __webpack_require__(4364); var Buffer = (__webpack_require__(9047).Buffer); module.exports = function publicEncrypt(publicKey, msg, reverse) { var padding; if (publicKey.padding) { padding = publicKey.padding; } else if (reverse) { padding = 1; } else { padding = 4; } var key = parseKeys(publicKey); var paddedMsg; if (padding === 4) { paddedMsg = oaep(key, msg); } else if (padding === 1) { paddedMsg = pkcs1(key, msg, reverse); } else if (padding === 3) { paddedMsg = new BN(msg); if (paddedMsg.cmp(key.modulus) >= 0) { throw new Error('data too long for modulus'); } } else { throw new Error('unknown padding'); } if (reverse) { return crt(paddedMsg, key); } else { return withPublic(paddedMsg, key); } }; function oaep(key, msg) { var k = key.modulus.byteLength(); var mLen = msg.length; var iHash = createHash('sha1').update(Buffer.alloc(0)).digest(); var hLen = iHash.length; var hLen2 = 2 * hLen; if (mLen > k - hLen2 - 2) { throw new Error('message too long'); } var ps = Buffer.alloc(k - mLen - hLen2 - 2); var dblen = k - hLen - 1; var seed = randomBytes(hLen); var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen)); var maskedSeed = xor(seed, mgf(maskedDb, hLen)); return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k)); } function pkcs1(key, msg, reverse) { var mLen = msg.length; var k = key.modulus.byteLength(); if (mLen > k - 11) { throw new Error('message too long'); } var ps; if (reverse) { ps = Buffer.alloc(k - mLen - 3, 0xff); } else { ps = nonZero(k - mLen - 3); } return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k)); } function nonZero(len) { var out = Buffer.allocUnsafe(len); var i = 0; var cache = randomBytes(len * 2); var cur = 0; var num; while (i < len) { if (cur === cache.length) { cache = randomBytes(len * 2); cur = 0; } num = cache[cur++]; if (num) { out[i++] = num; } } return out; } /***/ }), /***/ 1675: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var BN = __webpack_require__(6781); var Buffer = (__webpack_require__(9047).Buffer); function withPublic(paddedMsg, key) { return Buffer.from(paddedMsg.toRed(BN.mont(key.modulus)).redPow(new BN(key.publicExponent)).fromRed().toArray()); } module.exports = withPublic; /***/ }), /***/ 782: /***/ ((module) => { module.exports = function xor(a, b) { var len = a.length; var i = -1; while (++i < len) { a[i] ^= b[i]; } return a; }; /***/ }), /***/ 5760: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // limit of Crypto.getRandomValues() // https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues var MAX_BYTES = 65536; // Node supports requesting up to this number of bytes // https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 var MAX_UINT32 = 4294967295; function oldBrowser() { throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11'); } var Buffer = (__webpack_require__(9047).Buffer); var crypto = __webpack_require__.g.crypto || __webpack_require__.g.msCrypto; if (crypto && crypto.getRandomValues) { module.exports = randomBytes; } else { module.exports = oldBrowser; } function randomBytes(size, cb) { // phantomjs needs to throw if (size > MAX_UINT32) throw new RangeError('requested too many random bytes'); var bytes = Buffer.allocUnsafe(size); if (size > 0) { // getRandomValues fails on IE if size == 0 if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues for (var generated = 0; generated < size; generated += MAX_BYTES) { // buffer.slice automatically checks if the end is past the end of // the buffer so we don't have to here crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)); } } else { crypto.getRandomValues(bytes); } } if (typeof cb === 'function') { return ({env:{}}).nextTick(function () { cb(null, bytes); }); } return bytes; } /***/ }), /***/ 9301: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; function oldBrowser() { throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11'); } var safeBuffer = __webpack_require__(9047); var randombytes = __webpack_require__(5760); var Buffer = safeBuffer.Buffer; var kBufferMaxLength = safeBuffer.kMaxLength; var crypto = __webpack_require__.g.crypto || __webpack_require__.g.msCrypto; var kMaxUint32 = Math.pow(2, 32) - 1; function assertOffset(offset, length) { if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare throw new TypeError('offset must be a number'); } if (offset > kMaxUint32 || offset < 0) { throw new TypeError('offset must be a uint32'); } if (offset > kBufferMaxLength || offset > length) { throw new RangeError('offset out of range'); } } function assertSize(size, offset, length) { if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare throw new TypeError('size must be a number'); } if (size > kMaxUint32 || size < 0) { throw new TypeError('size must be a uint32'); } if (size + offset > length || size > kBufferMaxLength) { throw new RangeError('buffer too small'); } } if (crypto && crypto.getRandomValues || !({env:{}}).browser) { exports.randomFill = randomFill; exports.randomFillSync = randomFillSync; } else { exports.randomFill = oldBrowser; exports.randomFillSync = oldBrowser; } function randomFill(buf, offset, size, cb) { if (!Buffer.isBuffer(buf) && !(buf instanceof __webpack_require__.g.Uint8Array)) { throw new TypeError('"buf" argument must be a Buffer or Uint8Array'); } if (typeof offset === 'function') { cb = offset; offset = 0; size = buf.length; } else if (typeof size === 'function') { cb = size; size = buf.length - offset; } else if (typeof cb !== 'function') { throw new TypeError('"cb" argument must be a function'); } assertOffset(offset, buf.length); assertSize(size, offset, buf.length); return actualFill(buf, offset, size, cb); } function actualFill(buf, offset, size, cb) { if (({env:{}}).browser) { var ourBuf = buf.buffer; var uint = new Uint8Array(ourBuf, offset, size); crypto.getRandomValues(uint); if (cb) { ({env:{}}).nextTick(function () { cb(null, buf); }); return; } return buf; } if (cb) { randombytes(size, function (err, bytes) { if (err) { return cb(err); } bytes.copy(buf, offset); cb(null, buf); }); return; } var bytes = randombytes(size); bytes.copy(buf, offset); return buf; } function randomFillSync(buf, offset, size) { if (typeof offset === 'undefined') { offset = 0; } if (!Buffer.isBuffer(buf) && !(buf instanceof __webpack_require__.g.Uint8Array)) { throw new TypeError('"buf" argument must be a Buffer or Uint8Array'); } assertOffset(offset, buf.length); if (size === undefined) size = buf.length - offset; assertSize(size, offset, buf.length); return actualFill(buf, offset, size); } /***/ }), /***/ 5613: /***/ ((module) => { "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var codes = {}; function createErrorType(code, message, Base) { if (!Base) { Base = Error; } function getMessage(arg1, arg2, arg3) { if (typeof message === 'string') { return message; } else { return message(arg1, arg2, arg3); } } var NodeError = /*#__PURE__*/function (_Base) { _inheritsLoose(NodeError, _Base); function NodeError(arg1, arg2, arg3) { return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; } return NodeError; }(Base); NodeError.prototype.name = Base.name; NodeError.prototype.code = code; codes[code] = NodeError; } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js function oneOf(expected, thing) { if (Array.isArray(expected)) { var len = expected.length; expected = expected.map(function (i) { return String(i); }); if (len > 2) { return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; } else if (len === 2) { return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); } else { return "of ".concat(thing, " ").concat(expected[0]); } } else { return "of ".concat(thing, " ").concat(String(expected)); } } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith function startsWith(str, search, pos) { return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith function endsWith(str, search, this_len) { if (this_len === undefined || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes function includes(str, search, start) { if (typeof start !== 'number') { start = 0; } if (start + search.length > str.length) { return false; } else { return str.indexOf(search, start) !== -1; } } createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { return 'The value "' + value + '" is invalid for option "' + name + '"'; }, TypeError); createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { // determiner: 'must be' or 'must not be' var determiner; if (typeof expected === 'string' && startsWith(expected, 'not ')) { determiner = 'must not be'; expected = expected.replace(/^not /, ''); } else { determiner = 'must be'; } var msg; if (endsWith(name, ' argument')) { // For cases like 'first argument' msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); } else { var type = includes(name, '.') ? 'property' : 'argument'; msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); } msg += ". Received type ".concat(_typeof(actual)); return msg; }, TypeError); createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { return 'The ' + name + ' method is not implemented'; }); createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); createErrorType('ERR_STREAM_DESTROYED', function (name) { return 'Cannot call ' + name + ' after a stream was destroyed'; }); createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { return 'Unknown encoding: ' + arg; }, TypeError); createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); module.exports.q = codes; /***/ }), /***/ 4611: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. /**/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); } return keys; }; /**/ module.exports = Duplex; var Readable = __webpack_require__(6751); var Writable = __webpack_require__(679); __webpack_require__(376)(Duplex, Readable); { // Allow the keys array to be GC'ed. var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); this.allowHalfOpen = true; if (options) { if (options.readable === false) this.readable = false; if (options.writable === false) this.writable = false; if (options.allowHalfOpen === false) { this.allowHalfOpen = false; this.once('end', onend); } } } Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.highWaterMark; } }); Object.defineProperty(Duplex.prototype, 'writableBuffer', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState && this._writableState.getBuffer(); } }); Object.defineProperty(Duplex.prototype, 'writableLength', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.length; } }); // the no-half-open enforcer function onend() { // If the writable side ended, then we're ok. if (this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. ({env:{}}).nextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); /***/ }), /***/ 3684: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. module.exports = PassThrough; var Transform = __webpack_require__(4951); __webpack_require__(376)(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); }; /***/ }), /***/ 6751: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. module.exports = Readable; /**/ var Duplex; /**/ Readable.ReadableState = ReadableState; /**/ var EE = (__webpack_require__(9620).EventEmitter); var EElistenerCount = function EElistenerCount(emitter, type) { return emitter.listeners(type).length; }; /**/ /**/ var Stream = __webpack_require__(6054); /**/ var Buffer = (__webpack_require__(365).Buffer); var OurUint8Array = __webpack_require__.g.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ var debugUtil = __webpack_require__(4616); var debug; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function debug() {}; } /**/ var BufferList = __webpack_require__(1843); var destroyImpl = __webpack_require__(4798); var _require = __webpack_require__(6876), getHighWaterMark = _require.getHighWaterMark; var _require$codes = (__webpack_require__(5613)/* .codes */ .q), ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. var StringDecoder; var createReadableStreamAsyncIterator; var from; __webpack_require__(376)(Readable, Stream); var errorOrDestroy = destroyImpl.errorOrDestroy; var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } function ReadableState(options, stream, isDuplex) { Duplex = Duplex || __webpack_require__(4611); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. if (typeof isDuplex !== 'boolean') 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" this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // 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; this.paused = true; // Should close be emitted on destroy. Defaults to true. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') this.autoDestroy = !!options.autoDestroy; // has it been destroyed this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = (__webpack_require__(113)/* .StringDecoder */ .s); this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || __webpack_require__(4611); if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside // the ReadableState constructor, at least with V8 6.5 var isDuplex = this instanceof Duplex; this._readableState = new ReadableState(options, this, isDuplex); // legacy this.readable = true; if (options) { if (typeof options.read === 'function') this._read = options.read; if (typeof options.destroy === 'function') this._destroy = options.destroy; } Stream.call(this); } Object.defineProperty(Readable.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (!this._readableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; } }); Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; Readable.prototype._destroy = function (err, cb) { cb(err); }; // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; } skipChunkCheck = true; } } else { skipChunkCheck = true; } return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { debug('readableAddChunk', chunk); var state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); if (er) { errorOrDestroy(stream, 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) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); } else if (state.ended) { errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); } else if (state.destroyed) { return false; } 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; maybeReadMore(stream, state); } } // We can push more data if we are below the highWaterMark. // 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. return !state.ended && (state.length < state.highWaterMark || state.length === 0); } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { state.awaitDrain = 0; stream.emit('data', chunk); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } function chunkInvalid(state, chunk) { var er; if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); } return er; } Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = (__webpack_require__(113)/* .StringDecoder */ .s); var decoder = new StringDecoder(enc); this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: var p = this._readableState.buffer.head; var content = ''; while (p !== null) { content += decoder.write(p.data); p = p.next; } this._readableState.buffer.clear(); if (content !== '') this._readableState.buffer.push(content); this._readableState.length = content.length; return this; }; // Don't raise the hwm > 1GB var MAX_HWM = 0x40000000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. 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.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } var ret; if (n > 0) ret = fromList(n, state);else ret = null; if (ret === null) { state.needReadable = state.length <= state.highWaterMark; n = 0; } else { state.length -= n; state.awaitDrain = 0; } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } if (ret !== null) this.emit('data', ret); return ret; }; function onEofChunk(stream, state) { debug('onEofChunk'); if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; if (state.sync) { // if we are sync, wait until next tick to emit the data. // Otherwise we risk emitting data in the flow() // the readable code triggers during a read() call emitReadable(stream); } else { // emit 'readable' now to make sure it gets picked up. state.needReadable = false; if (!state.emittedReadable) { state.emittedReadable = true; emitReadable_(stream); } } } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; debug('emitReadable', state.needReadable, state.emittedReadable); state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; ({env:{}}).nextTick(emitReadable_, stream); } } function emitReadable_(stream) { var state = stream._readableState; debug('emitReadable_', state.destroyed, state.length, state.ended); if (!state.destroyed && (state.length || state.ended)) { stream.emit('readable'); state.emittedReadable = false; } // The stream needs another readable event if // 1. It is not flowing, as the flow mechanism will take // care of it. // 2. It is not ended. // 3. It is below the highWaterMark, so we can schedule // another readable later. state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; ({env:{}}).nextTick(maybeReadMore_, stream, state); } } function maybeReadMore_(stream, state) { // Attempt to read more data if we should. // // The conditions for reading more data are (one of): // - Not enough data buffered (state.length < state.highWaterMark). The loop // is responsible for filling the buffer with enough data if such data // is available. If highWaterMark is 0 and we are not in the flowing mode // we should _not_ attempt to buffer any extra data. We'll get more data // when the stream consumer calls read() instead. // - No data in the buffer, and the stream is in flowing mode. In this mode // the loop below is responsible for ensuring read() is called. Failing to // call read here would abort the flow and there's no other mechanism for // continuing the flow if the stream consumer has just subscribed to the // 'data' event. // // In addition to the above conditions to keep reading data, the following // conditions prevent the data from being read: // - The stream has ended (state.ended). // - There is already a pending 'read' operation (state.reading). This is a // case where the the stream has called the implementation defined _read() // method, but they are processing the call asynchronously and have _not_ // called push() with new data. In this case we skip performing more // read()s. The execution ends in this method again after the _read() ends // up calling push() with more data. while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { var len = state.length; debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); }; Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== ({env:{}}).stdout && dest !== ({env:{}}).stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) ({env:{}}).nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; cleanup(); } } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } src.on('data', ondata); function ondata(chunk) { debug('ondata'); var ret = dest.write(chunk); debug('dest.write', ret); if (ret === false) { // 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', state.awaitDrain); state.awaitDrain++; } src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function pipeOnDrainFunctionResult() { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function (dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) { dests[i].emit('unpipe', this, { hasUnpiped: false }); } return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this, unpipeInfo); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); var state = this._readableState; if (ev === 'data') { // update readableListening so that resume() may be a no-op // a few lines down. This is needed to support once('readable'). state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused if (state.flowing !== false) this.resume(); } else if (ev === 'readable') { if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.flowing = false; state.emittedReadable = false; debug('on readable', state.length, state.reading); if (state.length) { emitReadable(this); } else if (!state.reading) { ({env:{}}).nextTick(nReadingNextTick, this); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; Readable.prototype.removeListener = function (ev, fn) { var res = Stream.prototype.removeListener.call(this, ev, fn); if (ev === 'readable') { // We need to check if there is someone still listening to // readable and reset the state. However this needs to happen // after readable has been emitted but before I/O (nextTick) to // support once('readable', fn) cycles. This means that calling // resume within the same tick will have no // effect. ({env:{}}).nextTick(updateReadableListening, this); } return res; }; Readable.prototype.removeAllListeners = function (ev) { var res = Stream.prototype.removeAllListeners.apply(this, arguments); if (ev === 'readable' || ev === undefined) { // We need to check if there is someone still listening to // readable and reset the state. However this needs to happen // after readable has been emitted but before I/O (nextTick) to // support once('readable', fn) cycles. This means that calling // resume within the same tick will have no // effect. ({env:{}}).nextTick(updateReadableListening, this); } return res; }; function updateReadableListening(self) { var state = self._readableState; state.readableListening = self.listenerCount('readable') > 0; if (state.resumeScheduled && !state.paused) { // flowing needs to be set to true now, otherwise // the upcoming resume will not flow. state.flowing = true; // crude way to check if we should resume } else if (self.listenerCount('data') > 0) { self.resume(); } } function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); // we flow only if there is no one listening // for readable, but we still have to call // resume() state.flowing = !state.readableListening; resume(this, state); } state.paused = false; return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; ({env:{}}).nextTick(resume_, stream, state); } } function resume_(stream, state) { debug('resume', state.reading); if (!state.reading) { stream.read(0); } state.resumeScheduled = false; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); if (this._readableState.flowing !== false) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } this._readableState.paused = true; return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); while (state.flowing && stream.read() !== null) { ; } } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var _this = this; var state = this._readableState; var paused = false; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); } _this.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; var ret = _this.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function methodWrap(method) { return function methodWrapReturnFunction() { return stream[method].apply(stream, arguments); }; }(i); } } // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } // when we try to consume some more bytes, simply unpause the // underlying stream. this._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return this; }; if (typeof Symbol === 'function') { Readable.prototype[Symbol.asyncIterator] = function () { if (createReadableStreamAsyncIterator === undefined) { createReadableStreamAsyncIterator = __webpack_require__(7673); } return createReadableStreamAsyncIterator(this); }; } Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._readableState.highWaterMark; } }); Object.defineProperty(Readable.prototype, 'readableBuffer', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._readableState && this._readableState.buffer; } }); Object.defineProperty(Readable.prototype, 'readableFlowing', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._readableState.flowing; }, set: function set(state) { if (this._readableState) { this._readableState.flowing = state; } } }); // exposed for testing purposes only. Readable._fromList = fromList; Object.defineProperty(Readable.prototype, 'readableLength', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._readableState.length; } }); // 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.first();else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = state.buffer.consume(n, state.decoder); } return ret; } function endReadable(stream) { var state = stream._readableState; debug('endReadable', state.endEmitted); if (!state.endEmitted) { state.ended = true; ({env:{}}).nextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { debug('endReadableNT', state.endEmitted, state.length); // 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 (state.autoDestroy) { // In case of duplex streams we need a way to detect // if the writable side is ready for autoDestroy as well var wState = stream._writableState; if (!wState || wState.autoDestroy && wState.finished) { stream.destroy(); } } } } if (typeof Symbol === 'function') { Readable.from = function (iterable, opts) { if (from === undefined) { from = __webpack_require__(3799); } return from(Readable, iterable, opts); }; } function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } /***/ }), /***/ 4951: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. module.exports = Transform; var _require$codes = (__webpack_require__(5613)/* .codes */ .q), ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; var Duplex = __webpack_require__(4611); __webpack_require__(376)(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (cb === null) { return this.emit('error', new ERR_MULTIPLE_CALLBACK()); } ts.writechunk = null; ts.writecb = null; if (data != null) // single equals check for both `null` and `undefined` this.push(data); cb(er); var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } function prefinish() { var _this = this; if (typeof this._flush === 'function' && !this._readableState.destroyed) { this._flush(function (er, data) { done(_this, er, data); }); } else { done(this, null, null); } } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; Transform.prototype._destroy = function (err, cb) { Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data != null) // single equals check for both `null` and `undefined` stream.push(data); // TODO(BridgeAR): Write a test for these two error cases // if there's nothing in the write buffer, then that means // that nothing more will ever be provided if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); return stream.push(null); } /***/ }), /***/ 679: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. module.exports = Writable; /* */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; } /* */ /**/ var Duplex; /**/ Writable.WritableState = WritableState; /**/ var internalUtil = { deprecate: __webpack_require__(8016) }; /**/ /**/ var Stream = __webpack_require__(6054); /**/ var Buffer = (__webpack_require__(365).Buffer); var OurUint8Array = __webpack_require__.g.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } var destroyImpl = __webpack_require__(4798); var _require = __webpack_require__(6876), getHighWaterMark = _require.getHighWaterMark; var _require$codes = (__webpack_require__(5613)/* .codes */ .q), ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; var errorOrDestroy = destroyImpl.errorOrDestroy; __webpack_require__(376)(Writable, Stream); function nop() {} function WritableState(options, stream, isDuplex) { Duplex = Duplex || __webpack_require__(4611); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream, // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. if (typeof isDuplex !== 'boolean') 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() this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called this.finalCalled = false; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // has it been destroyed this.destroyed = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') this.autoDestroy = !!options.autoDestroy; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function writableStateBufferGetter() { 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 value(object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function realHasInstance(object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || __webpack_require__(4611); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. // Checking for a Stream.Duplex instance is faster here instead of inside // the WritableState constructor, at least with V8 6.5 var isDuplex = this instanceof Duplex; if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); this._writableState = new WritableState(options, this, isDuplex); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options["final"] === 'function') this._final = options["final"]; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); }; function writeAfterEnd(stream, cb) { var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb errorOrDestroy(stream, er); ({env:{}}).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 er; if (chunk === null) { er = new ERR_STREAM_NULL_VALUES(); } else if (typeof chunk !== 'string' && !state.objectMode) { er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); } if (er) { errorOrDestroy(stream, er); ({env:{}}).nextTick(cb, er); return false; } return true; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { this._writableState.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); this._writableState.defaultEncoding = encoding; return this; }; Object.defineProperty(Writable.prototype, 'writableBuffer', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState && this._writableState.getBuffer(); } }); 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 get() { return this._writableState.highWaterMark; } }); // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk: chunk, encoding: encoding, isBuf: isBuf, callback: cb, next: null }; if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack ({env:{}}).nextTick(cb, er); // this can emit finish, and it will always happen // after error ({env:{}}).nextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; errorOrDestroy(stream, er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; errorOrDestroy(stream, er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state) || stream.destroyed; if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { ({env:{}}).nextTick(afterWrite, stream, state, finished, cb); } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending) endWritable(this, state, cb); return this; }; Object.defineProperty(Writable.prototype, 'writableLength', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.length; } }); 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) { errorOrDestroy(stream, 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.destroyed) { state.pendingcb++; state.finalCalled = true; ({env:{}}).nextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); if (state.autoDestroy) { // In case of duplex streams we need a way to detect // if the readable side is ready for autoDestroy as well var rState = stream._readableState; if (!rState || rState.autoDestroy && rState.endEmitted) { stream.destroy(); } } } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) ({env:{}}).nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } // reuse the free corkReq. state.corkedRequestsFree.next = corkReq; } Object.defineProperty(Writable.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { cb(err); }; /***/ }), /***/ 7673: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var _Object$setPrototypeO; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var finished = __webpack_require__(8820); var kLastResolve = Symbol('lastResolve'); var kLastReject = Symbol('lastReject'); var kError = Symbol('error'); var kEnded = Symbol('ended'); var kLastPromise = Symbol('lastPromise'); var kHandlePromise = Symbol('handlePromise'); var kStream = Symbol('stream'); function createIterResult(value, done) { return { value: value, done: done }; } function readAndResolve(iter) { var resolve = iter[kLastResolve]; if (resolve !== null) { var data = iter[kStream].read(); // we defer if data is null // we can be expecting either 'end' or // 'error' if (data !== null) { iter[kLastPromise] = null; iter[kLastResolve] = null; iter[kLastReject] = null; resolve(createIterResult(data, false)); } } } function onReadable(iter) { // we wait for the next tick, because it might // emit an error with process.nextTick ({env:{}}).nextTick(readAndResolve, iter); } function wrapForNext(lastPromise, iter) { return function (resolve, reject) { lastPromise.then(function () { if (iter[kEnded]) { resolve(createIterResult(undefined, true)); return; } iter[kHandlePromise](resolve, reject); }, reject); }; } var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { get stream() { return this[kStream]; }, next: function next() { var _this = this; // if we have detected an error in the meanwhile // reject straight away var error = this[kError]; if (error !== null) { return Promise.reject(error); } if (this[kEnded]) { return Promise.resolve(createIterResult(undefined, true)); } if (this[kStream].destroyed) { // We need to defer via nextTick because if .destroy(err) is // called, the error will be emitted via nextTick, and // we cannot guarantee that there is no error lingering around // waiting to be emitted. return new Promise(function (resolve, reject) { ({env:{}}).nextTick(function () { if (_this[kError]) { reject(_this[kError]); } else { resolve(createIterResult(undefined, true)); } }); }); } // if we have multiple next() calls // we will wait for the previous Promise to finish // this logic is optimized to support for await loops, // where next() is only called once at a time var lastPromise = this[kLastPromise]; var promise; if (lastPromise) { promise = new Promise(wrapForNext(lastPromise, this)); } else { // fast path needed to support multiple this.push() // without triggering the next() queue var data = this[kStream].read(); if (data !== null) { return Promise.resolve(createIterResult(data, false)); } promise = new Promise(this[kHandlePromise]); } this[kLastPromise] = promise; return promise; } }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { return this; }), _defineProperty(_Object$setPrototypeO, "return", function _return() { var _this2 = this; // destroy(err, cb) is a private API // we can guarantee we have that here, because we control the // Readable class this is attached to return new Promise(function (resolve, reject) { _this2[kStream].destroy(null, function (err) { if (err) { reject(err); return; } resolve(createIterResult(undefined, true)); }); }); }), _Object$setPrototypeO), AsyncIteratorPrototype); var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { var _Object$create; var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { value: stream, writable: true }), _defineProperty(_Object$create, kLastResolve, { value: null, writable: true }), _defineProperty(_Object$create, kLastReject, { value: null, writable: true }), _defineProperty(_Object$create, kError, { value: null, writable: true }), _defineProperty(_Object$create, kEnded, { value: stream._readableState.endEmitted, writable: true }), _defineProperty(_Object$create, kHandlePromise, { value: function value(resolve, reject) { var data = iterator[kStream].read(); if (data) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; resolve(createIterResult(data, false)); } else { iterator[kLastResolve] = resolve; iterator[kLastReject] = reject; } }, writable: true }), _Object$create)); iterator[kLastPromise] = null; finished(stream, function (err) { if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise // returned by next() and store the error if (reject !== null) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; reject(err); } iterator[kError] = err; return; } var resolve = iterator[kLastResolve]; if (resolve !== null) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; resolve(createIterResult(undefined, true)); } iterator[kEnded] = true; }); stream.on('readable', onReadable.bind(null, iterator)); return iterator; }; module.exports = createReadableStreamAsyncIterator; /***/ }), /***/ 1843: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var _require = __webpack_require__(365), Buffer = _require.Buffer; var _require2 = __webpack_require__(2361), inspect = _require2.inspect; var custom = inspect && inspect.custom || 'inspect'; function copyBuffer(src, target, offset) { Buffer.prototype.copy.call(src, target, offset); } module.exports = /*#__PURE__*/function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } _createClass(BufferList, [{ key: "push", value: 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; } }, { key: "unshift", value: function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; } }, { key: "shift", value: 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; } }, { key: "clear", value: function clear() { this.head = this.tail = null; this.length = 0; } }, { key: "join", value: 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; } }, { key: "concat", value: function concat(n) { if (this.length === 0) return Buffer.alloc(0); 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; } // Consumes a specified amount of bytes or characters from the buffered data. }, { key: "consume", value: function consume(n, hasStrings) { var ret; if (n < this.head.data.length) { // `slice` is the same for buffers and strings. ret = this.head.data.slice(0, n); this.head.data = this.head.data.slice(n); } else if (n === this.head.data.length) { // First chunk is a perfect match. ret = this.shift(); } else { // Result spans more than one buffer. ret = hasStrings ? this._getString(n) : this._getBuffer(n); } return ret; } }, { key: "first", value: function first() { return this.head.data; } // Consumes a specified amount of characters from the buffered data. }, { key: "_getString", value: function _getString(n) { var p = this.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) this.head = p.next;else this.head = this.tail = null; } else { this.head = p; p.data = str.slice(nb); } break; } ++c; } this.length -= c; return ret; } // Consumes a specified amount of bytes from the buffered data. }, { key: "_getBuffer", value: function _getBuffer(n) { var ret = Buffer.allocUnsafe(n); var p = this.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) this.head = p.next;else this.head = this.tail = null; } else { this.head = p; p.data = buf.slice(nb); } break; } ++c; } this.length -= c; return ret; } // Make sure the linked list only shows the minimal necessary information. }, { key: custom, value: function value(_, options) { return inspect(this, _objectSpread({}, options, { // Only inspect one level. depth: 0, // It should not recurse. customInspect: false })); } }]); return BufferList; }(); /***/ }), /***/ 4798: /***/ ((module) => { "use strict"; // undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err) { if (!this._writableState) { ({env:{}}).nextTick(emitErrorNT, this, err); } else if (!this._writableState.errorEmitted) { this._writableState.errorEmitted = true; ({env:{}}).nextTick(emitErrorNT, this, err); } } return this; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, function (err) { if (!cb && err) { if (!_this._writableState) { ({env:{}}).nextTick(emitErrorAndCloseNT, _this, err); } else if (!_this._writableState.errorEmitted) { _this._writableState.errorEmitted = true; ({env:{}}).nextTick(emitErrorAndCloseNT, _this, err); } else { ({env:{}}).nextTick(emitCloseNT, _this); } } else if (cb) { ({env:{}}).nextTick(emitCloseNT, _this); cb(err); } else { ({env:{}}).nextTick(emitCloseNT, _this); } }); return this; } function emitErrorAndCloseNT(self, err) { emitErrorNT(self, err); emitCloseNT(self); } function emitCloseNT(self) { if (self._writableState && !self._writableState.emitClose) return; if (self._readableState && !self._readableState.emitClose) return; self.emit('close'); } function undestroy() { if (this._readableState) { this._readableState.destroyed = false; this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; } if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finalCalled = false; this._writableState.prefinished = false; this._writableState.finished = false; this._writableState.errorEmitted = false; } } function emitErrorNT(self, err) { self.emit('error', err); } function errorOrDestroy(stream, err) { // We have tests that rely on errors being emitted // in the same tick, so changing this is semver major. // For now when you opt-in to autoDestroy we allow // the error to be emitted nextTick. In a future // semver major update we should change the default to this. var rState = stream._readableState; var wState = stream._writableState; if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); } module.exports = { destroy: destroy, undestroy: undestroy, errorOrDestroy: errorOrDestroy }; /***/ }), /***/ 8820: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Ported from https://github.com/mafintosh/end-of-stream with // permission from the author, Mathias Buus (@mafintosh). var ERR_STREAM_PREMATURE_CLOSE = (__webpack_require__(5613)/* .codes.ERR_STREAM_PREMATURE_CLOSE */ .q.ERR_STREAM_PREMATURE_CLOSE); function once(callback) { var called = false; return function () { if (called) return; called = true; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } callback.apply(this, args); }; } function noop() {} function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function'; } function eos(stream, opts, callback) { if (typeof opts === 'function') return eos(stream, null, opts); if (!opts) opts = {}; callback = once(callback || noop); var readable = opts.readable || opts.readable !== false && stream.readable; var writable = opts.writable || opts.writable !== false && stream.writable; var onlegacyfinish = function onlegacyfinish() { if (!stream.writable) onfinish(); }; var writableEnded = stream._writableState && stream._writableState.finished; var onfinish = function onfinish() { writable = false; writableEnded = true; if (!readable) callback.call(stream); }; var readableEnded = stream._readableState && stream._readableState.endEmitted; var onend = function onend() { readable = false; readableEnded = true; if (!writable) callback.call(stream); }; var onerror = function onerror(err) { callback.call(stream, err); }; var onclose = function onclose() { var err; if (readable && !readableEnded) { if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); return callback.call(stream, err); } if (writable && !writableEnded) { if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); return callback.call(stream, err); } }; var onrequest = function onrequest() { stream.req.on('finish', onfinish); }; if (isRequest(stream)) { stream.on('complete', onfinish); stream.on('abort', onclose); if (stream.req) onrequest();else stream.on('request', onrequest); } else if (writable && !stream._writableState) { // legacy streams stream.on('end', onlegacyfinish); stream.on('close', onlegacyfinish); } stream.on('end', onend); stream.on('finish', onfinish); if (opts.error !== false) stream.on('error', onerror); stream.on('close', onclose); return function () { stream.removeListener('complete', onfinish); stream.removeListener('abort', onclose); stream.removeListener('request', onrequest); if (stream.req) stream.req.removeListener('finish', onfinish); stream.removeListener('end', onlegacyfinish); stream.removeListener('close', onlegacyfinish); stream.removeListener('finish', onfinish); stream.removeListener('end', onend); stream.removeListener('error', onerror); stream.removeListener('close', onclose); }; } module.exports = eos; /***/ }), /***/ 3799: /***/ ((module) => { module.exports = function () { throw new Error('Readable.from is not available in the browser'); }; /***/ }), /***/ 8751: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; // Ported from https://github.com/mafintosh/pump with // permission from the author, Mathias Buus (@mafintosh). var eos; function once(callback) { var called = false; return function () { if (called) return; called = true; callback.apply(void 0, arguments); }; } var _require$codes = (__webpack_require__(5613)/* .codes */ .q), ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; function noop(err) { // Rethrow the error if it exists to avoid swallowing it if (err) throw err; } function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function'; } function destroyer(stream, reading, writing, callback) { callback = once(callback); var closed = false; stream.on('close', function () { closed = true; }); if (eos === undefined) eos = __webpack_require__(8820); eos(stream, { readable: reading, writable: writing }, function (err) { if (err) return callback(err); closed = true; callback(); }); var destroyed = false; return function (err) { if (closed) return; if (destroyed) return; destroyed = true; // request.destroy just do .end - .abort is what we want if (isRequest(stream)) return stream.abort(); if (typeof stream.destroy === 'function') return stream.destroy(); callback(err || new ERR_STREAM_DESTROYED('pipe')); }; } function call(fn) { fn(); } function pipe(from, to) { return from.pipe(to); } function popCallback(streams) { if (!streams.length) return noop; if (typeof streams[streams.length - 1] !== 'function') return noop; return streams.pop(); } function pipeline() { for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { streams[_key] = arguments[_key]; } var callback = popCallback(streams); if (Array.isArray(streams[0])) streams = streams[0]; if (streams.length < 2) { throw new ERR_MISSING_ARGS('streams'); } var error; var destroys = streams.map(function (stream, i) { var reading = i < streams.length - 1; var writing = i > 0; return destroyer(stream, reading, writing, function (err) { if (!error) error = err; if (err) destroys.forEach(call); if (reading) return; destroys.forEach(call); callback(error); }); }); return streams.reduce(pipe); } module.exports = pipeline; /***/ }), /***/ 6876: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var ERR_INVALID_OPT_VALUE = (__webpack_require__(5613)/* .codes.ERR_INVALID_OPT_VALUE */ .q.ERR_INVALID_OPT_VALUE); function highWaterMarkFrom(options, isDuplex, duplexKey) { return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; } function getHighWaterMark(state, options, duplexKey, isDuplex) { var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); if (hwm != null) { if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { var name = isDuplex ? duplexKey : 'highWaterMark'; throw new ERR_INVALID_OPT_VALUE(name, hwm); } return Math.floor(hwm); } // Default value return state.objectMode ? 16 : 16 * 1024; } module.exports = { getHighWaterMark: getHighWaterMark }; /***/ }), /***/ 6054: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = __webpack_require__(9620).EventEmitter; /***/ }), /***/ 8237: /***/ ((module, exports, __webpack_require__) => { exports = module.exports = __webpack_require__(6751); exports.Stream = exports; exports.Readable = exports; exports.Writable = __webpack_require__(679); exports.Duplex = __webpack_require__(4611); exports.Transform = __webpack_require__(4951); exports.PassThrough = __webpack_require__(3684); exports.finished = __webpack_require__(8820); exports.pipeline = __webpack_require__(8751); /***/ }), /***/ 8100: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Buffer = (__webpack_require__(365).Buffer); var inherits = __webpack_require__(376); var HashBase = __webpack_require__(5125); var ARRAY16 = new Array(16); var zl = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]; var zr = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]; var sl = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6]; var sr = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11]; var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; function RIPEMD160() { HashBase.call(this, 64); // state this._a = 0x67452301; this._b = 0xefcdab89; this._c = 0x98badcfe; this._d = 0x10325476; this._e = 0xc3d2e1f0; } inherits(RIPEMD160, HashBase); RIPEMD160.prototype._update = function () { var words = ARRAY16; for (var j = 0; j < 16; ++j) { words[j] = this._block.readInt32LE(j * 4); } var al = this._a | 0; var bl = this._b | 0; var cl = this._c | 0; var dl = this._d | 0; var el = this._e | 0; var ar = this._a | 0; var br = this._b | 0; var cr = this._c | 0; var dr = this._d | 0; var er = this._e | 0; // computation for (var i = 0; i < 80; i += 1) { var tl; var tr; if (i < 16) { tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); } else if (i < 32) { tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); } else if (i < 48) { tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); } else if (i < 64) { tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); } else { // if (i<80) { tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); } al = el; el = dl; dl = rotl(cl, 10); cl = bl; bl = tl; ar = er; er = dr; dr = rotl(cr, 10); cr = br; br = tr; } // update state var t = this._b + cl + dr | 0; this._b = this._c + dl + er | 0; this._c = this._d + el + ar | 0; this._d = this._e + al + br | 0; this._e = this._a + bl + cr | 0; this._a = t; }; RIPEMD160.prototype._digest = function () { // create padding and handle blocks this._block[this._blockOffset++] = 0x80; if (this._blockOffset > 56) { this._block.fill(0, this._blockOffset, 64); this._update(); this._blockOffset = 0; } this._block.fill(0, this._blockOffset, 56); this._block.writeUInt32LE(this._length[0], 56); this._block.writeUInt32LE(this._length[1], 60); this._update(); // produce result var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20); buffer.writeInt32LE(this._a, 0); buffer.writeInt32LE(this._b, 4); buffer.writeInt32LE(this._c, 8); buffer.writeInt32LE(this._d, 12); buffer.writeInt32LE(this._e, 16); return buffer; }; function rotl(x, n) { return x << n | x >>> 32 - n; } function fn1(a, b, c, d, e, m, k, s) { return rotl(a + (b ^ c ^ d) + m + k | 0, s) + e | 0; } function fn2(a, b, c, d, e, m, k, s) { return rotl(a + (b & c | ~b & d) + m + k | 0, s) + e | 0; } function fn3(a, b, c, d, e, m, k, s) { return rotl(a + ((b | ~c) ^ d) + m + k | 0, s) + e | 0; } function fn4(a, b, c, d, e, m, k, s) { return rotl(a + (b & d | c & ~d) + m + k | 0, s) + e | 0; } function fn5(a, b, c, d, e, m, k, s) { return rotl(a + (b ^ (c | ~d)) + m + k | 0, s) + e | 0; } module.exports = RIPEMD160; /***/ }), /***/ 9047: /***/ ((module, exports, __webpack_require__) => { /* eslint-disable node/no-deprecated-api */ var buffer = __webpack_require__(365); var Buffer = buffer.Buffer; // alternative to using Object.keys for old browsers function copyProps(src, dst) { for (var key in src) { dst[key] = src[key]; } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer; } else { // Copy properties from require('buffer') copyProps(buffer, exports); exports.Buffer = SafeBuffer; } function SafeBuffer(arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length); } // Copy static methods from Buffer copyProps(Buffer, SafeBuffer); SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number'); } return Buffer(arg, encodingOrOffset, length); }; SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number'); } var buf = Buffer(size); if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding); } else { buf.fill(fill); } } else { buf.fill(0); } return buf; }; SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number'); } return Buffer(size); }; SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number'); } return buffer.SlowBuffer(size); }; /***/ }), /***/ 8723: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* eslint-disable node/no-deprecated-api */ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var buffer = __webpack_require__(365); var Buffer = buffer.Buffer; var safer = {}; var key; for (key in buffer) { if (!buffer.hasOwnProperty(key)) continue; if (key === 'SlowBuffer' || key === 'Buffer') continue; safer[key] = buffer[key]; } var Safer = safer.Buffer = {}; for (key in Buffer) { if (!Buffer.hasOwnProperty(key)) continue; if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue; Safer[key] = Buffer[key]; } safer.Buffer.prototype = Buffer.prototype; if (!Safer.from || Safer.from === Uint8Array.from) { Safer.from = function (value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('The "value" argument must not be of type number. Received type ' + _typeof(value)); } if (value && typeof value.length === 'undefined') { throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + _typeof(value)); } return Buffer(value, encodingOrOffset, length); }; } if (!Safer.alloc) { Safer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('The "size" argument must be of type number. Received type ' + _typeof(size)); } if (size < 0 || size >= 2 * (1 << 30)) { throw new RangeError('The value "' + size + '" is invalid for option "size"'); } var buf = Buffer(size); if (!fill || fill.length === 0) { buf.fill(0); } else if (typeof encoding === 'string') { buf.fill(fill, encoding); } else { buf.fill(fill); } return buf; }; } if (!safer.kStringMaxLength) { try { safer.kStringMaxLength = ({env:{}}).binding('buffer').kStringMaxLength; } catch (e) {// we can't determine kStringMaxLength in environments where process.binding // is unsupported, so let's not set it } } if (!safer.constants) { safer.constants = { MAX_LENGTH: safer.kMaxLength }; if (safer.kStringMaxLength) { safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength; } } module.exports = safer; /***/ }), /***/ 2159: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var Buffer = (__webpack_require__(9047).Buffer); // prototype class for hash functions function Hash(blockSize, finalSize) { this._block = Buffer.alloc(blockSize); this._finalSize = finalSize; this._blockSize = blockSize; this._len = 0; } Hash.prototype.update = function (data, enc) { if (typeof data === 'string') { enc = enc || 'utf8'; data = Buffer.from(data, enc); } var block = this._block; var blockSize = this._blockSize; var length = data.length; var accum = this._len; for (var offset = 0; offset < length;) { var assigned = accum % blockSize; var remainder = Math.min(length - offset, blockSize - assigned); for (var i = 0; i < remainder; i++) { block[assigned + i] = data[offset + i]; } accum += remainder; offset += remainder; if (accum % blockSize === 0) { this._update(block); } } this._len += length; return this; }; Hash.prototype.digest = function (enc) { var rem = this._len % this._blockSize; this._block[rem] = 0x80; // zero (rem + 1) trailing bits, where (rem + 1) is the smallest // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize this._block.fill(0, rem + 1); if (rem >= this._finalSize) { this._update(this._block); this._block.fill(0); } var bits = this._len * 8; // uint32 if (bits <= 0xffffffff) { this._block.writeUInt32BE(bits, this._blockSize - 4); // uint64 } else { var lowBits = (bits & 0xffffffff) >>> 0; var highBits = (bits - lowBits) / 0x100000000; this._block.writeUInt32BE(highBits, this._blockSize - 8); this._block.writeUInt32BE(lowBits, this._blockSize - 4); } this._update(this._block); var hash = this._hash(); return enc ? hash.toString(enc) : hash; }; Hash.prototype._update = function () { throw new Error('_update must be implemented by subclass'); }; module.exports = Hash; /***/ }), /***/ 1806: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var exports = module.exports = function SHA(algorithm) { algorithm = algorithm.toLowerCase(); var Algorithm = exports[algorithm]; if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)'); return new Algorithm(); }; exports.sha = __webpack_require__(9675); exports.sha1 = __webpack_require__(2950); exports.sha224 = __webpack_require__(8881); exports.sha256 = __webpack_require__(9642); exports.sha384 = __webpack_require__(8220); exports.sha512 = __webpack_require__(6859); /***/ }), /***/ 9675: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined * in FIPS PUB 180-1 * This source code is derived from sha1.js of the same repository. * The difference between SHA-0 and SHA-1 is just a bitwise rotate left * operation was added. */ var inherits = __webpack_require__(376); var Hash = __webpack_require__(2159); var Buffer = (__webpack_require__(9047).Buffer); var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0]; var W = new Array(80); function Sha() { this.init(); this._w = W; Hash.call(this, 64, 56); } inherits(Sha, Hash); Sha.prototype.init = function () { this._a = 0x67452301; this._b = 0xefcdab89; this._c = 0x98badcfe; this._d = 0x10325476; this._e = 0xc3d2e1f0; return this; }; function rotl5(num) { return num << 5 | num >>> 27; } function rotl30(num) { return num << 30 | num >>> 2; } function ft(s, b, c, d) { if (s === 0) return b & c | ~b & d; if (s === 2) return b & c | b & d | c & d; return b ^ c ^ d; } Sha.prototype._update = function (M) { var W = this._w; var a = this._a | 0; var b = this._b | 0; var c = this._c | 0; var d = this._d | 0; var e = this._e | 0; for (var i = 0; i < 16; ++i) { W[i] = M.readInt32BE(i * 4); } for (; i < 80; ++i) { W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; } for (var j = 0; j < 80; ++j) { var s = ~~(j / 20); var t = rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s] | 0; e = d; d = c; c = rotl30(b); b = a; a = t; } this._a = a + this._a | 0; this._b = b + this._b | 0; this._c = c + this._c | 0; this._d = d + this._d | 0; this._e = e + this._e | 0; }; Sha.prototype._hash = function () { var H = Buffer.allocUnsafe(20); H.writeInt32BE(this._a | 0, 0); H.writeInt32BE(this._b | 0, 4); H.writeInt32BE(this._c | 0, 8); H.writeInt32BE(this._d | 0, 12); H.writeInt32BE(this._e | 0, 16); return H; }; module.exports = Sha; /***/ }), /***/ 2950: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined * in FIPS PUB 180-1 * Version 2.1a Copyright Paul Johnston 2000 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for details. */ var inherits = __webpack_require__(376); var Hash = __webpack_require__(2159); var Buffer = (__webpack_require__(9047).Buffer); var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0]; var W = new Array(80); function Sha1() { this.init(); this._w = W; Hash.call(this, 64, 56); } inherits(Sha1, Hash); Sha1.prototype.init = function () { this._a = 0x67452301; this._b = 0xefcdab89; this._c = 0x98badcfe; this._d = 0x10325476; this._e = 0xc3d2e1f0; return this; }; function rotl1(num) { return num << 1 | num >>> 31; } function rotl5(num) { return num << 5 | num >>> 27; } function rotl30(num) { return num << 30 | num >>> 2; } function ft(s, b, c, d) { if (s === 0) return b & c | ~b & d; if (s === 2) return b & c | b & d | c & d; return b ^ c ^ d; } Sha1.prototype._update = function (M) { var W = this._w; var a = this._a | 0; var b = this._b | 0; var c = this._c | 0; var d = this._d | 0; var e = this._e | 0; for (var i = 0; i < 16; ++i) { W[i] = M.readInt32BE(i * 4); } for (; i < 80; ++i) { W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); } for (var j = 0; j < 80; ++j) { var s = ~~(j / 20); var t = rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s] | 0; e = d; d = c; c = rotl30(b); b = a; a = t; } this._a = a + this._a | 0; this._b = b + this._b | 0; this._c = c + this._c | 0; this._d = d + this._d | 0; this._e = e + this._e | 0; }; Sha1.prototype._hash = function () { var H = Buffer.allocUnsafe(20); H.writeInt32BE(this._a | 0, 0); H.writeInt32BE(this._b | 0, 4); H.writeInt32BE(this._c | 0, 8); H.writeInt32BE(this._d | 0, 12); H.writeInt32BE(this._e | 0, 16); return H; }; module.exports = Sha1; /***/ }), /***/ 8881: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined * in FIPS 180-2 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * */ var inherits = __webpack_require__(376); var Sha256 = __webpack_require__(9642); var Hash = __webpack_require__(2159); var Buffer = (__webpack_require__(9047).Buffer); var W = new Array(64); function Sha224() { this.init(); this._w = W; // new Array(64) Hash.call(this, 64, 56); } inherits(Sha224, Sha256); Sha224.prototype.init = function () { this._a = 0xc1059ed8; this._b = 0x367cd507; this._c = 0x3070dd17; this._d = 0xf70e5939; this._e = 0xffc00b31; this._f = 0x68581511; this._g = 0x64f98fa7; this._h = 0xbefa4fa4; return this; }; Sha224.prototype._hash = function () { var H = Buffer.allocUnsafe(28); H.writeInt32BE(this._a, 0); H.writeInt32BE(this._b, 4); H.writeInt32BE(this._c, 8); H.writeInt32BE(this._d, 12); H.writeInt32BE(this._e, 16); H.writeInt32BE(this._f, 20); H.writeInt32BE(this._g, 24); return H; }; module.exports = Sha224; /***/ }), /***/ 9642: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined * in FIPS 180-2 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * */ var inherits = __webpack_require__(376); var Hash = __webpack_require__(2159); var Buffer = (__webpack_require__(9047).Buffer); var K = [0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2]; var W = new Array(64); function Sha256() { this.init(); this._w = W; // new Array(64) Hash.call(this, 64, 56); } inherits(Sha256, Hash); Sha256.prototype.init = function () { this._a = 0x6a09e667; this._b = 0xbb67ae85; this._c = 0x3c6ef372; this._d = 0xa54ff53a; this._e = 0x510e527f; this._f = 0x9b05688c; this._g = 0x1f83d9ab; this._h = 0x5be0cd19; return this; }; function ch(x, y, z) { return z ^ x & (y ^ z); } function maj(x, y, z) { return x & y | z & (x | y); } function sigma0(x) { return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10); } function sigma1(x) { return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7); } function gamma0(x) { return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ x >>> 3; } function gamma1(x) { return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ x >>> 10; } Sha256.prototype._update = function (M) { var W = this._w; var a = this._a | 0; var b = this._b | 0; var c = this._c | 0; var d = this._d | 0; var e = this._e | 0; var f = this._f | 0; var g = this._g | 0; var h = this._h | 0; for (var i = 0; i < 16; ++i) { W[i] = M.readInt32BE(i * 4); } for (; i < 64; ++i) { W[i] = gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16] | 0; } for (var j = 0; j < 64; ++j) { var T1 = h + sigma1(e) + ch(e, f, g) + K[j] + W[j] | 0; var T2 = sigma0(a) + maj(a, b, c) | 0; h = g; g = f; f = e; e = d + T1 | 0; d = c; c = b; b = a; a = T1 + T2 | 0; } this._a = a + this._a | 0; this._b = b + this._b | 0; this._c = c + this._c | 0; this._d = d + this._d | 0; this._e = e + this._e | 0; this._f = f + this._f | 0; this._g = g + this._g | 0; this._h = h + this._h | 0; }; Sha256.prototype._hash = function () { var H = Buffer.allocUnsafe(32); H.writeInt32BE(this._a, 0); H.writeInt32BE(this._b, 4); H.writeInt32BE(this._c, 8); H.writeInt32BE(this._d, 12); H.writeInt32BE(this._e, 16); H.writeInt32BE(this._f, 20); H.writeInt32BE(this._g, 24); H.writeInt32BE(this._h, 28); return H; }; module.exports = Sha256; /***/ }), /***/ 8220: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var inherits = __webpack_require__(376); var SHA512 = __webpack_require__(6859); var Hash = __webpack_require__(2159); var Buffer = (__webpack_require__(9047).Buffer); var W = new Array(160); function Sha384() { this.init(); this._w = W; Hash.call(this, 128, 112); } inherits(Sha384, SHA512); Sha384.prototype.init = function () { this._ah = 0xcbbb9d5d; this._bh = 0x629a292a; this._ch = 0x9159015a; this._dh = 0x152fecd8; this._eh = 0x67332667; this._fh = 0x8eb44a87; this._gh = 0xdb0c2e0d; this._hh = 0x47b5481d; this._al = 0xc1059ed8; this._bl = 0x367cd507; this._cl = 0x3070dd17; this._dl = 0xf70e5939; this._el = 0xffc00b31; this._fl = 0x68581511; this._gl = 0x64f98fa7; this._hl = 0xbefa4fa4; return this; }; Sha384.prototype._hash = function () { var H = Buffer.allocUnsafe(48); function writeInt64BE(h, l, offset) { H.writeInt32BE(h, offset); H.writeInt32BE(l, offset + 4); } writeInt64BE(this._ah, this._al, 0); writeInt64BE(this._bh, this._bl, 8); writeInt64BE(this._ch, this._cl, 16); writeInt64BE(this._dh, this._dl, 24); writeInt64BE(this._eh, this._el, 32); writeInt64BE(this._fh, this._fl, 40); return H; }; module.exports = Sha384; /***/ }), /***/ 6859: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var inherits = __webpack_require__(376); var Hash = __webpack_require__(2159); var Buffer = (__webpack_require__(9047).Buffer); var K = [0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817]; var W = new Array(160); function Sha512() { this.init(); this._w = W; Hash.call(this, 128, 112); } inherits(Sha512, Hash); Sha512.prototype.init = function () { this._ah = 0x6a09e667; this._bh = 0xbb67ae85; this._ch = 0x3c6ef372; this._dh = 0xa54ff53a; this._eh = 0x510e527f; this._fh = 0x9b05688c; this._gh = 0x1f83d9ab; this._hh = 0x5be0cd19; this._al = 0xf3bcc908; this._bl = 0x84caa73b; this._cl = 0xfe94f82b; this._dl = 0x5f1d36f1; this._el = 0xade682d1; this._fl = 0x2b3e6c1f; this._gl = 0xfb41bd6b; this._hl = 0x137e2179; return this; }; function Ch(x, y, z) { return z ^ x & (y ^ z); } function maj(x, y, z) { return x & y | z & (x | y); } function sigma0(x, xl) { return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25); } function sigma1(x, xl) { return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23); } function Gamma0(x, xl) { return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ x >>> 7; } function Gamma0l(x, xl) { return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25); } function Gamma1(x, xl) { return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ x >>> 6; } function Gamma1l(x, xl) { return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26); } function getCarry(a, b) { return a >>> 0 < b >>> 0 ? 1 : 0; } Sha512.prototype._update = function (M) { var W = this._w; var ah = this._ah | 0; var bh = this._bh | 0; var ch = this._ch | 0; var dh = this._dh | 0; var eh = this._eh | 0; var fh = this._fh | 0; var gh = this._gh | 0; var hh = this._hh | 0; var al = this._al | 0; var bl = this._bl | 0; var cl = this._cl | 0; var dl = this._dl | 0; var el = this._el | 0; var fl = this._fl | 0; var gl = this._gl | 0; var hl = this._hl | 0; for (var i = 0; i < 32; i += 2) { W[i] = M.readInt32BE(i * 4); W[i + 1] = M.readInt32BE(i * 4 + 4); } for (; i < 160; i += 2) { var xh = W[i - 15 * 2]; var xl = W[i - 15 * 2 + 1]; var gamma0 = Gamma0(xh, xl); var gamma0l = Gamma0l(xl, xh); xh = W[i - 2 * 2]; xl = W[i - 2 * 2 + 1]; var gamma1 = Gamma1(xh, xl); var gamma1l = Gamma1l(xl, xh); // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7h = W[i - 7 * 2]; var Wi7l = W[i - 7 * 2 + 1]; var Wi16h = W[i - 16 * 2]; var Wi16l = W[i - 16 * 2 + 1]; var Wil = gamma0l + Wi7l | 0; var Wih = gamma0 + Wi7h + getCarry(Wil, gamma0l) | 0; Wil = Wil + gamma1l | 0; Wih = Wih + gamma1 + getCarry(Wil, gamma1l) | 0; Wil = Wil + Wi16l | 0; Wih = Wih + Wi16h + getCarry(Wil, Wi16l) | 0; W[i] = Wih; W[i + 1] = Wil; } for (var j = 0; j < 160; j += 2) { Wih = W[j]; Wil = W[j + 1]; var majh = maj(ah, bh, ch); var majl = maj(al, bl, cl); var sigma0h = sigma0(ah, al); var sigma0l = sigma0(al, ah); var sigma1h = sigma1(eh, el); var sigma1l = sigma1(el, eh); // t1 = h + sigma1 + ch + K[j] + W[j] var Kih = K[j]; var Kil = K[j + 1]; var chh = Ch(eh, fh, gh); var chl = Ch(el, fl, gl); var t1l = hl + sigma1l | 0; var t1h = hh + sigma1h + getCarry(t1l, hl) | 0; t1l = t1l + chl | 0; t1h = t1h + chh + getCarry(t1l, chl) | 0; t1l = t1l + Kil | 0; t1h = t1h + Kih + getCarry(t1l, Kil) | 0; t1l = t1l + Wil | 0; t1h = t1h + Wih + getCarry(t1l, Wil) | 0; // t2 = sigma0 + maj var t2l = sigma0l + majl | 0; var t2h = sigma0h + majh + getCarry(t2l, sigma0l) | 0; hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; el = dl + t1l | 0; eh = dh + t1h + getCarry(el, dl) | 0; dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; al = t1l + t2l | 0; ah = t1h + t2h + getCarry(al, t1l) | 0; } this._al = this._al + al | 0; this._bl = this._bl + bl | 0; this._cl = this._cl + cl | 0; this._dl = this._dl + dl | 0; this._el = this._el + el | 0; this._fl = this._fl + fl | 0; this._gl = this._gl + gl | 0; this._hl = this._hl + hl | 0; this._ah = this._ah + ah + getCarry(this._al, al) | 0; this._bh = this._bh + bh + getCarry(this._bl, bl) | 0; this._ch = this._ch + ch + getCarry(this._cl, cl) | 0; this._dh = this._dh + dh + getCarry(this._dl, dl) | 0; this._eh = this._eh + eh + getCarry(this._el, el) | 0; this._fh = this._fh + fh + getCarry(this._fl, fl) | 0; this._gh = this._gh + gh + getCarry(this._gl, gl) | 0; this._hh = this._hh + hh + getCarry(this._hl, hl) | 0; }; Sha512.prototype._hash = function () { var H = Buffer.allocUnsafe(64); function writeInt64BE(h, l, offset) { H.writeInt32BE(h, offset); H.writeInt32BE(l, offset + 4); } writeInt64BE(this._ah, this._al, 0); writeInt64BE(this._bh, this._bl, 8); writeInt64BE(this._ch, this._cl, 16); writeInt64BE(this._dh, this._dl, 24); writeInt64BE(this._eh, this._el, 32); writeInt64BE(this._fh, this._fl, 40); writeInt64BE(this._gh, this._gl, 48); writeInt64BE(this._hh, this._hl, 56); return H; }; module.exports = Sha512; /***/ }), /***/ 4723: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // 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. module.exports = Stream; var EE = (__webpack_require__(9620).EventEmitter); var inherits = __webpack_require__(376); inherits(Stream, EE); Stream.Readable = __webpack_require__(6751); Stream.Writable = __webpack_require__(679); Stream.Duplex = __webpack_require__(4611); Stream.Transform = __webpack_require__(4951); Stream.PassThrough = __webpack_require__(3684); Stream.finished = __webpack_require__(8820); Stream.pipeline = __webpack_require__(8751); // Backwards-compat with node 0.4.x Stream.Stream = Stream; // old-style streams. Note that the pipe method (the only relevant // part of this class) is overridden in the Readable class. function Stream() { EE.call(this); } Stream.prototype.pipe = function (dest, options) { var source = this; function ondata(chunk) { if (dest.writable) { if (false === dest.write(chunk) && source.pause) { source.pause(); } } } source.on('data', ondata); function ondrain() { if (source.readable && source.resume) { source.resume(); } } dest.on('drain', ondrain); // If the 'end' option is not supplied, dest.end() will be called when // source gets the 'end' or 'close' events. Only dest.end() once. if (!dest._isStdio && (!options || options.end !== false)) { source.on('end', onend); source.on('close', onclose); } var didOnEnd = false; function onend() { if (didOnEnd) return; didOnEnd = true; dest.end(); } function onclose() { if (didOnEnd) return; didOnEnd = true; if (typeof dest.destroy === 'function') dest.destroy(); } // don't leave dangling pipes when there are errors. function onerror(er) { cleanup(); if (EE.listenerCount(this, 'error') === 0) { throw er; // Unhandled stream error in pipe. } } source.on('error', onerror); dest.on('error', onerror); // remove all the event listeners that were added. function cleanup() { source.removeListener('data', ondata); dest.removeListener('drain', ondrain); source.removeListener('end', onend); source.removeListener('close', onclose); source.removeListener('error', onerror); dest.removeListener('error', onerror); source.removeListener('end', cleanup); source.removeListener('close', cleanup); dest.removeListener('close', cleanup); } source.on('end', cleanup); source.on('close', cleanup); dest.on('close', cleanup); dest.emit('pipe', source); // Allow for unix-like usage: A.pipe(B).pipe(C) return dest; }; /***/ }), /***/ 113: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /**/ var Buffer = (__webpack_require__(4368).Buffer); /**/ var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } } ; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.s = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. If an invalid byte is detected, -2 is returned. function utf8CheckByte(_byte) { if (_byte <= 0x7F) return 0;else if (_byte >> 5 === 0x06) return 2;else if (_byte >> 4 === 0x0E) return 3;else if (_byte >> 3 === 0x1E) return 4; return _byte >> 6 === 0x02 ? -1 : -2; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return "\uFFFD"; } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return "\uFFFD"; } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return "\uFFFD"; } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character is added when ending on a partial // character. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + "\uFFFD"; return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } /***/ }), /***/ 4368: /***/ ((module, exports, __webpack_require__) => { /*! safe-buffer. MIT License. Feross Aboukhadijeh */ /* eslint-disable node/no-deprecated-api */ var buffer = __webpack_require__(365); var Buffer = buffer.Buffer; // alternative to using Object.keys for old browsers function copyProps(src, dst) { for (var key in src) { dst[key] = src[key]; } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer; } else { // Copy properties from require('buffer') copyProps(buffer, exports); exports.Buffer = SafeBuffer; } function SafeBuffer(arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length); } SafeBuffer.prototype = Object.create(Buffer.prototype); // Copy static methods from Buffer copyProps(Buffer, SafeBuffer); SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number'); } return Buffer(arg, encodingOrOffset, length); }; SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number'); } var buf = Buffer(size); if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding); } else { buf.fill(fill); } } else { buf.fill(0); } return buf; }; SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number'); } return Buffer(size); }; SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number'); } return buffer.SlowBuffer(size); }; /***/ }), /***/ 8016: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** * Module exports. */ module.exports = deprecate; /** * Mark that a method should not be used. * Returns a modified function which warns once by default. * * If `localStorage.noDeprecation = true` is set, then it is a no-op. * * If `localStorage.throwDeprecation = true` is set, then deprecated functions * will throw an Error when invoked. * * If `localStorage.traceDeprecation = true` is set, then deprecated functions * will invoke `console.trace()` instead of `console.error()`. * * @param {Function} fn - the function to deprecate * @param {String} msg - the string to print to the console when `fn` is invoked * @returns {Function} a new "deprecated" version of `fn` * @api public */ function deprecate(fn, msg) { if (config('noDeprecation')) { return fn; } var warned = false; function deprecated() { if (!warned) { if (config('throwDeprecation')) { throw new Error(msg); } else if (config('traceDeprecation')) { console.trace(msg); } else { console.warn(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; } /** * Checks `localStorage` for boolean values for the given `name`. * * @param {String} name * @returns {Boolean} * @api private */ function config(name) { // accessing global.localStorage can trigger a DOMException in sandboxed iframes try { if (!__webpack_require__.g.localStorage) return false; } catch (_) { return false; } var val = __webpack_require__.g.localStorage[name]; if (null == val) return false; return String(val).toLowerCase() === 'true'; } /***/ }), /***/ 8538: /***/ ((module) => { function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } module.exports = function isBuffer(arg) { return arg && _typeof(arg) === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; }; /***/ }), /***/ 9957: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; // Currently in sync with Node.js lib/internal/util/types.js // https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var isArgumentsObject = __webpack_require__(2755); var isGeneratorFunction = __webpack_require__(6738); var whichTypedArray = __webpack_require__(1482); var isTypedArray = __webpack_require__(7913); function uncurryThis(f) { return f.call.bind(f); } var BigIntSupported = typeof BigInt !== 'undefined'; var SymbolSupported = typeof Symbol !== 'undefined'; var ObjectToString = uncurryThis(Object.prototype.toString); var numberValue = uncurryThis(Number.prototype.valueOf); var stringValue = uncurryThis(String.prototype.valueOf); var booleanValue = uncurryThis(Boolean.prototype.valueOf); if (BigIntSupported) { var bigIntValue = uncurryThis(BigInt.prototype.valueOf); } if (SymbolSupported) { var symbolValue = uncurryThis(Symbol.prototype.valueOf); } function checkBoxedPrimitive(value, prototypeValueOf) { if (_typeof(value) !== 'object') { return false; } try { prototypeValueOf(value); return true; } catch (e) { return false; } } exports.isArgumentsObject = isArgumentsObject; exports.isGeneratorFunction = isGeneratorFunction; exports.isTypedArray = isTypedArray; // Taken from here and modified for better browser support // https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js function isPromise(input) { return typeof Promise !== 'undefined' && input instanceof Promise || input !== null && _typeof(input) === 'object' && typeof input.then === 'function' && typeof input["catch"] === 'function'; } exports.isPromise = isPromise; function isArrayBufferView(value) { if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { return ArrayBuffer.isView(value); } return isTypedArray(value) || isDataView(value); } exports.isArrayBufferView = isArrayBufferView; function isUint8Array(value) { return whichTypedArray(value) === 'Uint8Array'; } exports.isUint8Array = isUint8Array; function isUint8ClampedArray(value) { return whichTypedArray(value) === 'Uint8ClampedArray'; } exports.isUint8ClampedArray = isUint8ClampedArray; function isUint16Array(value) { return whichTypedArray(value) === 'Uint16Array'; } exports.isUint16Array = isUint16Array; function isUint32Array(value) { return whichTypedArray(value) === 'Uint32Array'; } exports.isUint32Array = isUint32Array; function isInt8Array(value) { return whichTypedArray(value) === 'Int8Array'; } exports.isInt8Array = isInt8Array; function isInt16Array(value) { return whichTypedArray(value) === 'Int16Array'; } exports.isInt16Array = isInt16Array; function isInt32Array(value) { return whichTypedArray(value) === 'Int32Array'; } exports.isInt32Array = isInt32Array; function isFloat32Array(value) { return whichTypedArray(value) === 'Float32Array'; } exports.isFloat32Array = isFloat32Array; function isFloat64Array(value) { return whichTypedArray(value) === 'Float64Array'; } exports.isFloat64Array = isFloat64Array; function isBigInt64Array(value) { return whichTypedArray(value) === 'BigInt64Array'; } exports.isBigInt64Array = isBigInt64Array; function isBigUint64Array(value) { return whichTypedArray(value) === 'BigUint64Array'; } exports.isBigUint64Array = isBigUint64Array; function isMapToString(value) { return ObjectToString(value) === '[object Map]'; } isMapToString.working = typeof Map !== 'undefined' && isMapToString(new Map()); function isMap(value) { if (typeof Map === 'undefined') { return false; } return isMapToString.working ? isMapToString(value) : value instanceof Map; } exports.isMap = isMap; function isSetToString(value) { return ObjectToString(value) === '[object Set]'; } isSetToString.working = typeof Set !== 'undefined' && isSetToString(new Set()); function isSet(value) { if (typeof Set === 'undefined') { return false; } return isSetToString.working ? isSetToString(value) : value instanceof Set; } exports.isSet = isSet; function isWeakMapToString(value) { return ObjectToString(value) === '[object WeakMap]'; } isWeakMapToString.working = typeof WeakMap !== 'undefined' && isWeakMapToString(new WeakMap()); function isWeakMap(value) { if (typeof WeakMap === 'undefined') { return false; } return isWeakMapToString.working ? isWeakMapToString(value) : value instanceof WeakMap; } exports.isWeakMap = isWeakMap; function isWeakSetToString(value) { return ObjectToString(value) === '[object WeakSet]'; } isWeakSetToString.working = typeof WeakSet !== 'undefined' && isWeakSetToString(new WeakSet()); function isWeakSet(value) { return isWeakSetToString(value); } exports.isWeakSet = isWeakSet; function isArrayBufferToString(value) { return ObjectToString(value) === '[object ArrayBuffer]'; } isArrayBufferToString.working = typeof ArrayBuffer !== 'undefined' && isArrayBufferToString(new ArrayBuffer()); function isArrayBuffer(value) { if (typeof ArrayBuffer === 'undefined') { return false; } return isArrayBufferToString.working ? isArrayBufferToString(value) : value instanceof ArrayBuffer; } exports.isArrayBuffer = isArrayBuffer; function isDataViewToString(value) { return ObjectToString(value) === '[object DataView]'; } isDataViewToString.working = typeof ArrayBuffer !== 'undefined' && typeof DataView !== 'undefined' && isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)); function isDataView(value) { if (typeof DataView === 'undefined') { return false; } return isDataViewToString.working ? isDataViewToString(value) : value instanceof DataView; } exports.isDataView = isDataView; // Store a copy of SharedArrayBuffer in case it's deleted elsewhere var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; function isSharedArrayBufferToString(value) { return ObjectToString(value) === '[object SharedArrayBuffer]'; } function isSharedArrayBuffer(value) { if (typeof SharedArrayBufferCopy === 'undefined') { return false; } if (typeof isSharedArrayBufferToString.working === 'undefined') { isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); } return isSharedArrayBufferToString.working ? isSharedArrayBufferToString(value) : value instanceof SharedArrayBufferCopy; } exports.isSharedArrayBuffer = isSharedArrayBuffer; function isAsyncFunction(value) { return ObjectToString(value) === '[object AsyncFunction]'; } exports.isAsyncFunction = isAsyncFunction; function isMapIterator(value) { return ObjectToString(value) === '[object Map Iterator]'; } exports.isMapIterator = isMapIterator; function isSetIterator(value) { return ObjectToString(value) === '[object Set Iterator]'; } exports.isSetIterator = isSetIterator; function isGeneratorObject(value) { return ObjectToString(value) === '[object Generator]'; } exports.isGeneratorObject = isGeneratorObject; function isWebAssemblyCompiledModule(value) { return ObjectToString(value) === '[object WebAssembly.Module]'; } exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; function isNumberObject(value) { return checkBoxedPrimitive(value, numberValue); } exports.isNumberObject = isNumberObject; function isStringObject(value) { return checkBoxedPrimitive(value, stringValue); } exports.isStringObject = isStringObject; function isBooleanObject(value) { return checkBoxedPrimitive(value, booleanValue); } exports.isBooleanObject = isBooleanObject; function isBigIntObject(value) { return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); } exports.isBigIntObject = isBigIntObject; function isSymbolObject(value) { return SymbolSupported && checkBoxedPrimitive(value, symbolValue); } exports.isSymbolObject = isSymbolObject; function isBoxedPrimitive(value) { return isNumberObject(value) || isStringObject(value) || isBooleanObject(value) || isBigIntObject(value) || isSymbolObject(value); } exports.isBoxedPrimitive = isBoxedPrimitive; function isAnyArrayBuffer(value) { return typeof Uint8Array !== 'undefined' && (isArrayBuffer(value) || isSharedArrayBuffer(value)); } exports.isAnyArrayBuffer = isAnyArrayBuffer; ['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function (method) { Object.defineProperty(exports, method, { enumerable: false, value: function value() { throw new Error(method + ' is not supported in userland'); } }); }); /***/ }), /***/ 161: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } // 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 getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(obj) { var keys = Object.keys(obj); var descriptors = {}; for (var i = 0; i < keys.length; i++) { descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); } return descriptors; }; var formatRegExp = /%[sdj%]/g; exports.format = function (f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function (x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function (fn, msg) { if (typeof ({env:{}}) !== 'undefined' && ({env:{}}).noDeprecation === true) { return fn; } // Allow for deprecating things in the process of starting up. if (typeof ({env:{}}) === 'undefined') { return function () { return exports.deprecate(fn, msg).apply(this, arguments); }; } var warned = false; function deprecated() { if (!warned) { if (({env:{}}).throwDeprecation) { throw new Error(msg); } else if (({env:{}}).traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnvRegex = /^$/; if (({env:{}}).env.NODE_DEBUG) { var debugEnv = ({env:{}}).env.NODE_DEBUG; debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&').replace(/\*/g, '.*').replace(/,/g, '$|^').toUpperCase(); debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); } exports.debuglog = function (set) { set = set.toUpperCase(); if (!debugs[set]) { if (debugEnvRegex.test(set)) { var pid = ({env:{}}).pid; debugs[set] = function () { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function () {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold': [1, 22], 'italic': [3, 23], 'underline': [4, 24], 'inverse': [7, 27], 'white': [37, 39], 'grey': [90, 39], 'black': [30, 39], 'blue': [34, 39], 'cyan': [36, 39], 'green': [32, 39], 'magenta': [35, 39], 'red': [31, 39], 'yellow': [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return "\x1B[" + inspect.colors[style][0] + 'm' + str + "\x1B[" + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function (val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function (key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, "\\'").replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function (key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function (line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function (line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function (prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. exports.types = __webpack_require__(9957); function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return _typeof(arg) === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; exports.types.isRegExp = isRegExp; function isObject(arg) { return _typeof(arg) === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; exports.types.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; exports.types.isNativeError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || _typeof(arg) === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = __webpack_require__(8538); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function () { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = __webpack_require__(376); exports._extend = function (origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; exports.promisify = function promisify(original) { if (typeof original !== 'function') throw new TypeError('The "original" argument must be of type Function'); if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { var fn = original[kCustomPromisifiedSymbol]; if (typeof fn !== 'function') { throw new TypeError('The "util.promisify.custom" argument must be of type Function'); } Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); return fn; } function fn() { var promiseResolve, promiseReject; var promise = new Promise(function (resolve, reject) { promiseResolve = resolve; promiseReject = reject; }); var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } args.push(function (err, value) { if (err) { promiseReject(err); } else { promiseResolve(value); } }); try { original.apply(this, args); } catch (err) { promiseReject(err); } return promise; } Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); return Object.defineProperties(fn, getOwnPropertyDescriptors(original)); }; exports.promisify.custom = kCustomPromisifiedSymbol; function callbackifyOnRejected(reason, cb) { // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). // Because `null` is a special error value in callbacks which means "no error // occurred", we error-wrap so the callback consumer can distinguish between // "the promise rejected with null" or "the promise fulfilled with undefined". if (!reason) { var newReason = new Error('Promise was rejected with a falsy value'); newReason.reason = reason; reason = newReason; } return cb(reason); } function callbackify(original) { if (typeof original !== 'function') { throw new TypeError('The "original" argument must be of type Function'); } // We DO NOT return the promise as it gives the user a false sense that // the promise is actually somehow related to the callback's execution // and that the callback throwing will reject the promise. function callbackified() { var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } var maybeCb = args.pop(); if (typeof maybeCb !== 'function') { throw new TypeError('The last argument must be of type Function'); } var self = this; var cb = function cb() { return maybeCb.apply(self, arguments); }; // In true node style we process the callback on `nextTick` with all the // implications (stack, `uncaughtException`, `async_hooks`) original.apply(this, args).then(function (ret) { ({env:{}}).nextTick(cb.bind(null, null, ret)); }, function (rej) { ({env:{}}).nextTick(callbackifyOnRejected.bind(null, rej, cb)); }); } Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); Object.defineProperties(callbackified, getOwnPropertyDescriptors(original)); return callbackified; } exports.callbackify = callbackify; /***/ }), /***/ 1482: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var forEach = __webpack_require__(5337); var availableTypedArrays = __webpack_require__(6461); var callBound = __webpack_require__(8780); var $toString = callBound('Object.prototype.toString'); var hasToStringTag = __webpack_require__(5994)(); var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; var typedArrays = availableTypedArrays(); var $slice = callBound('String.prototype.slice'); var toStrTags = {}; var gOPD = __webpack_require__(3999); var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); if (hasToStringTag && gOPD && getPrototypeOf) { forEach(typedArrays, function (typedArray) { if (typeof g[typedArray] === 'function') { var arr = new g[typedArray](); if (Symbol.toStringTag in arr) { var proto = getPrototypeOf(arr); var descriptor = gOPD(proto, Symbol.toStringTag); if (!descriptor) { var superProto = getPrototypeOf(proto); descriptor = gOPD(superProto, Symbol.toStringTag); } toStrTags[typedArray] = descriptor.get; } } }); } var tryTypedArrays = function tryAllTypedArrays(value) { var foundName = false; forEach(toStrTags, function (getter, typedArray) { if (!foundName) { try { var name = getter.call(value); if (name === typedArray) { foundName = name; } } catch (e) {} } }); return foundName; }; var isTypedArray = __webpack_require__(7913); module.exports = function whichTypedArray(value) { if (!isTypedArray(value)) { return false; } if (!hasToStringTag || !(Symbol.toStringTag in value)) { return $slice($toString(value), 8, -1); } return tryTypedArrays(value); }; /***/ }), /***/ 6601: /***/ (() => { /* (ignored) */ /***/ }), /***/ 9214: /***/ (() => { /* (ignored) */ /***/ }), /***/ 2361: /***/ (() => { /* (ignored) */ /***/ }), /***/ 4616: /***/ (() => { /* (ignored) */ /***/ }), /***/ 6461: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var possibleNames = ['BigInt64Array', 'BigUint64Array', 'Float32Array', 'Float64Array', 'Int16Array', 'Int32Array', 'Int8Array', 'Uint16Array', 'Uint32Array', 'Uint8Array', 'Uint8ClampedArray']; var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis; module.exports = function availableTypedArrays() { var out = []; for (var i = 0; i < possibleNames.length; i++) { if (typeof g[possibleNames[i]] === 'function') { out[out.length] = possibleNames[i]; } } return out; }; /***/ }), /***/ 3999: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var GetIntrinsic = __webpack_require__(6893); var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); if ($gOPD) { try { $gOPD([], 'length'); } catch (e) { // IE 8 has a broken gOPD $gOPD = null; } } module.exports = $gOPD; /***/ }), /***/ 4946: /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"aes-128-ecb":{"cipher":"AES","key":128,"iv":0,"mode":"ECB","type":"block"},"aes-192-ecb":{"cipher":"AES","key":192,"iv":0,"mode":"ECB","type":"block"},"aes-256-ecb":{"cipher":"AES","key":256,"iv":0,"mode":"ECB","type":"block"},"aes-128-cbc":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes-192-cbc":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes-256-cbc":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes128":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes192":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes256":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes-128-cfb":{"cipher":"AES","key":128,"iv":16,"mode":"CFB","type":"stream"},"aes-192-cfb":{"cipher":"AES","key":192,"iv":16,"mode":"CFB","type":"stream"},"aes-256-cfb":{"cipher":"AES","key":256,"iv":16,"mode":"CFB","type":"stream"},"aes-128-cfb8":{"cipher":"AES","key":128,"iv":16,"mode":"CFB8","type":"stream"},"aes-192-cfb8":{"cipher":"AES","key":192,"iv":16,"mode":"CFB8","type":"stream"},"aes-256-cfb8":{"cipher":"AES","key":256,"iv":16,"mode":"CFB8","type":"stream"},"aes-128-cfb1":{"cipher":"AES","key":128,"iv":16,"mode":"CFB1","type":"stream"},"aes-192-cfb1":{"cipher":"AES","key":192,"iv":16,"mode":"CFB1","type":"stream"},"aes-256-cfb1":{"cipher":"AES","key":256,"iv":16,"mode":"CFB1","type":"stream"},"aes-128-ofb":{"cipher":"AES","key":128,"iv":16,"mode":"OFB","type":"stream"},"aes-192-ofb":{"cipher":"AES","key":192,"iv":16,"mode":"OFB","type":"stream"},"aes-256-ofb":{"cipher":"AES","key":256,"iv":16,"mode":"OFB","type":"stream"},"aes-128-ctr":{"cipher":"AES","key":128,"iv":16,"mode":"CTR","type":"stream"},"aes-192-ctr":{"cipher":"AES","key":192,"iv":16,"mode":"CTR","type":"stream"},"aes-256-ctr":{"cipher":"AES","key":256,"iv":16,"mode":"CTR","type":"stream"},"aes-128-gcm":{"cipher":"AES","key":128,"iv":12,"mode":"GCM","type":"auth"},"aes-192-gcm":{"cipher":"AES","key":192,"iv":12,"mode":"GCM","type":"auth"},"aes-256-gcm":{"cipher":"AES","key":256,"iv":12,"mode":"GCM","type":"auth"}}'); /***/ }), /***/ 5207: /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"sha224WithRSAEncryption":{"sign":"rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"RSA-SHA224":{"sign":"ecdsa/rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"sha256WithRSAEncryption":{"sign":"rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"RSA-SHA256":{"sign":"ecdsa/rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"sha384WithRSAEncryption":{"sign":"rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"RSA-SHA384":{"sign":"ecdsa/rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"sha512WithRSAEncryption":{"sign":"rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA512":{"sign":"ecdsa/rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA1":{"sign":"rsa","hash":"sha1","id":"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{"sign":"ecdsa","hash":"sha1","id":""},"sha256":{"sign":"ecdsa","hash":"sha256","id":""},"sha224":{"sign":"ecdsa","hash":"sha224","id":""},"sha384":{"sign":"ecdsa","hash":"sha384","id":""},"sha512":{"sign":"ecdsa","hash":"sha512","id":""},"DSA-SHA":{"sign":"dsa","hash":"sha1","id":""},"DSA-SHA1":{"sign":"dsa","hash":"sha1","id":""},"DSA":{"sign":"dsa","hash":"sha1","id":""},"DSA-WITH-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-WITH-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-WITH-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-WITH-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-RIPEMD160":{"sign":"dsa","hash":"rmd160","id":""},"ripemd160WithRSA":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"RSA-RIPEMD160":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"md5WithRSAEncryption":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"},"RSA-MD5":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"}}'); /***/ }), /***/ 1308: /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}'); /***/ }), /***/ 9799: /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"modp1":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},"modp2":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},"modp5":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},"modp14":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},"modp15":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},"modp16":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},"modp17":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},"modp18":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}'); /***/ }), /***/ 8597: /***/ ((module) => { "use strict"; module.exports = {"i8":"6.5.4"}; /***/ }), /***/ 2562: /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}'); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_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] = { /******/ id: moduleId, /******/ loaded: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/global */ /******/ (() => { /******/ __webpack_require__.g = (function() { /******/ if (typeof globalThis === 'object') return globalThis; /******/ try { /******/ return this || new Function('return this')(); /******/ } catch (e) { /******/ if (typeof window === 'object') return window; /******/ } /******/ })(); /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/node module decorator */ /******/ (() => { /******/ __webpack_require__.nmd = (module) => { /******/ module.paths = []; /******/ if (!module.children) module.children = []; /******/ return module; /******/ }; /******/ })(); /******/ /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module used 'module' so it can't be inlined /******/ var __webpack_exports__ = __webpack_require__(5507); /******/ /******/ return __webpack_exports__; /******/ })() ; });